rok_ui_macros/lib.rs
1//! Procedural macros for `rok-ui`: entry points only.
2//!
3//! Parsing and code generation live in `rok-ui-grammar`, where they are unit-tested; each
4//! macro here forwards its tokens and turns errors into `compile_error!`.
5
6use proc_macro::TokenStream;
7use rok_ui_grammar::{
8 children, component, file_route, form_values, procedure, search, store, styles,
9};
10
11/// Turn an expansion result into tokens, errors included.
12fn expansion(result: syn::Result<proc_macro2::TokenStream>) -> TokenStream {
13 result
14 .unwrap_or_else(|error| error.to_compile_error())
15 .into()
16}
17
18/// Turn a function into a reusable component, React style.
19///
20/// ```no_run
21/// use rok_ui::prelude::*;
22///
23/// /// A greeting card.
24/// #[component]
25/// pub fn Greeting(
26/// name: SharedString,
27/// #[default] excited: bool,
28/// #[default] on_wave: Option<EventHandler<ClickEvent>>,
29/// #[children] children: Vec<AnyElement>,
30/// window: &mut Window,
31/// cx: &mut App,
32/// ) -> impl IntoElement {
33/// div().child(format!("Hello, {name}{}", if excited { "!" } else { "." })).children(children)
34/// }
35///
36/// // Usage: required props go to `new`, optional props are builder methods,
37/// // children use the familiar `.child(..)`.
38/// let greeting = Greeting::new("Ada").excited(true).on_wave(|_, _, _| {}).child("Welcome back");
39/// ```
40///
41/// Parameter rules:
42/// - A parameter named `window` or `cx` receives the GPUI window or app context.
43/// `cx: &mut Cx` receives both as one [`Cx`](../rok_ui/struct.Cx.html) handle instead
44/// (then there is no `window` parameter).
45/// - Plain parameters are required props and become arguments of `new(..)` (taking `impl Into<T>`).
46/// - `#[default]` parameters start at `Default::default()`, `#[default(expr)]` ones at `expr`,
47/// and get a builder method with the same name. For `Option<T>` the method takes
48/// `impl Into<T>`. `#[prop(optional)]` is the older spelling of `#[default]`.
49/// - Props of type `EventHandler<E>` (or `Option<EventHandler<E>>`) take a closure
50/// `Fn(&E, &mut Window, &mut App)` directly.
51/// - One `#[children]` parameter of type `Vec<AnyElement>` makes the component a
52/// `ParentElement`, so `.child(..)` and `.children(..)` work.
53/// - One `#[style]` parameter of type `StyleRefinement` makes the component `Styled`,
54/// so callers can chain `.w_full()`, `.mt_4()`, … like a `className`. Apply it in
55/// the body with `.apply_style_overrides(&style_overrides)`.
56/// - One `#[sx] sx: Sx` parameter makes the component accept `.sx(..)` styles
57/// (`StyleX`'s `xstyle`). Apply them last in the body: `.sx((&MY_STYLES.base, &sx))`.
58#[proc_macro_attribute]
59pub fn component(attribute_arguments: TokenStream, item: TokenStream) -> TokenStream {
60 expansion(component::expand(attribute_arguments.into(), item.into()))
61}
62
63/// Declare the route in a route file under `src/routes/` (see `rok_ui::routes!`).
64///
65/// Keys: `params: { id: u64 }` (types of the path's `$` parameters), `search: Type`,
66/// `component: Page` or `layout: Layout` (a layout renders its child route as its children),
67/// `before_load: |location, cx| ..` (a guard returning `Result<(), RouteControl>`), and on
68/// pages `loader: |route: &Route, cx| ..` (starts loading data before the page renders).
69#[proc_macro]
70pub fn file_route(input: TokenStream) -> TokenStream {
71 expansion(file_route::expand_file_route(input.into()))
72}
73
74/// Implement `rok_ui::form::FormValues` and add a typed field constant per struct field:
75/// `email: String` becomes `pub const EMAIL: Field<Self, String>`.
76#[proc_macro_derive(FormValues)]
77pub fn derive_form_values(input: TokenStream) -> TokenStream {
78 expansion(form_values::expand_form_values(input.into()))
79}
80
81/// Generate `NameStore`, a fine-grained store with one signal per field (`state` feature):
82/// `store.title()` reads (and tracks) only `title`, `store.set_title(..)` re-renders only its
83/// readers, and `store.get()` / `store.set(..)` work on the whole value.
84#[proc_macro_derive(Store)]
85pub fn derive_store(input: TokenStream) -> TokenStream {
86 expansion(store::expand_store(input.into()))
87}
88
89/// Implement `rok_ui::router::Search` for a struct of query parameters.
90///
91/// Field attributes: `#[search(default = expr)]` (the value when missing or invalid; otherwise
92/// `Default::default()`), `#[search(rename = "p")]` (the query key). `Option` fields are `None`
93/// when missing.
94#[proc_macro_derive(Search, attributes(search))]
95pub fn derive_search(input: TokenStream) -> TokenStream {
96 expansion(search::expand_search(input.into()))
97}
98
99/// Declare a typed async command: a [`Procedure`](../rok_ui/query/trait.Procedure.html) with
100/// optional queries to invalidate after it succeeds.
101///
102/// The function is `async`, takes an optional `TaskCx` and one input, and returns
103/// `Result<Output, Error>`. The attribute turns it into a unit struct of the same name that
104/// implements `Procedure`, for `use_procedure(cx, create_note)` or `create_note.call(cx, input)`.
105///
106/// ```no_run
107/// # use rok_ui::{procedure, query::TaskCx, query_key};
108/// # #[derive(Clone)] struct NewNote { title: String }
109/// # struct Note { title: String }
110/// # #[derive(Debug)] enum NoteError { Empty }
111/// #[procedure(invalidates = [query_key!["notes"]])]
112/// async fn create_note(cx: TaskCx, input: NewNote) -> Result<Note, NoteError> {
113/// if input.title.is_empty() {
114/// return Err(NoteError::Empty);
115/// }
116/// Ok(Note { title: input.title })
117/// }
118/// ```
119#[proc_macro_attribute]
120pub fn procedure(arguments: TokenStream, item: TokenStream) -> TokenStream {
121 expansion(procedure::expand_procedure(arguments.into(), item.into()))
122}
123
124/// Memoize an async function: calls with the same arguments share one in-flight future and its
125/// result, until `rok_ui::query::memo::invalidate` forgets it. Arguments are owned and `Debug`
126/// (they form the cache key); the output is `Clone + Send + Sync`.
127///
128/// `#[memoize(scope = navigation)]` keeps results until the next navigation, and
129/// `#[memoize(ttl_ms = 5000)]` for that long after the work started.
130///
131/// ```no_run
132/// # use rok_ui::{memoize, query::TaskCx};
133/// # #[derive(Clone)] struct User;
134/// # async fn load_session(_: &TaskCx) -> Option<User> { None }
135/// #[memoize]
136/// async fn current_user(cx: TaskCx) -> Option<User> {
137/// load_session(&cx).await
138/// }
139/// ```
140#[proc_macro_attribute]
141pub fn memoize(arguments: TokenStream, item: TokenStream) -> TokenStream {
142 expansion(procedure::expand_memoize(arguments.into(), item.into()))
143}
144
145/// Define StyleX-style style objects once, at module level.
146///
147/// ```no_run
148/// # use rok_ui::prelude::*;
149/// styles! {
150/// pub CARD = {
151/// base: {
152/// display: flex, direction: column, gap: 6, padding: 6,
153/// radius: xl, border: 1, border_color: border, background: card,
154/// hover: { border_color: ring },
155/// },
156/// compact: { padding: 3, gap: 3 },
157/// variant(ButtonVariant): {
158/// Primary: { background: primary, color: primary_foreground },
159/// Destructive: { background: destructive },
160/// Outline: { border: 1, border_color: input },
161/// Secondary: { background: secondary },
162/// Ghost: { background: transparent },
163/// Link: { color: primary },
164/// },
165/// }
166/// }
167///
168/// # fn example(compact: bool, variant: ButtonVariant) {
169/// let card = div().sx((&CARD.base, compact.then_some(&CARD.compact), CARD.variant(variant)));
170/// # }
171/// ```
172///
173/// Each object becomes a static (`CARD`) with one `Sx` field per key and one
174/// lookup method per variant table. Values:
175/// - lengths: numbers are multiples of 4px (`gap: 6` is 24px); also `50%`,
176/// `full`, `auto`, or any expression (`px(10.)`, `{width}`);
177/// - colors: theme tokens (`primary`, `muted_foreground`), with opacity
178/// (`primary/90`), `transparent`, or an expression;
179/// - radius: `none`, `sm`, `md`, `lg`, `xl`, `full`, or a length;
180/// - `hover`, `focus` and `active` blocks style interaction states.
181#[proc_macro]
182pub fn styles(input: TokenStream) -> TokenStream {
183 expansion(styles::expand_styles(input.into()))
184}
185
186/// One inline style object, for one-off or dynamic values:
187/// `style! { width: {px(width)}, background: primary/90 }`.
188#[proc_macro]
189pub fn style(input: TokenStream) -> TokenStream {
190 expansion(styles::expand_style(input.into()))
191}
192
193/// A `Vec<AnyElement>` from mixed element types, with control flow:
194///
195/// ```no_run
196/// # use rok_ui::prelude::*;
197/// # struct Project { id: usize, name: SharedString }
198/// # enum Status { Ok, Stale }
199/// # fn example(loading: bool, projects: Vec<Project>, status: Status) {
200/// let list = div().children(children![
201/// H3::new("Projects"),
202/// if loading { Spinner::new() } else { Badge::new("Ready") },
203/// for project in &projects => Item::new(project.id).title(project.name.clone()),
204/// match status { Status::Ok => "Up to date", Status::Stale => Button::new("refresh") },
205/// "plain text",
206/// ]);
207/// # }
208/// ```
209#[proc_macro]
210pub fn children(input: TokenStream) -> TokenStream {
211 expansion(children::expand_children(input.into()))
212}
213
214/// JSX-like markup compiled to builder calls.
215///
216/// ```no_run
217/// # use rok_ui::prelude::*;
218/// # styles! { CARD = { base: { padding: 6 }, compact: { padding: 3 } } ROW = { end: { justify: end } } }
219/// # struct Project { id: usize, name: SharedString }
220/// # fn example(compact: bool, error: Option<SharedString>, projects: Vec<Project>, some_element: Div) {
221/// let card = view! {
222/// Card(sx = [CARD.base, compact => CARD.compact]) {
223/// CardHeader {
224/// CardTitle("Create project")
225/// CardDescription("Deploy your new project in one click.")
226/// }
227/// if let Some(error) = error {
228/// Alert("Deploy failed", description = error).destructive()
229/// }
230/// for project in &projects {
231/// Item(project.id, title = project.name.clone())
232/// }
233/// div(sx = ROW.end) { "Raw text" {some_element} }
234/// }
235/// };
236/// # }
237/// ```
238///
239/// - `Name(a, b, key = value)` is `Name::new(a, b).key(value)`; lowercase
240/// `div(..)`, `img(src)` and `svg()` are GPUI element functions.
241/// - `sx = [a, cond => b]` merges styles like `sx![..]`; `sx = expr` passes one.
242/// - `.method(..)` after the arguments is passed through unchanged.
243/// - `{ .. }` after an element holds its children: elements, `"text"`,
244/// `{expr}`, `if` / `if let` / `match` / `for`.
245#[proc_macro]
246pub fn view(input: TokenStream) -> TokenStream {
247 expansion(children::expand_view(input.into()))
248}
249
250/// Define keyframe sequences for [`Motion`](../rok_ui/motion/struct.Motion.html).
251///
252/// ```no_run
253/// # use rok_ui::prelude::*;
254/// keyframes! {
255/// pub FADE_UP = {
256/// from: { opacity: 0, y: 2 },
257/// 60%: { opacity: 1 },
258/// to: { y: 0, background: card },
259/// }
260/// }
261///
262/// # fn example() {
263/// let card = div().motion("enter", Motion::new(&FADE_UP).duration_ms(250).easing(Easing::EaseOut));
264/// # }
265/// ```
266///
267/// Offsets are `from`, `to` or percentages. Animatable properties: `opacity`,
268/// `x` / `y` (offsets from the laid-out position), `width`, `height`, `radius`,
269/// `background`, `color` and `border_color`, with the same values as `styles!`.
270#[proc_macro]
271pub fn keyframes(input: TokenStream) -> TokenStream {
272 expansion(styles::expand_keyframes(input.into()))
273}