Skip to main content

gize_admin/
lib.rs

1//! Admin UI generator for Gize (ADR-006).
2//!
3//! `gize make admin` generates a **separate** Vite + React + TypeScript SPA under `admin/`,
4//! driven by the manifest. The app is data-driven: [`resources_ts`] emits one descriptor
5//! (fields, relationships and a Zod schema) per resource from `gize.toml`, and generic
6//! components render List/Create/Edit/Delete for any of them. It talks to the backend through
7//! a Vite dev proxy (`/api` → the API), so no CORS or backend changes are needed.
8//!
9//! The UI is a token-based design system (light + dark theme) with a Django-inspired layout:
10//! an app shell, a changelist with search/filters/pagination/bulk actions, and a slide-over
11//! drawer form. Templates are Rust functions returning file contents.
12
13use gize_core::naming::table_name;
14use gize_core::{FieldType, Manifest};
15
16/// `admin/package.json` — the SPA's dependencies and scripts.
17pub fn package_json(project: &str) -> String {
18    format!(
19        r#"{{
20  "name": "{project}-admin",
21  "private": true,
22  "type": "module",
23  "scripts": {{
24    "dev": "vite",
25    "build": "tsc --noEmit && vite build",
26    "preview": "vite preview"
27  }},
28  "dependencies": {{
29    "@hookform/resolvers": "^3.9.0",
30    "@tanstack/react-query": "^5.59.0",
31    "react": "^18.3.1",
32    "react-dom": "^18.3.1",
33    "react-hook-form": "^7.53.0",
34    "zod": "^3.23.8"
35  }},
36  "devDependencies": {{
37    "@types/react": "^18.3.11",
38    "@types/react-dom": "^18.3.1",
39    "@vitejs/plugin-react": "^4.3.2",
40    "typescript": "^5.6.2",
41    "vite": "^5.4.8"
42  }},
43  "pnpm": {{
44    "onlyBuiltDependencies": ["esbuild"]
45  }}
46}}
47"#
48    )
49}
50
51/// `admin/vite.config.ts` — React, and a dev proxy so `/api/*` reaches the backend.
52pub fn vite_config() -> String {
53    r#"import { defineConfig } from "vite";
54import react from "@vitejs/plugin-react";
55
56// The API base is proxied so the browser talks same-origin in dev. Set VITE_API_URL to point
57// at your running Gize backend (default http://localhost:8080).
58export default defineConfig({
59  plugins: [react()],
60  server: {
61    proxy: {
62      "/api": {
63        target: process.env.VITE_API_URL || "http://localhost:8080",
64        changeOrigin: true,
65        rewrite: (p) => p.replace(/^\/api/, ""),
66      },
67    },
68  },
69});
70"#
71    .to_string()
72}
73
74/// `admin/tsconfig.json`.
75pub fn tsconfig() -> String {
76    r#"{
77  "compilerOptions": {
78    "target": "ES2020",
79    "useDefineForClassFields": true,
80    "lib": ["ES2020", "DOM", "DOM.Iterable"],
81    "module": "ESNext",
82    "skipLibCheck": true,
83    "moduleResolution": "bundler",
84    "allowImportingTsExtensions": true,
85    "resolveJsonModule": true,
86    "isolatedModules": true,
87    "noEmit": true,
88    "jsx": "react-jsx",
89    "strict": true,
90    "noUnusedLocals": false,
91    "noUnusedParameters": false,
92    "noFallthroughCasesInSwitch": true
93  },
94  "include": ["src"]
95}
96"#
97    .to_string()
98}
99
100/// `admin/index.html`. Sets the theme before first paint to avoid a flash.
101pub fn index_html() -> String {
102    r####"<!doctype html>
103<html lang="en">
104  <head>
105    <meta charset="UTF-8" />
106    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
107    <title>Admin</title>
108    <script>
109      try {
110        var t = localStorage.getItem("gize-admin-theme");
111        if (t === "dark" || t === "light") document.documentElement.setAttribute("data-theme", t);
112      } catch (e) {}
113    </script>
114  </head>
115  <body>
116    <div id="root"></div>
117    <script type="module" src="/src/main.tsx"></script>
118  </body>
119</html>
120"####
121        .to_string()
122}
123
124/// `admin/.env.example`.
125pub fn env_example() -> String {
126    "# Point at your running Gize backend (proxied under /api in dev).\nVITE_API_URL=http://localhost:8080\n"
127        .to_string()
128}
129
130/// `admin/.gitignore`.
131pub fn gitignore() -> String {
132    "node_modules\ndist\n.env\n".to_string()
133}
134
135/// `admin/src/styles.css` — the token-based design system (light + dark).
136pub fn styles_css() -> String {
137    include_str!("assets/styles.css").to_string()
138}
139
140/// `admin/src/main.tsx`.
141pub fn main_tsx() -> String {
142    r#"import React from "react";
143import { createRoot } from "react-dom/client";
144import App from "./App";
145import "./styles.css";
146
147createRoot(document.getElementById("root")!).render(
148  <React.StrictMode>
149    <App />
150  </React.StrictMode>,
151);
152"#
153    .to_string()
154}
155
156/// `admin/src/theme.ts` — light/dark theme helpers (persisted, system-aware).
157pub fn theme_ts() -> String {
158    r#"export type Theme = "light" | "dark";
159
160export function currentTheme(): Theme {
161  const stored = safeGet();
162  if (stored === "light" || stored === "dark") return stored;
163  return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
164}
165
166export function setTheme(theme: Theme): void {
167  document.documentElement.setAttribute("data-theme", theme);
168  try {
169    localStorage.setItem("gize-admin-theme", theme);
170  } catch {
171    /* ignore */
172  }
173}
174
175export function toggleTheme(): Theme {
176  const next: Theme = currentTheme() === "dark" ? "light" : "dark";
177  setTheme(next);
178  return next;
179}
180
181function safeGet(): string | null {
182  try {
183    return localStorage.getItem("gize-admin-theme");
184  } catch {
185    return null;
186  }
187}
188"#
189    .to_string()
190}
191
192/// `admin/src/icons.tsx` — a small inline SVG icon set.
193pub fn icons_tsx() -> String {
194    include_str!("assets/icons.tsx").to_string()
195}
196
197/// `admin/src/toast.tsx` — a lightweight toast (event-based, no context wiring).
198pub fn toast_tsx() -> String {
199    r#"import { useEffect, useState } from "react";
200import { Icon } from "./icons";
201
202export function toast(message: string): void {
203  window.dispatchEvent(new CustomEvent("gize-toast", { detail: message }));
204}
205
206export function ToastHost() {
207  const [msg, setMsg] = useState<string | null>(null);
208  useEffect(() => {
209    let timer: number | undefined;
210    function onToast(e: Event) {
211      setMsg((e as CustomEvent<string>).detail);
212      window.clearTimeout(timer);
213      timer = window.setTimeout(() => setMsg(null), 2400);
214    }
215    window.addEventListener("gize-toast", onToast);
216    return () => {
217      window.removeEventListener("gize-toast", onToast);
218      window.clearTimeout(timer);
219    };
220  }, []);
221  return (
222    <div className={"toast" + (msg ? " show" : "")} role="status" aria-live="polite">
223      <Icon name="check" className="ok" />
224      <span>{msg}</span>
225    </div>
226  );
227}
228"#
229    .to_string()
230}
231
232/// `admin/src/api.ts` — a tiny typed fetch client that attaches the JWT and hits `/api`.
233pub fn api_ts() -> String {
234    r#"const BASE = "/api";
235
236export function getToken(): string | null {
237  return localStorage.getItem("gize_token");
238}
239
240/** A failed API call. `status` tells a refused request (401/403) apart from a broken one. */
241export class ApiError extends Error {
242  status: number;
243  constructor(status: number, message: string) {
244    super(message);
245    this.status = status;
246  }
247}
248
249/** The HTTP status of a failed call, or undefined when the request never got an answer. */
250export function statusOf(error: unknown): number | undefined {
251  return error instanceof ApiError ? error.status : undefined;
252}
253
254async function req(path: string, opts: RequestInit = {}): Promise<any> {
255  const headers: Record<string, string> = {
256    "content-type": "application/json",
257    ...(opts.headers as Record<string, string>),
258  };
259  const t = getToken();
260  if (t) headers["authorization"] = `Bearer ${t}`;
261  const res = await fetch(`${BASE}${path}`, { ...opts, headers });
262  if (!res.ok) {
263    const body = await res.text();
264    throw new ApiError(res.status, body || String(res.status));
265  }
266  if (res.status === 204) return null;
267  return res.json();
268}
269
270/** Largest page the API serves (ADR-022). */
271const PER_PAGE = 100;
272
273/** Every row of a resource: pages of PER_PAGE until the last one, so search, filters and
274 * foreign-key selects can keep working on the full list in the browser. */
275async function listAll(path: string): Promise<any[]> {
276  const rows: any[] = [];
277  for (let page = 1; ; page++) {
278    const res = await req(`/${path}?page=${page}&per_page=${PER_PAGE}`);
279    rows.push(...res.items);
280    if (res.items.length < PER_PAGE || rows.length >= res.total) return rows;
281  }
282}
283
284export const api = {
285  list: listAll,
286  get: (path: string, id: string) => req(`/${path}/${id}`),
287  create: (path: string, body: unknown) =>
288    req(`/${path}`, { method: "POST", body: JSON.stringify(body) }),
289  update: (path: string, id: string, body: unknown) =>
290    req(`/${path}/${id}`, { method: "PUT", body: JSON.stringify(body) }),
291  remove: (path: string, id: string) => req(`/${path}/${id}`, { method: "DELETE" }),
292  login: (email: string, password: string) =>
293    req(`/users/login`, { method: "POST", body: JSON.stringify({ email, password }) }),
294};
295
296/** A resource's display label: the (plural) path in words, capitalized — e.g.
297 * "posts" -> "Posts", "ticket_types" -> "Ticket types". */
298export function titleCase(s: string): string {
299  const words = s.replace(/_/g, " ");
300  return words.charAt(0).toUpperCase() + words.slice(1);
301}
302
303/** A model name as a lowercase noun for buttons and dialogs — e.g. "TicketType" -> "ticket type". */
304export function nounOf(model: string): string {
305  return model.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase();
306}
307
308/** A readable label for a related record (used by foreign-key selects and cells). */
309export function labelOf(row: Record<string, any>): string {
310  for (const key of ["name", "title", "email", "slug"]) {
311    if (row[key]) return String(row[key]);
312  }
313  for (const key of Object.keys(row)) {
314    const value = row[key];
315    if (typeof value === "string" && key !== "id" && !key.endsWith("_at")) return value;
316  }
317  return String(row.id ?? "");
318}
319"#
320    .to_string()
321}
322
323/// `admin/src/auth.tsx` — token storage hook and the branded login screen.
324pub fn auth_tsx() -> String {
325    include_str!("assets/auth.tsx").to_string()
326}
327
328/// `admin/src/App.tsx` — the app shell (topbar, sidebar, drawer, toasts, theme toggle).
329pub fn app_tsx() -> String {
330    include_str!("assets/App.tsx").to_string()
331}
332
333/// `admin/src/Resource.tsx` — the changelist (search, filters, pagination, bulk actions).
334pub fn resource_tsx() -> String {
335    include_str!("assets/Resource.tsx").to_string()
336}
337
338/// `admin/src/ResourceForm.tsx` — the drawer form (fieldsets, typed inputs, FK selects).
339pub fn resource_form_tsx() -> String {
340    include_str!("assets/ResourceForm.tsx").to_string()
341}
342
343/// `admin/src/resources.ts` — the descriptors generated from the manifest (ADR-006): one entry
344/// per resource with its editable fields (each field carrying its kind, and a `ref` target for
345/// foreign keys) and a Zod schema mirroring the backend validation.
346pub fn resources_ts(manifest: &Manifest) -> anyhow::Result<String> {
347    let mut entries = String::new();
348    for module in &manifest.modules {
349        let model = module.model_spec()?;
350        let table = table_name(&model.name);
351
352        let mut fields_ts = String::new();
353        let mut schema_ts = String::new();
354        for f in &model.fields {
355            let kind = field_kind(&f.name, f.ty);
356            // A synthetic `<name>_id` foreign-key column references `belongs_to` target's table.
357            let ref_target = model
358                .relations
359                .iter()
360                .find(|r| r.fk_column() == f.name)
361                .map(|r| r.target.clone());
362            let ref_ts = match &ref_target {
363                Some(t) => format!(", ref: \"{t}\""),
364                None => String::new(),
365            };
366            fields_ts.push_str(&format!(
367                "      {{ name: \"{}\", kind: \"{kind}\"{ref_ts} }},\n",
368                f.name
369            ));
370            // A foreign key is a required select: say so instead of zod's "Invalid uuid".
371            let zod = if ref_target.is_some() {
372                "z.string().uuid(\"Choose one\")"
373            } else {
374                zod_for(kind)
375            };
376            schema_ts.push_str(&format!("      {}: {zod},\n", f.name));
377        }
378
379        entries.push_str(&format!(
380            "  {{\n    name: \"{name}\",\n    path: \"{table}\",\n    fields: [\n{fields_ts}    ],\n    createSchema: z.object({{\n{schema_ts}    }}),\n  }},\n",
381            name = model.name,
382        ));
383    }
384
385    Ok(format!(
386        r#"import {{ z }} from "zod";
387
388export type FieldKind =
389  | "string"
390  | "number"
391  | "boolean"
392  | "uuid"
393  | "datetime"
394  | "email"
395  | "password";
396
397export interface FieldDesc {{
398  name: string;
399  kind: FieldKind;
400  /** For a foreign key: the target resource path (e.g. "users"). */
401  ref?: string;
402}}
403
404export interface ResourceDesc {{
405  name: string;
406  path: string;
407  fields: FieldDesc[];
408  createSchema: z.ZodTypeAny;
409}}
410
411export const resources: ResourceDesc[] = [
412{entries}];
413"#
414    ))
415}
416
417/// The admin field kind for a model field: `email`/`password` are recognized by name (mirroring
418/// the backend's users validation), everything else maps from the scalar type.
419fn field_kind(name: &str, ty: FieldType) -> &'static str {
420    match name {
421        "email" => "email",
422        "password" => "password",
423        _ => match ty {
424            FieldType::String => "string",
425            FieldType::Bool => "boolean",
426            FieldType::I32 | FieldType::I64 | FieldType::F64 => "number",
427            FieldType::Uuid => "uuid",
428            FieldType::DateTime => "datetime",
429        },
430    }
431}
432
433/// The Zod validator for a field kind, mirroring the backend `validator` rules.
434fn zod_for(kind: &str) -> &'static str {
435    match kind {
436        "email" => "z.string().email()",
437        "password" => "z.string().min(8)",
438        "number" => "z.coerce.number()",
439        "boolean" => "z.boolean()",
440        "uuid" => "z.string().uuid()",
441        "datetime" => "z.string().min(1)",
442        _ => "z.string().min(1)",
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449    use gize_core::{Module, Relation};
450
451    fn manifest() -> Manifest {
452        let mut m = Manifest::new("blog");
453        m.upsert_module(Module {
454            name: "users".to_string(),
455            model: None,
456            fields: vec![
457                "name:String".to_string(),
458                "email:String".to_string(),
459                "password:String".to_string(),
460                "is_admin:bool".to_string(),
461            ],
462            belongs_to: vec![],
463        });
464        m.upsert_module(Module {
465            name: "posts".to_string(),
466            model: None,
467            fields: vec!["title:String".to_string()],
468            belongs_to: vec![Relation {
469                field: "author".to_string(),
470                target: "users".to_string(),
471            }],
472        });
473        m
474    }
475
476    #[test]
477    fn resources_ts_describes_each_resource() {
478        let ts = resources_ts(&manifest()).unwrap();
479        assert!(ts.contains("path: \"users\""));
480        assert!(ts.contains("path: \"posts\""));
481        assert!(ts.contains("{ name: \"email\", kind: \"email\" }"));
482        assert!(ts.contains("email: z.string().email()"));
483        assert!(ts.contains("password: z.string().min(8)"));
484        // the FK column is a uuid field carrying its ref target.
485        assert!(ts.contains("{ name: \"author_id\", kind: \"uuid\", ref: \"users\" }"));
486    }
487
488    #[test]
489    fn api_client_walks_every_page() {
490        let out = api_ts();
491        assert!(out.contains("const PER_PAGE = 100;"));
492        assert!(out.contains("?page=${page}&per_page=${PER_PAGE}"));
493        assert!(out.contains("list: listAll,"));
494    }
495
496    #[test]
497    fn api_errors_carry_their_status() {
498        let out = api_ts();
499        assert!(out.contains("export class ApiError extends Error"));
500        assert!(out.contains("throw new ApiError(res.status, body || String(res.status));"));
501        assert!(out.contains("export function statusOf(error: unknown)"));
502    }
503
504    #[test]
505    fn refused_requests_are_not_retried_and_end_an_expired_session() {
506        let app = app_tsx();
507        assert!(app.contains("queryCache: new QueryCache({ onError: endExpiredSession })"));
508        assert!(app.contains("mutationCache: new MutationCache({ onError: endExpiredSession })"));
509        assert!(app.contains("(status === undefined || status >= 500) && failures < 3"));
510        let resource = resource_tsx();
511        assert!(resource.contains("list.isError"));
512        assert!(resource.contains("You don't have permission to see"));
513        assert!(resource.contains("if (expired) throw (expired as PromiseRejectedResult).reason;"));
514    }
515
516    #[test]
517    fn labels_read_as_words_and_foreign_keys_explain_themselves() {
518        let api = api_ts();
519        assert!(api.contains(r#"s.replace(/_/g, " ")"#));
520        assert!(api.contains("export function nounOf(model: string)"));
521        let ts = resources_ts(&manifest()).unwrap();
522        assert!(ts.contains(r#"author_id: z.string().uuid("Choose one"),"#));
523    }
524
525    #[test]
526    fn package_json_uses_the_project_name() {
527        assert!(package_json("blog").contains("\"name\": \"blog-admin\""));
528    }
529
530    #[test]
531    fn package_json_approves_esbuild_build_so_serve_works_without_pnpm_approve_builds() {
532        // pnpm v10 blocks dependency build scripts by default; whitelisting esbuild lets the
533        // first-run `pnpm install` build it, so `gize serve` works without `pnpm approve-builds`.
534        assert!(package_json("blog").contains("\"onlyBuiltDependencies\": [\"esbuild\"]"));
535    }
536}