@eutobias/serenojs 0.0.0-stage → 0.1.1

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.
Files changed (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +682 -2
  3. package/admin-dist/assets/index-B3EgqtT6.js +9 -0
  4. package/admin-dist/assets/index-D2m0Eb4k.css +2 -0
  5. package/admin-dist/index.html +17 -0
  6. package/dist/auth/auth.server.d.ts +31 -0
  7. package/dist/auth/auth.server.js +141 -0
  8. package/dist/auth/config.d.ts +32 -0
  9. package/dist/auth/config.js +25 -0
  10. package/dist/auth/cookies.server.d.ts +7 -0
  11. package/dist/auth/cookies.server.js +65 -0
  12. package/dist/auth/http.server.d.ts +8 -0
  13. package/dist/auth/http.server.js +30 -0
  14. package/dist/auth/password.server.d.ts +2 -0
  15. package/dist/auth/password.server.js +21 -0
  16. package/dist/auth/session.server.d.ts +2 -0
  17. package/dist/auth/session.server.js +14 -0
  18. package/dist/auth/users.server.d.ts +16 -0
  19. package/dist/auth/users.server.js +123 -0
  20. package/dist/config.d.ts +91 -0
  21. package/dist/config.js +39 -0
  22. package/dist/core/backup.server.d.ts +52 -0
  23. package/dist/core/backup.server.js +349 -0
  24. package/dist/core/db.server.d.ts +24 -0
  25. package/dist/core/db.server.js +526 -0
  26. package/dist/core/media.d.ts +22 -0
  27. package/dist/core/media.js +76 -0
  28. package/dist/core/media.server.d.ts +18 -0
  29. package/dist/core/media.server.js +102 -0
  30. package/dist/core/schema.d.ts +26 -0
  31. package/dist/core/schema.js +99 -0
  32. package/dist/core/types.d.ts +143 -0
  33. package/dist/core/types.js +1 -0
  34. package/dist/core/validation.d.ts +16 -0
  35. package/dist/core/validation.js +192 -0
  36. package/dist/locale.d.ts +2 -0
  37. package/dist/locale.js +14 -0
  38. package/dist/runtime.d.ts +8 -0
  39. package/dist/runtime.js +37 -0
  40. package/dist/server/app.d.ts +20 -0
  41. package/dist/server/app.js +661 -0
  42. package/dist/ui/admin/admin-shell.d.ts +16 -0
  43. package/dist/ui/admin/admin-shell.js +38 -0
  44. package/dist/ui/admin/backup-manager.d.ts +5 -0
  45. package/dist/ui/admin/backup-manager.js +165 -0
  46. package/dist/ui/admin/collection-icon.d.ts +22 -0
  47. package/dist/ui/admin/collection-icon.js +34 -0
  48. package/dist/ui/admin/collection-manager.d.ts +7 -0
  49. package/dist/ui/admin/collection-manager.js +212 -0
  50. package/dist/ui/admin/display.d.ts +7 -0
  51. package/dist/ui/admin/display.js +65 -0
  52. package/dist/ui/admin/field-control.d.ts +14 -0
  53. package/dist/ui/admin/field-control.js +58 -0
  54. package/dist/ui/admin/i18n.d.ts +27 -0
  55. package/dist/ui/admin/i18n.js +324 -0
  56. package/dist/ui/admin/item-form.d.ts +20 -0
  57. package/dist/ui/admin/item-form.js +60 -0
  58. package/dist/ui/admin/list-control.d.ts +13 -0
  59. package/dist/ui/admin/list-control.js +31 -0
  60. package/dist/ui/admin/locales.d.ts +4 -0
  61. package/dist/ui/admin/locales.js +8 -0
  62. package/dist/ui/admin/login-form.d.ts +3 -0
  63. package/dist/ui/admin/login-form.js +52 -0
  64. package/dist/ui/admin/media-control.d.ts +14 -0
  65. package/dist/ui/admin/media-control.js +74 -0
  66. package/dist/ui/admin/media-list-control.d.ts +14 -0
  67. package/dist/ui/admin/media-list-control.js +91 -0
  68. package/dist/ui/admin/pagination.d.ts +11 -0
  69. package/dist/ui/admin/pagination.js +14 -0
  70. package/dist/ui/admin/relation-control.d.ts +14 -0
  71. package/dist/ui/admin/relation-control.js +33 -0
  72. package/dist/ui/admin/router.d.ts +17 -0
  73. package/dist/ui/admin/router.js +58 -0
  74. package/dist/ui/admin/runtime.d.ts +28 -0
  75. package/dist/ui/admin/runtime.js +29 -0
  76. package/dist/ui/admin/sidebar.d.ts +13 -0
  77. package/dist/ui/admin/sidebar.js +29 -0
  78. package/dist/ui/admin/standalone-manager.d.ts +11 -0
  79. package/dist/ui/admin/standalone-manager.js +51 -0
  80. package/dist/ui/admin/table.d.ts +21 -0
  81. package/dist/ui/admin/table.js +23 -0
  82. package/dist/ui/admin/toast.d.ts +16 -0
  83. package/dist/ui/admin/toast.js +59 -0
  84. package/dist/ui/admin/users-manager.d.ts +6 -0
  85. package/dist/ui/admin/users-manager.js +157 -0
  86. package/dist/ui/badge.d.ts +9 -0
  87. package/dist/ui/badge.js +14 -0
  88. package/dist/ui/box.d.ts +17 -0
  89. package/dist/ui/box.js +14 -0
  90. package/dist/ui/button.d.ts +25 -0
  91. package/dist/ui/button.js +28 -0
  92. package/dist/ui/card.d.ts +45 -0
  93. package/dist/ui/card.js +49 -0
  94. package/dist/ui/container.d.ts +13 -0
  95. package/dist/ui/container.js +13 -0
  96. package/dist/ui/drawer.d.ts +15 -0
  97. package/dist/ui/drawer.js +31 -0
  98. package/dist/ui/field-wrapper.d.ts +15 -0
  99. package/dist/ui/field-wrapper.js +11 -0
  100. package/dist/ui/index.d.ts +8 -0
  101. package/dist/ui/index.js +8 -0
  102. package/dist/ui/text.d.ts +19 -0
  103. package/dist/ui/text.js +40 -0
  104. package/package.json +81 -3
  105. package/src/admin/app.tsx +371 -0
  106. package/src/admin/index.html +16 -0
  107. package/src/admin/main.tsx +42 -0
  108. package/src/admin/styles.css +9 -0
  109. package/src/auth/auth.server.ts +203 -0
  110. package/src/auth/config.ts +46 -0
  111. package/src/auth/cookies.server.ts +84 -0
  112. package/src/auth/http.server.ts +32 -0
  113. package/src/auth/password.server.ts +25 -0
  114. package/src/auth/session.server.ts +16 -0
  115. package/src/auth/users.server.ts +159 -0
  116. package/src/config.ts +120 -0
  117. package/src/core/backup.server.ts +446 -0
  118. package/src/core/db.server.ts +685 -0
  119. package/src/core/media.server.ts +136 -0
  120. package/src/core/media.ts +91 -0
  121. package/src/core/schema.ts +126 -0
  122. package/src/core/types.ts +194 -0
  123. package/src/core/validation.ts +215 -0
  124. package/src/global.d.ts +1 -0
  125. package/src/locale.ts +16 -0
  126. package/src/runtime.ts +54 -0
  127. package/src/server/app.ts +737 -0
  128. package/src/ui/admin/admin-shell.tsx +106 -0
  129. package/src/ui/admin/backup-manager.tsx +327 -0
  130. package/src/ui/admin/collection-icon.tsx +69 -0
  131. package/src/ui/admin/collection-manager.tsx +408 -0
  132. package/src/ui/admin/display.tsx +138 -0
  133. package/src/ui/admin/field-control.tsx +214 -0
  134. package/src/ui/admin/i18n.tsx +401 -0
  135. package/src/ui/admin/item-form.tsx +200 -0
  136. package/src/ui/admin/list-control.tsx +121 -0
  137. package/src/ui/admin/locales.ts +12 -0
  138. package/src/ui/admin/login-form.tsx +98 -0
  139. package/src/ui/admin/media-control.tsx +161 -0
  140. package/src/ui/admin/media-list-control.tsx +242 -0
  141. package/src/ui/admin/pagination.tsx +58 -0
  142. package/src/ui/admin/relation-control.tsx +142 -0
  143. package/src/ui/admin/router.tsx +105 -0
  144. package/src/ui/admin/runtime.tsx +58 -0
  145. package/src/ui/admin/sidebar.tsx +178 -0
  146. package/src/ui/admin/standalone-manager.tsx +103 -0
  147. package/src/ui/admin/table.tsx +129 -0
  148. package/src/ui/admin/toast.tsx +126 -0
  149. package/src/ui/admin/users-manager.tsx +344 -0
  150. package/src/ui/badge.tsx +27 -0
  151. package/src/ui/box.tsx +33 -0
  152. package/src/ui/button.tsx +77 -0
  153. package/src/ui/card.tsx +92 -0
  154. package/src/ui/container.tsx +28 -0
  155. package/src/ui/drawer.tsx +104 -0
  156. package/src/ui/field-wrapper.tsx +54 -0
  157. package/src/ui/index.ts +8 -0
  158. package/src/ui/text.tsx +93 -0
@@ -0,0 +1,242 @@
1
+ "use client";
2
+
3
+ import { useRef, useState } from "react";
4
+ import {
5
+ FiArrowLeft,
6
+ FiArrowRight,
7
+ FiStar,
8
+ FiTrash2,
9
+ FiUpload,
10
+ } from "react-icons/fi";
11
+
12
+ import { acceptAttribute, isImageUrl } from "../../core/media.js";
13
+ import type { FieldDef, MediaItem } from "../../core/types.js";
14
+ import { Box } from "../box.js";
15
+ import { Button, IconButton } from "../button.js";
16
+ import { FieldWrapper } from "../field-wrapper.js";
17
+ import { useCmsUrls } from "./runtime.js";
18
+ import { Text } from "../text.js";
19
+ import { useI18n } from "./i18n.js";
20
+
21
+ export type MediaListControlProps = {
22
+ field: FieldDef;
23
+ collectionSlug: string;
24
+ value: MediaItem[];
25
+ error?: string | undefined;
26
+ disabled?: boolean | undefined;
27
+ onChange: (value: MediaItem[]) => void;
28
+ };
29
+
30
+ async function uploadFile(
31
+ file: File,
32
+ collectionSlug: string,
33
+ fieldName: string,
34
+ mediaPath: string,
35
+ uploadFailed: string,
36
+ ): Promise<string> {
37
+ const params = new URLSearchParams({
38
+ collection: collectionSlug,
39
+ field: fieldName,
40
+ });
41
+ const form = new FormData();
42
+ form.append("file", file);
43
+ const response = await fetch(`${mediaPath}?${params.toString()}`, {
44
+ method: "POST",
45
+ body: form,
46
+ });
47
+ const json = (await response.json().catch(() => null)) as
48
+ | { media?: { url?: string }; message?: string }
49
+ | null;
50
+ const url = json?.media?.url;
51
+ if (!response.ok || !url) {
52
+ throw new Error(json?.message ?? uploadFailed);
53
+ }
54
+ return url;
55
+ }
56
+
57
+ /**
58
+ * Native `media-list` widget: upload several images, reorder them and pick one
59
+ * as the principal (cover/highlight).
60
+ */
61
+ export const MediaListControl = ({
62
+ field,
63
+ collectionSlug,
64
+ value,
65
+ error,
66
+ disabled,
67
+ onChange,
68
+ }: MediaListControlProps) => {
69
+ const { media } = useCmsUrls();
70
+ const { t } = useI18n();
71
+ const inputRef = useRef<HTMLInputElement>(null);
72
+ const [uploading, setUploading] = useState(false);
73
+ const [localError, setLocalError] = useState<string | null>(null);
74
+
75
+ const ensurePrimary = (items: MediaItem[]): MediaItem[] => {
76
+ if (items.length === 0 || items.some((item) => item.primary)) return items;
77
+ const [first, ...rest] = items;
78
+ return first ? [{ ...first, primary: true }, ...rest] : items;
79
+ };
80
+
81
+ const setPrimary = (index: number) =>
82
+ onChange(value.map((item, i) => ({ ...item, primary: i === index })));
83
+
84
+ const remove = (index: number) =>
85
+ onChange(ensurePrimary(value.filter((_, i) => i !== index)));
86
+
87
+ const move = (index: number, direction: -1 | 1) => {
88
+ const target = index + direction;
89
+ if (target < 0 || target >= value.length) return;
90
+ const next = [...value];
91
+ const current = next[index];
92
+ const swap = next[target];
93
+ if (!current || !swap) return;
94
+ next[index] = swap;
95
+ next[target] = current;
96
+ onChange(next);
97
+ };
98
+
99
+ const onFiles = async (files: FileList | null) => {
100
+ if (!files || files.length === 0) return;
101
+ setUploading(true);
102
+ setLocalError(null);
103
+ try {
104
+ const urls: string[] = [];
105
+ for (const file of Array.from(files)) {
106
+ urls.push(await uploadFile(file, collectionSlug, field.name, media(), t("media.uploadFailed")));
107
+ }
108
+ const additions: MediaItem[] = urls.map((url, index) => ({
109
+ url,
110
+ alt: "",
111
+ primary: value.length === 0 && index === 0,
112
+ }));
113
+ onChange(ensurePrimary([...value, ...additions]));
114
+ } catch (uploadError) {
115
+ setLocalError(
116
+ uploadError instanceof Error ? uploadError.message : t("media.uploadFailed"),
117
+ );
118
+ } finally {
119
+ setUploading(false);
120
+ if (inputRef.current) inputRef.current.value = "";
121
+ }
122
+ };
123
+
124
+ const busy = disabled || uploading;
125
+
126
+ return (
127
+ <FieldWrapper
128
+ label={field.label}
129
+ required={field.required}
130
+ help={field.help}
131
+ error={error ?? localError ?? undefined}
132
+ >
133
+ <Box className="flex-col gap-3">
134
+ {value.length === 0 ? (
135
+ <Text size="caption" className="text-gray-400">
136
+ {t("media.noMedia")}
137
+ </Text>
138
+ ) : (
139
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
140
+ {value.map((item, index) => (
141
+ <Box
142
+ key={`${item.url}-${index}`}
143
+ className={`flex-col overflow-hidden rounded-md border bg-white ${
144
+ item.primary
145
+ ? "border-gray-900 ring-1 ring-gray-900"
146
+ : "border-gray-200"
147
+ }`}
148
+ >
149
+ <Box className="relative">
150
+ {isImageUrl(item.url) ? (
151
+ // eslint-disable-next-line @next/next/no-img-element
152
+ <img
153
+ src={item.url}
154
+ alt={item.alt ?? ""}
155
+ className="aspect-[4/3] w-full object-cover"
156
+ />
157
+ ) : (
158
+ <a
159
+ href={item.url}
160
+ target="_blank"
161
+ rel="noreferrer"
162
+ className="block truncate p-3 text-xs text-gray-600 underline"
163
+ >
164
+ {item.url}
165
+ </a>
166
+ )}
167
+ {item.primary ? (
168
+ <span className="absolute left-2 top-2 rounded bg-gray-900 px-1.5 py-0.5 text-[10px] font-bold uppercase text-white">
169
+ {t("media.primary")}
170
+ </span>
171
+ ) : null}
172
+ </Box>
173
+ <Box className="flex-wrap items-center justify-between gap-0.5 border-t border-gray-100 p-1">
174
+ <IconButton
175
+ type="button"
176
+ label={t("media.moveBack")}
177
+ disabled={busy || index === 0}
178
+ onClick={() => move(index, -1)}
179
+ >
180
+ <FiArrowLeft aria-hidden />
181
+ </IconButton>
182
+ <IconButton
183
+ type="button"
184
+ label={t("media.setPrimary")}
185
+ disabled={busy || item.primary}
186
+ className={item.primary ? "text-amber-500" : ""}
187
+ onClick={() => setPrimary(index)}
188
+ >
189
+ <FiStar aria-hidden />
190
+ </IconButton>
191
+ <IconButton
192
+ type="button"
193
+ label={t("media.moveForward")}
194
+ disabled={busy || index === value.length - 1}
195
+ onClick={() => move(index, 1)}
196
+ >
197
+ <FiArrowRight aria-hidden />
198
+ </IconButton>
199
+ <IconButton
200
+ type="button"
201
+ label={t("common.remove")}
202
+ className="text-red-600 hover:bg-red-50 hover:text-red-700"
203
+ disabled={busy}
204
+ onClick={() => remove(index)}
205
+ >
206
+ <FiTrash2 aria-hidden />
207
+ </IconButton>
208
+ </Box>
209
+ </Box>
210
+ ))}
211
+ </div>
212
+ )}
213
+
214
+ <Box className="items-center gap-3">
215
+ <Button
216
+ type="button"
217
+ variant="secondary"
218
+ size="sm"
219
+ disabled={busy}
220
+ onClick={() => inputRef.current?.click()}
221
+ >
222
+ <FiUpload aria-hidden className="mr-1.5" />
223
+ {uploading ? t("media.uploading") : t("media.addImages")}
224
+ </Button>
225
+ <Text size="caption" className="text-gray-400">
226
+ {t("media.count", { count: value.length })}
227
+ </Text>
228
+ </Box>
229
+
230
+ <input
231
+ ref={inputRef}
232
+ type="file"
233
+ multiple
234
+ accept={acceptAttribute(field)}
235
+ disabled={busy}
236
+ className="hidden"
237
+ onChange={(event) => void onFiles(event.target.files)}
238
+ />
239
+ </Box>
240
+ </FieldWrapper>
241
+ );
242
+ };
@@ -0,0 +1,58 @@
1
+ import { Box } from "../box.js";
2
+ import { Button } from "../button.js";
3
+ import { Text } from "../text.js";
4
+ import { useI18n } from "./i18n.js";
5
+
6
+ export type PaginationProps = {
7
+ page: number;
8
+ totalPages: number;
9
+ total: number;
10
+ limit: number;
11
+ onPage: (page: number) => void;
12
+ };
13
+
14
+ /**
15
+ * Simple previous/next pagination with a result summary.
16
+ */
17
+ export const Pagination = ({
18
+ page,
19
+ totalPages,
20
+ total,
21
+ limit,
22
+ onPage,
23
+ }: PaginationProps) => {
24
+ const { t } = useI18n();
25
+ const from = total === 0 ? 0 : (page - 1) * limit + 1;
26
+ const to = Math.min(page * limit, total);
27
+
28
+ return (
29
+ <Box className="items-center justify-between gap-4 pt-4">
30
+ <Text size="caption" className="text-gray-500">
31
+ {t("pagination.range", { from, to, total })}
32
+ </Text>
33
+ <Box className="items-center gap-2">
34
+ <Button
35
+ type="button"
36
+ variant="secondary"
37
+ size="sm"
38
+ disabled={page <= 1}
39
+ onClick={() => onPage(page - 1)}
40
+ >
41
+ {t("pagination.previous")}
42
+ </Button>
43
+ <Text size="caption" className="px-1 text-gray-600">
44
+ {page} / {totalPages}
45
+ </Text>
46
+ <Button
47
+ type="button"
48
+ variant="secondary"
49
+ size="sm"
50
+ disabled={page >= totalPages}
51
+ onClick={() => onPage(page + 1)}
52
+ >
53
+ {t("pagination.next")}
54
+ </Button>
55
+ </Box>
56
+ </Box>
57
+ );
58
+ };
@@ -0,0 +1,142 @@
1
+ "use client";
2
+
3
+ import type {
4
+ FieldDef,
5
+ FieldValue,
6
+ RelationOption,
7
+ } from "../../core/types.js";
8
+ import { relationIsMany } from "../../core/schema.js";
9
+ import { Box } from "../box.js";
10
+ import { FieldWrapper, inputClass } from "../field-wrapper.js";
11
+ import { Text } from "../text.js";
12
+ import { useI18n } from "./i18n.js";
13
+
14
+ export type RelationControlProps = {
15
+ field: FieldDef;
16
+ value: FieldValue;
17
+ options: RelationOption[];
18
+ error?: string | undefined;
19
+ disabled?: boolean | undefined;
20
+ onChange: (value: FieldValue) => void;
21
+ };
22
+
23
+ /**
24
+ * Renders a relation field: a `<select>` for singular relations, a scrollable
25
+ * checkbox list for plural ones.
26
+ */
27
+ export const RelationControl = ({
28
+ field,
29
+ value,
30
+ options,
31
+ error,
32
+ disabled,
33
+ onChange,
34
+ }: RelationControlProps) => {
35
+ const { t } = useI18n();
36
+ const id = `field-${field.name}`;
37
+ const label = `${field.label} (${field.relation?.to ?? ""})`;
38
+ const many = relationIsMany(field);
39
+
40
+ return (
41
+ <FieldWrapper
42
+ label={label}
43
+ htmlFor={id}
44
+ required={field.required}
45
+ help={field.help}
46
+ error={error}
47
+ >
48
+ {many ? (
49
+ <ManyControl
50
+ id={id}
51
+ disabled={disabled}
52
+ options={options}
53
+ selected={Array.isArray(value) ? (value as number[]) : []}
54
+ onChange={onChange}
55
+ />
56
+ ) : (
57
+ <select
58
+ id={id}
59
+ disabled={disabled}
60
+ aria-invalid={Boolean(error)}
61
+ value={value === null || value === undefined ? "" : String(value)}
62
+ onChange={(event) =>
63
+ onChange(event.target.value === "" ? null : Number(event.target.value))
64
+ }
65
+ className={`${inputClass} ${
66
+ error
67
+ ? "border-red-400 focus:border-red-500 focus:ring-red-500"
68
+ : "border-gray-300"
69
+ }`}
70
+ >
71
+ <option value="">{t("field.none")}</option>
72
+ {options.map((option) => (
73
+ <option key={option.id} value={option.id}>
74
+ {option.label}
75
+ </option>
76
+ ))}
77
+ </select>
78
+ )}
79
+ </FieldWrapper>
80
+ );
81
+ };
82
+
83
+ type ManyControlProps = {
84
+ id: string;
85
+ disabled?: boolean | undefined;
86
+ options: RelationOption[];
87
+ selected: number[];
88
+ onChange: (value: FieldValue) => void;
89
+ };
90
+
91
+ const ManyControl = ({
92
+ id,
93
+ disabled,
94
+ options,
95
+ selected,
96
+ onChange,
97
+ }: ManyControlProps) => {
98
+ const { t } = useI18n();
99
+ const toggle = (optionId: number) => {
100
+ const next = selected.includes(optionId)
101
+ ? selected.filter((entry) => entry !== optionId)
102
+ : [...selected, optionId];
103
+ onChange(next);
104
+ };
105
+
106
+ return (
107
+ <Box
108
+ id={id}
109
+ className={`max-h-44 flex-col gap-1 overflow-y-auto rounded-md border bg-white p-1.5 ${
110
+ disabled ? "opacity-60" : ""
111
+ }`}
112
+ >
113
+ {options.length === 0 ? (
114
+ <Text size="caption" className="px-2 py-3 text-gray-400">
115
+ {t("relation.empty")}
116
+ </Text>
117
+ ) : (
118
+ options.map((option) => {
119
+ const checked = selected.includes(option.id);
120
+ return (
121
+ <Box
122
+ as="label"
123
+ key={option.id}
124
+ className="cursor-pointer items-center gap-2 rounded px-2 py-1.5 transition-colors hover:bg-gray-50"
125
+ >
126
+ <input
127
+ type="checkbox"
128
+ checked={checked}
129
+ disabled={disabled}
130
+ onChange={() => toggle(option.id)}
131
+ className="h-4 w-4 cursor-pointer accent-gray-900"
132
+ />
133
+ <Text size="caption" className="text-gray-700">
134
+ {option.label}
135
+ </Text>
136
+ </Box>
137
+ );
138
+ })
139
+ )}
140
+ </Box>
141
+ );
142
+ };
@@ -0,0 +1,105 @@
1
+ "use client";
2
+
3
+ import {
4
+ createContext,
5
+ useCallback,
6
+ useContext,
7
+ useEffect,
8
+ useMemo,
9
+ useState,
10
+ type AnchorHTMLAttributes,
11
+ type MouseEvent,
12
+ type ReactNode,
13
+ } from "react";
14
+
15
+ import { joinPath, useCms } from "./runtime.js";
16
+
17
+ type RouterValue = {
18
+ /** Current path relative to the admin mount path (`/`, `/todos`, ...). */
19
+ path: string;
20
+ navigate: (to: string) => void;
21
+ };
22
+
23
+ const RouterContext = createContext<RouterValue | null>(null);
24
+
25
+ function relativePath(pathname: string, base: string): string {
26
+ const basePath = base.replace(/\/+$/, "");
27
+ if (pathname === basePath) return "/";
28
+ if (pathname.startsWith(`${basePath}/`)) {
29
+ const rest = pathname.slice(basePath.length);
30
+ return rest.startsWith("/") ? rest : `/${rest}`;
31
+ }
32
+ return "/";
33
+ }
34
+
35
+ export function RouterProvider({
36
+ basePath,
37
+ children,
38
+ }: {
39
+ basePath: string;
40
+ children: ReactNode;
41
+ }) {
42
+ const [path, setPath] = useState(() =>
43
+ typeof window === "undefined" ? "/" : relativePath(window.location.pathname, basePath),
44
+ );
45
+
46
+ useEffect(() => {
47
+ const onPop = () => setPath(relativePath(window.location.pathname, basePath));
48
+ window.addEventListener("popstate", onPop);
49
+ return () => window.removeEventListener("popstate", onPop);
50
+ }, [basePath]);
51
+
52
+ const navigate = useCallback(
53
+ (to: string) => {
54
+ const absolute = joinPath(basePath, to);
55
+ if (absolute !== window.location.pathname) {
56
+ window.history.pushState(null, "", absolute);
57
+ }
58
+ setPath(relativePath(absolute, basePath));
59
+ },
60
+ [basePath],
61
+ );
62
+
63
+ const value = useMemo(() => ({ path, navigate }), [path, navigate]);
64
+ return <RouterContext.Provider value={value}>{children}</RouterContext.Provider>;
65
+ }
66
+
67
+ export function useRouter(): RouterValue {
68
+ const value = useContext(RouterContext);
69
+ if (!value) {
70
+ throw new Error("[serenojs] RouterProvider is missing.");
71
+ }
72
+ return value;
73
+ }
74
+
75
+ type LinkProps = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"> & {
76
+ to: string;
77
+ };
78
+
79
+ /** Internal link that preserves the SPA history. */
80
+ export function Link({ to, onClick, children, ...rest }: LinkProps) {
81
+ const { navigate } = useRouter();
82
+ const { adminPath } = useCms();
83
+
84
+ const handleClick = (event: MouseEvent<HTMLAnchorElement>) => {
85
+ onClick?.(event);
86
+ if (
87
+ event.defaultPrevented ||
88
+ event.button !== 0 ||
89
+ event.metaKey ||
90
+ event.ctrlKey ||
91
+ event.shiftKey ||
92
+ event.altKey
93
+ ) {
94
+ return;
95
+ }
96
+ event.preventDefault();
97
+ navigate(to);
98
+ };
99
+
100
+ return (
101
+ <a href={joinPath(adminPath, to)} onClick={handleClick} {...rest}>
102
+ {children}
103
+ </a>
104
+ );
105
+ }
@@ -0,0 +1,58 @@
1
+ "use client";
2
+
3
+ import { createContext, useContext, useMemo, type ReactNode } from "react";
4
+
5
+ import type { CollectionDef, LocaleDef } from "../../config.js";
6
+
7
+ /** Payload injected into the admin shell by the server (no secrets). */
8
+ export type AdminRuntimeConfig = {
9
+ title: string;
10
+ adminPath: string;
11
+ apiPath: string;
12
+ authPath: string;
13
+ mediaPath: string;
14
+ filesPath: string;
15
+ backupPath: string;
16
+ collections: CollectionDef[];
17
+ locales: LocaleDef[];
18
+ defaultLocale: string;
19
+ };
20
+
21
+ const RuntimeContext = createContext<AdminRuntimeConfig | null>(null);
22
+
23
+ export function AdminRuntimeProvider({
24
+ value,
25
+ children,
26
+ }: {
27
+ value: AdminRuntimeConfig;
28
+ children: ReactNode;
29
+ }) {
30
+ return <RuntimeContext.Provider value={value}>{children}</RuntimeContext.Provider>;
31
+ }
32
+
33
+ export function useCms(): AdminRuntimeConfig {
34
+ const value = useContext(RuntimeContext);
35
+ if (!value) {
36
+ throw new Error("[serenojs] AdminRuntimeProvider is missing.");
37
+ }
38
+ return value;
39
+ }
40
+
41
+ /** Join a mount path and a relative segment without double slashes. */
42
+ export function joinPath(base: string, segment: string): string {
43
+ if (!segment) return base;
44
+ return `${base.replace(/\/+$/, "")}/${segment.replace(/^\/+/, "")}`;
45
+ }
46
+
47
+ export function useCmsUrls() {
48
+ const config = useCms();
49
+ return useMemo(
50
+ () => ({
51
+ api: (path: string) => joinPath(config.apiPath, path),
52
+ auth: (path: string) => joinPath(config.authPath, path),
53
+ media: (query = "") => `${config.mediaPath}${query ? `?${query}` : ""}`,
54
+ backup: (query = "") => `${config.backupPath}${query ? `?${query}` : ""}`,
55
+ }),
56
+ [config.apiPath, config.authPath, config.mediaPath, config.backupPath],
57
+ );
58
+ }