1use gize_core::naming::table_name;
14use gize_core::{FieldType, Manifest};
15
16pub 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
51pub 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
74pub 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
100pub 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
124pub 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
130pub fn gitignore() -> String {
132 "node_modules\ndist\n.env\n".to_string()
133}
134
135pub fn styles_css() -> String {
137 include_str!("assets/styles.css").to_string()
138}
139
140pub 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
156pub 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
192pub fn icons_tsx() -> String {
194 include_str!("assets/icons.tsx").to_string()
195}
196
197pub 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
232pub fn api_ts() -> String {
234 r#"const BASE = "/api";
235
236export function getToken(): string | null {
237 return localStorage.getItem("gize_token");
238}
239
240async function req(path: string, opts: RequestInit = {}): Promise<any> {
241 const headers: Record<string, string> = {
242 "content-type": "application/json",
243 ...(opts.headers as Record<string, string>),
244 };
245 const t = getToken();
246 if (t) headers["authorization"] = `Bearer ${t}`;
247 const res = await fetch(`${BASE}${path}`, { ...opts, headers });
248 if (!res.ok) {
249 const body = await res.text();
250 throw new Error(body || String(res.status));
251 }
252 if (res.status === 204) return null;
253 return res.json();
254}
255
256/** Largest page the API serves (ADR-022). */
257const PER_PAGE = 100;
258
259/** Every row of a resource: pages of PER_PAGE until the last one, so search, filters and
260 * foreign-key selects can keep working on the full list in the browser. */
261async function listAll(path: string): Promise<any[]> {
262 const rows: any[] = [];
263 for (let page = 1; ; page++) {
264 const res = await req(`/${path}?page=${page}&per_page=${PER_PAGE}`);
265 rows.push(...res.items);
266 if (res.items.length < PER_PAGE || rows.length >= res.total) return rows;
267 }
268}
269
270export const api = {
271 list: listAll,
272 get: (path: string, id: string) => req(`/${path}/${id}`),
273 create: (path: string, body: unknown) =>
274 req(`/${path}`, { method: "POST", body: JSON.stringify(body) }),
275 update: (path: string, id: string, body: unknown) =>
276 req(`/${path}/${id}`, { method: "PUT", body: JSON.stringify(body) }),
277 remove: (path: string, id: string) => req(`/${path}/${id}`, { method: "DELETE" }),
278 login: (email: string, password: string) =>
279 req(`/users/login`, { method: "POST", body: JSON.stringify({ email, password }) }),
280};
281
282/** A resource's display label: the (plural) path, capitalized — e.g. "posts" -> "Posts". */
283export function titleCase(s: string): string {
284 return s.charAt(0).toUpperCase() + s.slice(1);
285}
286
287/** A readable label for a related record (used by foreign-key selects and cells). */
288export function labelOf(row: Record<string, any>): string {
289 for (const key of ["name", "title", "email", "slug"]) {
290 if (row[key]) return String(row[key]);
291 }
292 for (const key of Object.keys(row)) {
293 const value = row[key];
294 if (typeof value === "string" && key !== "id" && !key.endsWith("_at")) return value;
295 }
296 return String(row.id ?? "");
297}
298"#
299 .to_string()
300}
301
302pub fn auth_tsx() -> String {
304 include_str!("assets/auth.tsx").to_string()
305}
306
307pub fn app_tsx() -> String {
309 include_str!("assets/App.tsx").to_string()
310}
311
312pub fn resource_tsx() -> String {
314 include_str!("assets/Resource.tsx").to_string()
315}
316
317pub fn resource_form_tsx() -> String {
319 include_str!("assets/ResourceForm.tsx").to_string()
320}
321
322pub fn resources_ts(manifest: &Manifest) -> anyhow::Result<String> {
326 let mut entries = String::new();
327 for module in &manifest.modules {
328 let model = module.model_spec()?;
329 let table = table_name(&model.name);
330
331 let mut fields_ts = String::new();
332 let mut schema_ts = String::new();
333 for f in &model.fields {
334 let kind = field_kind(&f.name, f.ty);
335 let ref_target = model
337 .relations
338 .iter()
339 .find(|r| r.fk_column() == f.name)
340 .map(|r| r.target.clone());
341 let ref_ts = match &ref_target {
342 Some(t) => format!(", ref: \"{t}\""),
343 None => String::new(),
344 };
345 fields_ts.push_str(&format!(
346 " {{ name: \"{}\", kind: \"{kind}\"{ref_ts} }},\n",
347 f.name
348 ));
349 schema_ts.push_str(&format!(" {}: {},\n", f.name, zod_for(kind)));
350 }
351
352 entries.push_str(&format!(
353 " {{\n name: \"{name}\",\n path: \"{table}\",\n fields: [\n{fields_ts} ],\n createSchema: z.object({{\n{schema_ts} }}),\n }},\n",
354 name = model.name,
355 ));
356 }
357
358 Ok(format!(
359 r#"import {{ z }} from "zod";
360
361export type FieldKind =
362 | "string"
363 | "number"
364 | "boolean"
365 | "uuid"
366 | "datetime"
367 | "email"
368 | "password";
369
370export interface FieldDesc {{
371 name: string;
372 kind: FieldKind;
373 /** For a foreign key: the target resource path (e.g. "users"). */
374 ref?: string;
375}}
376
377export interface ResourceDesc {{
378 name: string;
379 path: string;
380 fields: FieldDesc[];
381 createSchema: z.ZodTypeAny;
382}}
383
384export const resources: ResourceDesc[] = [
385{entries}];
386"#
387 ))
388}
389
390fn field_kind(name: &str, ty: FieldType) -> &'static str {
393 match name {
394 "email" => "email",
395 "password" => "password",
396 _ => match ty {
397 FieldType::String => "string",
398 FieldType::Bool => "boolean",
399 FieldType::I32 | FieldType::I64 | FieldType::F64 => "number",
400 FieldType::Uuid => "uuid",
401 FieldType::DateTime => "datetime",
402 },
403 }
404}
405
406fn zod_for(kind: &str) -> &'static str {
408 match kind {
409 "email" => "z.string().email()",
410 "password" => "z.string().min(8)",
411 "number" => "z.coerce.number()",
412 "boolean" => "z.boolean()",
413 "uuid" => "z.string().uuid()",
414 "datetime" => "z.string().min(1)",
415 _ => "z.string().min(1)",
416 }
417}
418
419#[cfg(test)]
420mod tests {
421 use super::*;
422 use gize_core::{Module, Relation};
423
424 fn manifest() -> Manifest {
425 let mut m = Manifest::new("blog");
426 m.upsert_module(Module {
427 name: "users".to_string(),
428 fields: vec![
429 "name:String".to_string(),
430 "email:String".to_string(),
431 "password:String".to_string(),
432 "is_admin:bool".to_string(),
433 ],
434 belongs_to: vec![],
435 });
436 m.upsert_module(Module {
437 name: "posts".to_string(),
438 fields: vec!["title:String".to_string()],
439 belongs_to: vec![Relation {
440 field: "author".to_string(),
441 target: "users".to_string(),
442 }],
443 });
444 m
445 }
446
447 #[test]
448 fn resources_ts_describes_each_resource() {
449 let ts = resources_ts(&manifest()).unwrap();
450 assert!(ts.contains("path: \"users\""));
451 assert!(ts.contains("path: \"posts\""));
452 assert!(ts.contains("{ name: \"email\", kind: \"email\" }"));
453 assert!(ts.contains("email: z.string().email()"));
454 assert!(ts.contains("password: z.string().min(8)"));
455 assert!(ts.contains("{ name: \"author_id\", kind: \"uuid\", ref: \"users\" }"));
457 }
458
459 #[test]
460 fn api_client_walks_every_page() {
461 let out = api_ts();
462 assert!(out.contains("const PER_PAGE = 100;"));
463 assert!(out.contains("?page=${page}&per_page=${PER_PAGE}"));
464 assert!(out.contains("list: listAll,"));
465 }
466
467 #[test]
468 fn package_json_uses_the_project_name() {
469 assert!(package_json("blog").contains("\"name\": \"blog-admin\""));
470 }
471
472 #[test]
473 fn package_json_approves_esbuild_build_so_serve_works_without_pnpm_approve_builds() {
474 assert!(package_json("blog").contains("\"onlyBuiltDependencies\": [\"esbuild\"]"));
477 }
478}