Skip to main content

laravel_rust_admin/
protocol.rs

1//! What the panel's server and its browser app say to each other: every request and response body
2//! of the panel's JSON API.
3//!
4//! Each type here is plain data with a twin in `frontend/src/api/types.ts`. The twins are kept in
5//! step by hand for now. They are meant to be generated from these types by
6//! `laravel-rust-typescript-bridge`, which is why nothing here borrows or holds a closure.
7
8// The builders in `schema` and `widget` document what each of these fields means. The types here
9// only carry the values to the browser.
10#![allow(missing_docs)]
11
12use std::collections::BTreeMap;
13
14use laravel::validation::Validate;
15use serde::{Deserialize, Serialize};
16
17/// The color of the panel's primary buttons, checked controls, and brand mark. `Zinc`, the
18/// default, is near-black on a light page and white on a dark one.
19#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21pub enum AccentColor {
22    #[default]
23    Zinc,
24    Indigo,
25    Blue,
26    Emerald,
27    Amber,
28    Rose,
29    Violet,
30}
31
32impl AccentColor {
33    /// The accent's name, as the panel's stylesheet spells it.
34    #[must_use]
35    pub const fn as_str(self) -> &'static str {
36        match self {
37            Self::Zinc => "zinc",
38            Self::Indigo => "indigo",
39            Self::Blue => "blue",
40            Self::Emerald => "emerald",
41            Self::Amber => "amber",
42            Self::Rose => "rose",
43            Self::Violet => "violet",
44        }
45    }
46}
47
48/// Badge color token used for status pills, sidebar badges, and deltas.
49#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(rename_all = "snake_case")]
51pub enum BadgeColor {
52    #[default]
53    Zinc,
54    Emerald,
55    Amber,
56    Rose,
57    Sky,
58    Indigo,
59    Violet,
60}
61
62/// Sort direction for table queries.
63#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(rename_all = "snake_case")]
65pub enum SortDirection {
66    #[default]
67    Asc,
68    Desc,
69}
70
71/// Initial bootstrap payload injected into the HTML shell so the SPA knows its mount path
72/// before its first API call.
73#[derive(Debug, Clone, Serialize, Deserialize)]
74pub struct ShellBootstrap {
75    pub base_path: String,
76    pub api_base: String,
77    pub brand: String,
78    pub subtitle: Option<String>,
79    pub accent: AccentColor,
80    pub logout_url: Option<String>,
81}
82
83/// Information about the currently signed-in admin user shown in the sidebar footer & dashboard greeting.
84#[derive(Debug, Clone, Serialize, Deserialize)]
85pub struct AdminUserDto {
86    pub name: String,
87    pub email: Option<String>,
88    pub avatar_url: Option<String>,
89    pub role: Option<String>,
90}
91
92/// Sidebar badge displayed next to a resource item (e.g. unread count).
93#[derive(Debug, Clone, Serialize, Deserialize)]
94pub struct NavigationBadgeDto {
95    pub label: String,
96    pub color: BadgeColor,
97}
98
99/// Effective permissions for the current user on a resource.
100#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
101pub struct ResourcePermissionsDto {
102    pub view_any: bool,
103    pub create: bool,
104    pub edit: bool,
105    pub delete: bool,
106}
107
108/// Full panel schema returned by `GET {base}/api/panel`.
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct PanelSchemaResponse {
111    pub brand: String,
112    pub subtitle: Option<String>,
113    pub base_path: String,
114    pub accent: AccentColor,
115    pub logout_url: Option<String>,
116    pub user: Option<AdminUserDto>,
117    pub resources: Vec<ResourceSchemaDto>,
118}
119
120/// Complete schema describing one admin resource (navigation, table, form, actions, permissions).
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct ResourceSchemaDto {
123    pub slug: String,
124    pub label: String,
125    pub plural_label: String,
126    pub icon: String,
127    pub navigation_group: Option<String>,
128    pub navigation_sort: i32,
129    pub navigation_badge: Option<NavigationBadgeDto>,
130    pub key_column: String,
131    pub title_column: Option<String>,
132    pub permissions: ResourcePermissionsDto,
133    pub per_page_options: Vec<u64>,
134    pub default_per_page: u64,
135    pub searchable: bool,
136    pub exportable: bool,
137    pub default_sort: Option<DefaultSortDto>,
138    pub columns: Vec<ColumnSchemaDto>,
139    pub filters: Vec<FilterSchemaDto>,
140    pub tabs: Vec<TableTabSchemaDto>,
141    pub row_actions: Vec<ActionSchemaDto>,
142    pub bulk_actions: Vec<ActionSchemaDto>,
143    pub form_sections: Vec<FormSectionSchemaDto>,
144}
145
146/// Default sort configuration for a resource table.
147#[derive(Debug, Clone, Serialize, Deserialize)]
148pub struct DefaultSortDto {
149    pub column: String,
150    pub direction: SortDirection,
151}
152
153/// Column renderer kind.
154#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
155#[serde(rename_all = "snake_case")]
156pub enum ColumnKind {
157    #[default]
158    Text,
159    Badge,
160    Boolean,
161    Number,
162    Currency,
163    Datetime,
164    Date,
165    RelativeTime,
166    Avatar,
167    Tags,
168    Json,
169}
170
171/// Column horizontal alignment.
172#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
173#[serde(rename_all = "snake_case")]
174pub enum ColumnAlign {
175    #[default]
176    Left,
177    Center,
178    Right,
179}
180
181/// Schema for a single table column.
182#[derive(Debug, Clone, Serialize, Deserialize)]
183pub struct ColumnSchemaDto {
184    pub name: String,
185    pub label: String,
186    pub kind: ColumnKind,
187    pub align: ColumnAlign,
188    pub sortable: bool,
189    pub searchable: bool,
190    pub toggleable: bool,
191    pub hidden_by_default: bool,
192    pub copyable: bool,
193    pub mono: bool,
194    pub prefix: Option<String>,
195    pub suffix: Option<String>,
196    pub currency: Option<String>,
197    pub description_column: Option<String>,
198    pub limit: Option<usize>,
199    pub badge_colors: BTreeMap<String, BadgeColor>,
200    pub badge_dot: bool,
201}
202
203/// Option for select/radio inputs and filters.
204#[derive(Debug, Clone, Serialize, Deserialize)]
205pub struct SelectOptionDto {
206    pub value: String,
207    pub label: String,
208    pub description: Option<String>,
209}
210
211/// Filter control type.
212#[derive(Debug, Clone, Serialize, Deserialize)]
213#[serde(tag = "kind", rename_all = "snake_case")]
214pub enum FilterKindDto {
215    Select { options: Vec<SelectOptionDto> },
216    Boolean { true_label: String, false_label: String },
217    DateRange,
218    Text { placeholder: Option<String> },
219}
220
221/// Schema for one table filter chip.
222#[derive(Debug, Clone, Serialize, Deserialize)]
223pub struct FilterSchemaDto {
224    pub name: String,
225    pub label: String,
226    pub control: FilterKindDto,
227}
228
229/// A tab above a resource's table.
230#[derive(Debug, Clone, Serialize, Deserialize)]
231pub struct TableTabSchemaDto {
232    pub key: String,
233    pub label: String,
234    pub badge_color: Option<BadgeColor>,
235}
236
237/// Form input field kind.
238#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
239#[serde(rename_all = "snake_case")]
240pub enum FieldKind {
241    #[default]
242    Text,
243    Email,
244    Url,
245    Password,
246    Textarea,
247    Number,
248    Decimal,
249    Select,
250    Radio,
251    Toggle,
252    Checkbox,
253    Date,
254    /// An instant, such as a `Timestamp`. The browser edits it in the user's time zone.
255    Datetime,
256    /// A wall-clock date and time without a time zone, such as a `civil::DateTime`.
257    CivilDatetime,
258    Tags,
259    Json,
260    Readonly,
261}
262
263/// A section of a resource's form: a card with a heading and some of the form's fields.
264#[derive(Debug, Clone, Serialize, Deserialize)]
265pub struct FormSectionSchemaDto {
266    pub title: Option<String>,
267    pub description: Option<String>,
268    pub columns: u8,
269    pub fields: Vec<FieldSchemaDto>,
270}
271
272/// Schema for a single form field.
273#[derive(Debug, Clone, Serialize, Deserialize)]
274pub struct FieldSchemaDto {
275    pub name: String,
276    pub label: String,
277    pub kind: FieldKind,
278    pub required: bool,
279    pub nullable: bool,
280    pub disabled: bool,
281    pub placeholder: Option<String>,
282    pub helper: Option<String>,
283    pub prefix: Option<String>,
284    pub suffix: Option<String>,
285    pub rows: Option<u8>,
286    pub min: Option<f64>,
287    pub max: Option<f64>,
288    pub max_length: Option<usize>,
289    pub column_span: u8,
290    pub default_value: Option<serde_json::Value>,
291    pub options: Vec<SelectOptionDto>,
292    pub create_only: bool,
293    pub edit_only: bool,
294}
295
296/// Confirmation prompt configuration for an action.
297#[derive(Debug, Clone, Serialize, Deserialize)]
298pub struct ActionConfirmationDto {
299    pub title: String,
300    pub description: String,
301    pub confirm_label: String,
302}
303
304/// Schema for a row action or bulk action.
305#[derive(Debug, Clone, Serialize, Deserialize)]
306pub struct ActionSchemaDto {
307    pub name: String,
308    pub label: String,
309    pub icon: Option<String>,
310    pub destructive: bool,
311    pub confirmation: Option<ActionConfirmationDto>,
312    pub fields: Vec<FieldSchemaDto>,
313}
314
315/// Paginated resource list response (`GET {base}/api/resources/{slug}`).
316#[derive(Debug, Clone, Serialize, Deserialize)]
317pub struct ResourceListResponse {
318    pub data: Vec<RecordEnvelopeDto>,
319    pub meta: PaginationMetaDto,
320    pub tab_counts: BTreeMap<String, u64>,
321}
322
323/// Wrapper around a serialized model record with resolved key, title, and per-row permissions.
324#[derive(Debug, Clone, Serialize, Deserialize)]
325pub struct RecordEnvelopeDto {
326    pub key: String,
327    pub title: Option<String>,
328    pub data: serde_json::Value,
329    pub can_view: bool,
330    pub can_edit: bool,
331    pub can_delete: bool,
332    /// The names of the row actions that apply to the record and that the user may run on it.
333    pub actions: Vec<String>,
334}
335
336/// Pagination metadata matching Laravel's paginator semantics.
337#[derive(Debug, Clone, Serialize, Deserialize)]
338pub struct PaginationMetaDto {
339    pub current_page: u64,
340    pub last_page: u64,
341    pub per_page: u64,
342    pub total: u64,
343    pub from: Option<u64>,
344    pub to: Option<u64>,
345}
346
347/// Single record response (`GET/POST/PATCH {base}/api/resources/{slug}[/{id}]`).
348#[derive(Debug, Clone, Serialize, Deserialize)]
349pub struct RecordResponse {
350    pub record: RecordEnvelopeDto,
351    pub message: Option<String>,
352}
353
354/// Payload sent when invoking a custom row action (`POST .../actions/{action}`).
355#[derive(Debug, Clone, Default, Serialize, Deserialize, Validate)]
356pub struct RunRowActionRequest {
357    #[serde(default)]
358    pub data: BTreeMap<String, serde_json::Value>,
359}
360
361/// Payload sent when invoking a bulk action (`POST .../bulk/{action}`).
362#[derive(Debug, Clone, Default, Serialize, Deserialize, Validate)]
363pub struct RunBulkActionRequest {
364    pub ids: Vec<String>,
365    #[serde(default)]
366    pub data: BTreeMap<String, serde_json::Value>,
367}
368
369/// Result returned by a row action, bulk action, or delete endpoint.
370#[derive(Debug, Clone, Serialize, Deserialize)]
371pub struct ActionResponse {
372    pub message: String,
373    pub affected: u64,
374    pub redirect_to: Option<String>,
375    pub refresh: bool,
376}
377
378/// Global search response (`GET {base}/api/search?q=...`).
379#[derive(Debug, Clone, Serialize, Deserialize)]
380pub struct GlobalSearchResponse {
381    pub query: String,
382    pub groups: Vec<GlobalSearchGroupDto>,
383}
384
385/// Search matches grouped by resource.
386#[derive(Debug, Clone, Serialize, Deserialize)]
387pub struct GlobalSearchGroupDto {
388    pub resource_slug: String,
389    pub resource_label: String,
390    pub icon: String,
391    pub hits: Vec<GlobalSearchHitDto>,
392}
393
394/// Single hit returned by global search.
395#[derive(Debug, Clone, Serialize, Deserialize)]
396pub struct GlobalSearchHitDto {
397    pub key: String,
398    pub title: String,
399    pub subtitle: Option<String>,
400}
401
402/// Dashboard response (`GET {base}/api/dashboard`).
403#[derive(Debug, Clone, Serialize, Deserialize)]
404pub struct DashboardResponse {
405    pub widgets: Vec<DashboardWidgetDto>,
406}
407
408/// Which way a stat's value moved.
409#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
410#[serde(rename_all = "snake_case")]
411pub enum TrendDirection {
412    Up,
413    Down,
414    Neutral,
415}
416
417/// Chart visual style.
418#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
419#[serde(rename_all = "snake_case")]
420pub enum ChartStyle {
421    Bar,
422    Area,
423    HorizontalBar,
424}
425
426/// One data point in a chart widget.
427#[derive(Debug, Clone, Serialize, Deserialize)]
428pub struct ChartPointDto {
429    pub label: String,
430    pub value: f64,
431    pub color: Option<BadgeColor>,
432}
433
434/// One column in a compact dashboard table widget.
435#[derive(Debug, Clone, Serialize, Deserialize)]
436pub struct TableWidgetColumnDto {
437    pub key: String,
438    pub label: String,
439    pub align: ColumnAlign,
440    pub badge_colors: BTreeMap<String, BadgeColor>,
441}
442
443/// One row in a compact dashboard table widget.
444#[derive(Debug, Clone, Serialize, Deserialize)]
445pub struct TableWidgetRowDto {
446    pub key: String,
447    pub href: Option<String>,
448    pub cells: BTreeMap<String, serde_json::Value>,
449}
450
451/// Discriminated union of dashboard widgets.
452#[derive(Debug, Clone, Serialize, Deserialize)]
453#[serde(tag = "kind", rename_all = "snake_case")]
454pub enum DashboardWidgetDto {
455    Stat {
456        id: String,
457        label: String,
458        value: String,
459        description: Option<String>,
460        trend: Option<String>,
461        trend_direction: Option<TrendDirection>,
462        icon: Option<String>,
463        color: BadgeColor,
464        sparkline: Vec<f64>,
465        href: Option<String>,
466        col_span: u8,
467    },
468    Chart {
469        id: String,
470        title: String,
471        subtitle: Option<String>,
472        style: ChartStyle,
473        points: Vec<ChartPointDto>,
474        value_prefix: Option<String>,
475        value_suffix: Option<String>,
476        col_span: u8,
477    },
478    Table {
479        id: String,
480        title: String,
481        subtitle: Option<String>,
482        action_label: Option<String>,
483        action_href: Option<String>,
484        columns: Vec<TableWidgetColumnDto>,
485        rows: Vec<TableWidgetRowDto>,
486        col_span: u8,
487    },
488}
489
490/// Standard Laravel 422 validation error response shape.
491#[derive(Debug, Clone, Serialize, Deserialize)]
492pub struct ValidationErrorResponse {
493    pub message: String,
494    pub errors: BTreeMap<String, Vec<String>>,
495}