create-start-serenojs 0.1.1 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,41 @@
1
1
  "use client";
2
2
 
3
- import { type FormEvent, useEffect, useState } from "react";
3
+ import { type ReactNode, useEffect, useState } from "react";
4
4
 
5
- type Todo = {
5
+ import { MarkdownPreview } from "@eutobias/serenojs/ui";
6
+
7
+ type MediaItem = {
8
+ url: string;
9
+ alt?: string;
10
+ primary?: boolean;
11
+ };
12
+
13
+ type ObjectLink = {
14
+ label: string;
15
+ url?: string;
16
+ };
17
+
18
+ type ShowcaseItem = {
6
19
  id: number;
7
20
  title: string;
8
- priority?: string;
9
- done?: boolean;
10
- dueDate?: string;
21
+ contactEmail?: string;
22
+ summary?: string;
23
+ body?: string;
24
+ rating?: number;
25
+ published?: boolean;
26
+ category?: string;
27
+ releaseDate?: string;
28
+ related?: number[];
29
+ cover?: string;
30
+ gallery?: MediaItem[];
31
+ features?: string[];
32
+ links?: ObjectLink[];
33
+ };
34
+
35
+ const categoryLabels: Record<string, string> = {
36
+ design: "Design",
37
+ engineering: "Engineering",
38
+ marketing: "Marketing",
11
39
  };
12
40
 
13
41
  const MONTHS = [
@@ -25,41 +53,57 @@ const MONTHS = [
25
53
  "Dec",
26
54
  ];
27
55
 
28
- const priorityLabels: Record<string, string> = {
29
- low: "Low",
30
- medium: "Medium",
31
- high: "High",
32
- };
33
-
34
- function formatDueDate(value: string): string {
56
+ function formatDate(value: string | undefined): string {
57
+ if (!value) return "—";
35
58
  const [year, month, day] = value.slice(0, 10).split("-");
36
59
  const monthName = month ? MONTHS[Number(month) - 1] : undefined;
37
60
  if (!year || !monthName || !day) return value;
38
61
  return `${monthName} ${Number(day)}, ${year}`;
39
62
  }
40
63
 
41
- async function readTodos(): Promise<Todo[]> {
42
- const response = await fetch("/api/todos?limit=100");
64
+ function isImage(url: string): boolean {
65
+ return /\.(png|jpe?g|gif|webp|avif|svg)(\?|$)/i.test(url);
66
+ }
67
+
68
+ async function readShowcase(): Promise<ShowcaseItem[]> {
69
+ const response = await fetch("/api/showcase?limit=100");
43
70
  if (!response.ok) throw new Error(`Request failed: ${response.status}`);
44
- const json = (await response.json()) as { items?: Todo[] };
71
+ const json = (await response.json()) as { items?: ShowcaseItem[] };
45
72
  return json.items ?? [];
46
73
  }
47
74
 
48
- export default function TodosPage() {
49
- const [todos, setTodos] = useState<Todo[]>([]);
75
+ function Field({
76
+ label,
77
+ type,
78
+ children,
79
+ }: {
80
+ label: string;
81
+ type: string;
82
+ children: ReactNode;
83
+ }) {
84
+ return (
85
+ <div className="field">
86
+ <dt>
87
+ {label} <span className="field-type">{type}</span>
88
+ </dt>
89
+ <dd>{children}</dd>
90
+ </div>
91
+ );
92
+ }
93
+
94
+ export default function ShowcasePage() {
95
+ const [items, setItems] = useState<ShowcaseItem[]>([]);
50
96
  const [loading, setLoading] = useState(true);
97
+ const [busy, setBusy] = useState(false);
51
98
  const [error, setError] = useState<string | null>(null);
52
- const [title, setTitle] = useState("");
53
- const [editingId, setEditingId] = useState<number | null>(null);
54
- const [editTitle, setEditTitle] = useState("");
55
99
 
56
100
  const load = async () => {
57
101
  setLoading(true);
58
102
  setError(null);
59
103
  try {
60
- setTodos(await readTodos());
104
+ setItems(await readShowcase());
61
105
  } catch {
62
- setError("Could not load tasks.");
106
+ setError("Could not load the showcase records.");
63
107
  } finally {
64
108
  setLoading(false);
65
109
  }
@@ -69,80 +113,70 @@ export default function TodosPage() {
69
113
  void load();
70
114
  }, []);
71
115
 
72
- const mutate = async (
73
- action: () => Promise<void>,
74
- failureMessage: string,
75
- ): Promise<boolean> => {
116
+ const createSample = async () => {
117
+ setBusy(true);
76
118
  setError(null);
77
119
  try {
78
- await action();
79
- setTodos(await readTodos());
80
- return true;
81
- } catch {
82
- setError(failureMessage);
83
- return false;
84
- }
85
- };
86
-
87
- const add = async (event: FormEvent) => {
88
- event.preventDefault();
89
- const value = title.trim();
90
- if (!value) return;
91
-
92
- const saved = await mutate(async () => {
93
- const response = await fetch("/api/todos", {
120
+ const response = await fetch("/api/showcase", {
94
121
  method: "POST",
95
122
  headers: { "Content-Type": "application/json" },
96
- body: JSON.stringify({ title: value }),
123
+ body: JSON.stringify({
124
+ title: `SerenoJS field showcase #${items.length + 1}`,
125
+ contactEmail: "hello@example.com",
126
+ summary:
127
+ "A single record that exercises every SerenoJS field type: text, e-mail, textarea, richtext, number, boolean, select, date, relation, media, media-list, list and object-list.",
128
+ body: [
129
+ "## Markdown richtext",
130
+ "",
131
+ "This body is **Markdown**, edited with the GitHub toolbar and",
132
+ "rendered with a sanitized preview.",
133
+ "",
134
+ "> The stored value stays plain Markdown.",
135
+ "",
136
+ "- Bold, italic and headings",
137
+ "- Lists and task lists",
138
+ "- [Links](https://github.com/eutobias/serenojs)",
139
+ ].join("\n"),
140
+ rating: 5,
141
+ published: true,
142
+ category: "design",
143
+ releaseDate: new Date().toISOString().slice(0, 10),
144
+ related: items.slice(0, 2).map((item) => item.id),
145
+ cover: "/images/showcase.svg",
146
+ gallery: [
147
+ { url: "/images/showcase.svg", alt: "Showcase cover", primary: true },
148
+ ],
149
+ features: ["Schema-driven", "REST API", "Cookie auth", "Object lists"],
150
+ links: [
151
+ { label: "SerenoJS", url: "https://github.com/eutobias/serenojs" },
152
+ { label: "Waku", url: "https://waku.gg" },
153
+ ],
154
+ }),
97
155
  });
98
156
  if (!response.ok) throw new Error(`Request failed: ${response.status}`);
99
- }, "Could not add the task.");
100
-
101
- if (saved) setTitle("");
102
- };
103
-
104
- const toggle = (todo: Todo) =>
105
- mutate(async () => {
106
- const response = await fetch(`/api/todos/${todo.id}`, {
107
- method: "PATCH",
108
- headers: { "Content-Type": "application/json" },
109
- body: JSON.stringify({ done: !todo.done }),
110
- });
111
- if (!response.ok) throw new Error(`Request failed: ${response.status}`);
112
- }, "Could not update the task.");
113
-
114
- const remove = (id: number) =>
115
- mutate(async () => {
116
- const response = await fetch(`/api/todos/${id}`, { method: "DELETE" });
117
- if (!response.ok) throw new Error(`Request failed: ${response.status}`);
118
- }, "Could not remove the task.");
119
-
120
- const startEdit = (todo: Todo) => {
121
- setEditingId(todo.id);
122
- setEditTitle(todo.title);
157
+ await load();
158
+ } catch {
159
+ setError("Could not create the example record.");
160
+ } finally {
161
+ setBusy(false);
162
+ }
123
163
  };
124
164
 
125
- const saveEdit = async () => {
126
- const value = editTitle.trim();
127
- if (!value || editingId === null) return;
128
-
129
- const saved = await mutate(async () => {
130
- const response = await fetch(`/api/todos/${editingId}`, {
131
- method: "PATCH",
132
- headers: { "Content-Type": "application/json" },
133
- body: JSON.stringify({ title: value }),
134
- });
165
+ const remove = async (id: number) => {
166
+ setBusy(true);
167
+ setError(null);
168
+ try {
169
+ const response = await fetch(`/api/showcase/${id}`, { method: "DELETE" });
135
170
  if (!response.ok) throw new Error(`Request failed: ${response.status}`);
136
- }, "Could not save the task.");
137
-
138
- if (saved) setEditingId(null);
171
+ await load();
172
+ } catch {
173
+ setError("Could not remove the record.");
174
+ } finally {
175
+ setBusy(false);
176
+ }
139
177
  };
140
178
 
141
- const remaining = todos.filter((todo) => !todo.done).length;
142
- const countLabel =
143
- remaining === 0
144
- ? "All done"
145
- : `${remaining} open ${remaining === 1 ? "task" : "tasks"}`;
179
+ const titles = new Map(items.map((item) => [item.id, item.title]));
146
180
 
147
181
  return (
148
182
  <main className="app">
@@ -160,34 +194,33 @@ export default function TodosPage() {
160
194
  </header>
161
195
 
162
196
  <section className="intro">
163
- <h1>Tasks</h1>
164
- <p>A minimal CRUD app on top of the SerenoJS public API.</p>
197
+ <h1>Field showcase</h1>
198
+ <p>
199
+ One collection, every field type. Create a record here, then edit the
200
+ same content in the admin panel.
201
+ </p>
165
202
  </section>
166
203
 
167
- <section className="panel" aria-label="Task list">
168
- <form className="composer" onSubmit={(event) => void add(event)}>
169
- <label htmlFor="todo-title">New task</label>
204
+ <section className="panel" aria-label="Showcase records">
205
+ <div className="composer">
206
+ <span className="composer-label">Schema demo</span>
170
207
  <div className="composer-row">
171
- <input
172
- id="todo-title"
173
- value={title}
174
- onChange={(event) => setTitle(event.target.value)}
175
- placeholder="e.g. review the posts schema"
176
- />
177
- <button className="btn btn-primary" type="submit">
178
- Add
208
+ <button
209
+ className="btn btn-primary"
210
+ type="button"
211
+ disabled={busy}
212
+ onClick={() => void createSample()}
213
+ >
214
+ {busy ? "Working…" : "Create example item"}
179
215
  </button>
216
+ <a className="btn btn-ghost" href="/admin">
217
+ Edit in admin
218
+ </a>
180
219
  </div>
181
220
  <p className="hint">
182
- The task is created by the API at <code>/api/todos</code>.
221
+ The record is created by the public API at{" "}
222
+ <code>/api/showcase</code>.
183
223
  </p>
184
- </form>
185
-
186
- <div className="list-head">
187
- <h2>Your tasks</h2>
188
- <span className="count" aria-live="polite">
189
- {loading ? "Loading" : countLabel}
190
- </span>
191
224
  </div>
192
225
 
193
226
  {error ? (
@@ -202,117 +235,185 @@ export default function TodosPage() {
202
235
  Try again
203
236
  </button>
204
237
  </div>
205
- ) : loading ? (
206
- <div className="skeleton" role="status" aria-label="Loading tasks">
207
- {[0, 1, 2].map((index) => (
238
+ ) : null}
239
+
240
+ <div className="list-head">
241
+ <h2>Records</h2>
242
+ <span className="count" aria-live="polite">
243
+ {loading ? "Loading" : error ? "—" : `${items.length} item(s)`}
244
+ </span>
245
+ </div>
246
+
247
+ {loading ? (
248
+ <div className="skeleton" role="status" aria-label="Loading records">
249
+ {[0, 1].map((index) => (
208
250
  <div className="skeleton-row" key={index} aria-hidden="true">
209
- <span className="skeleton-dot" />
210
251
  <span className="skeleton-line" />
211
252
  </div>
212
253
  ))}
213
254
  </div>
214
- ) : todos.length === 0 ? (
255
+ ) : error ? null : items.length === 0 ? (
215
256
  <div className="state">
216
- <strong>No tasks yet</strong>
217
- <p>Add the first one above to see the API in action.</p>
257
+ <strong>No records yet</strong>
258
+ <p>Create the example item above to inspect every field type.</p>
218
259
  </div>
219
260
  ) : (
220
- <ul className="todo-list">
221
- {todos.map((todo) => {
222
- const done = Boolean(todo.done);
223
- const priority = todo.priority
224
- ? (priorityLabels[todo.priority] ?? todo.priority)
225
- : null;
226
- const priorityClass =
227
- todo.priority && priorityLabels[todo.priority]
228
- ? `chip chip-${todo.priority}`
229
- : "chip";
261
+ <div className="showcase-list">
262
+ {items.map((item) => (
263
+ <article className="showcase-card" key={item.id}>
264
+ <header className="showcase-head">
265
+ <div>
266
+ <h2>{item.title}</h2>
267
+ <p className="showcase-summary">{item.summary || "—"}</p>
268
+ </div>
269
+ <button
270
+ className="btn btn-danger btn-small"
271
+ type="button"
272
+ disabled={busy}
273
+ onClick={() => void remove(item.id)}
274
+ >
275
+ Remove
276
+ </button>
277
+ </header>
230
278
 
231
- return (
232
- <li className={done ? "todo is-done" : "todo"} key={todo.id}>
233
- <label className="check">
234
- <input
235
- type="checkbox"
236
- checked={done}
237
- onChange={() => void toggle(todo)}
238
- />
239
- <span className="box" aria-hidden="true" />
240
- <span className="sr-only">
241
- {done ? "Reopen" : "Complete"} {todo.title}
279
+ <dl className="field-grid">
280
+ <Field label="Title" type="text">
281
+ {item.title || "—"}
282
+ </Field>
283
+ <Field label="Contact email" type="email">
284
+ {item.contactEmail ? (
285
+ <a href={`mailto:${item.contactEmail}`}>
286
+ {item.contactEmail}
287
+ </a>
288
+ ) : (
289
+ "—"
290
+ )}
291
+ </Field>
292
+ <Field label="Summary" type="textarea">
293
+ {item.summary || "—"}
294
+ </Field>
295
+ <Field label="Body" type="richtext">
296
+ {item.body ? (
297
+ <MarkdownPreview value={item.body} />
298
+ ) : (
299
+ "—"
300
+ )}
301
+ </Field>
302
+ <Field label="Rating" type="number">
303
+ {item.rating ?? "—"}
304
+ </Field>
305
+ <Field label="Published" type="boolean">
306
+ <span className={item.published ? "chip chip-on" : "chip"}>
307
+ {item.published ? "Published" : "Draft"}
242
308
  </span>
243
- </label>
244
-
245
- <div className="todo-body">
246
- {editingId === todo.id ? (
247
- <input
248
- className="edit-input"
249
- value={editTitle}
250
- onChange={(event) => setEditTitle(event.target.value)}
251
- aria-label="Edit title"
252
- autoFocus
253
- />
309
+ </Field>
310
+ <Field label="Category" type="select">
311
+ <span className="chip">
312
+ {categoryLabels[item.category ?? ""] ?? item.category ?? "—"}
313
+ </span>
314
+ </Field>
315
+ <Field label="Release date" type="date">
316
+ {formatDate(item.releaseDate)}
317
+ </Field>
318
+ <Field label="Related items" type="relation">
319
+ {(item.related ?? []).length === 0 ? (
320
+ "—"
254
321
  ) : (
255
- <span className="todo-title">{todo.title}</span>
322
+ <span className="related-list">
323
+ {(item.related ?? []).map((id) => (
324
+ <span className="chip" key={id}>
325
+ {titles.get(id) ?? `#${id}`}
326
+ </span>
327
+ ))}
328
+ </span>
256
329
  )}
257
-
258
- <div className="todo-meta">
259
- {priority ? (
260
- <span className={priorityClass}>{priority}</span>
261
- ) : null}
262
- {todo.dueDate ? (
263
- <span className="due">
264
- {formatDueDate(todo.dueDate)}
265
- </span>
266
- ) : null}
267
- </div>
268
- </div>
269
-
270
- <div className="todo-actions">
271
- {editingId === todo.id ? (
272
- <>
273
- <button
274
- className="btn btn-small btn-primary"
275
- type="button"
276
- onClick={() => void saveEdit()}
277
- >
278
- Save
279
- </button>
280
- <button
281
- className="btn btn-small btn-ghost"
282
- type="button"
283
- onClick={() => setEditingId(null)}
284
- >
285
- Cancel
286
- </button>
287
- </>
330
+ </Field>
331
+ <Field label="Cover" type="media">
332
+ {item.cover && isImage(item.cover) ? (
333
+ <a href={item.cover} target="_blank" rel="noreferrer">
334
+ <img
335
+ className="media-thumb"
336
+ src={item.cover}
337
+ alt=""
338
+ />
339
+ </a>
288
340
  ) : (
289
- <>
290
- <button
291
- className="btn btn-small btn-ghost"
292
- type="button"
293
- onClick={() => startEdit(todo)}
294
- >
295
- Edit
296
- </button>
297
- <button
298
- className="btn btn-small btn-danger"
299
- type="button"
300
- onClick={() => void remove(todo.id)}
301
- >
302
- Remove
303
- </button>
304
- </>
341
+ item.cover || "—"
305
342
  )}
306
- </div>
307
- </li>
308
- );
309
- })}
310
- </ul>
343
+ </Field>
344
+ <Field label="Gallery" type="media-list">
345
+ {(item.gallery ?? []).length === 0 ? (
346
+ "—"
347
+ ) : (
348
+ <span className="gallery">
349
+ {(item.gallery ?? []).map((media, index) =>
350
+ isImage(media.url) ? (
351
+ <img
352
+ className="media-thumb"
353
+ src={media.url}
354
+ alt={media.alt ?? ""}
355
+ key={`${media.url}-${index}`}
356
+ />
357
+ ) : (
358
+ <a
359
+ href={media.url}
360
+ target="_blank"
361
+ rel="noreferrer"
362
+ key={`${media.url}-${index}`}
363
+ >
364
+ {media.url.split("/").pop() ?? media.url}
365
+ </a>
366
+ ),
367
+ )}
368
+ </span>
369
+ )}
370
+ </Field>
371
+ <Field label="Features" type="list">
372
+ {(item.features ?? []).length === 0 ? (
373
+ "—"
374
+ ) : (
375
+ <span className="related-list">
376
+ {(item.features ?? []).map((feature, index) => (
377
+ <span className="chip" key={`${feature}-${index}`}>
378
+ {feature}
379
+ </span>
380
+ ))}
381
+ </span>
382
+ )}
383
+ </Field>
384
+ <Field label="Links" type="object-list">
385
+ {(item.links ?? []).length === 0 ? (
386
+ "—"
387
+ ) : (
388
+ <ul className="object-links">
389
+ {(item.links ?? []).map((link, index) => (
390
+ <li key={`${link.label}-${index}`}>
391
+ {link.url ? (
392
+ <a href={link.url} target="_blank" rel="noreferrer">
393
+ {link.label}
394
+ </a>
395
+ ) : (
396
+ link.label
397
+ )}
398
+ </li>
399
+ ))}
400
+ </ul>
401
+ )}
402
+ </Field>
403
+ </dl>
404
+ </article>
405
+ ))}
406
+ </div>
311
407
  )}
312
408
  </section>
313
409
 
314
410
  <footer className="foot">
315
- Powered by <code><a href="https://www.npmjs.com/package/@eutobias/serenojs">@eutobias/serenojs</a></code>
411
+ Powered by{" "}
412
+ <code>
413
+ <a href="https://www.npmjs.com/package/@eutobias/serenojs">
414
+ @eutobias/serenojs
415
+ </a>
416
+ </code>
316
417
  </footer>
317
418
  </main>
318
419
  );
@@ -1,6 +1,6 @@
1
1
  import type { CollectionDef } from "@eutobias/serenojs/config";
2
2
 
3
- import { todos } from "./todos";
3
+ import { showcase } from "./showcase";
4
4
 
5
5
  export { defaultLocale, localeLabel, locales } from "./locales";
6
6
  export type { LocaleDef } from "./locales";
@@ -14,4 +14,4 @@ export const schemaTitle = "SerenoJS";
14
14
  * To add a new collection: create a `<name>.ts` file in this folder exporting
15
15
  * a `CollectionDef` and register it in the array below.
16
16
  */
17
- export const collections: CollectionDef[] = [todos];
17
+ export const collections: CollectionDef[] = [showcase];