@ampless/admin 0.2.0-alpha.7 → 1.0.0-alpha.26

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 (48) hide show
  1. package/README.ja.md +73 -0
  2. package/README.md +3 -0
  3. package/dist/api/index.d.ts +1 -1
  4. package/dist/chunk-2ITWLRYF.js +38 -0
  5. package/dist/chunk-2U3POKAZ.js +198 -0
  6. package/dist/{chunk-VXEVLHGL.js → chunk-6LQGVDCW.js} +2 -2
  7. package/dist/chunk-6NPYUTV6.js +250 -0
  8. package/dist/chunk-6SB7YICQ.js +48 -0
  9. package/dist/chunk-6W3JIOOR.js +37 -0
  10. package/dist/chunk-CTGFMK2J.js +335 -0
  11. package/dist/chunk-G4CF5ZWV.js +1319 -0
  12. package/dist/chunk-KQOE5CT6.js +21 -0
  13. package/dist/chunk-MWSCSCCU.js +67 -0
  14. package/dist/chunk-Q66BLMNJ.js +33 -0
  15. package/dist/chunk-TZ5F24BG.js +149 -0
  16. package/dist/chunk-VL6MMF2P.js +21 -0
  17. package/dist/chunk-VSS5FWSR.js +334 -0
  18. package/dist/{chunk-L5NHN3MY.js → chunk-WL4IBW2D.js} +145 -43
  19. package/dist/chunk-YFWHKIVH.js +1187 -0
  20. package/dist/components/admin-dashboard.d.ts +10 -0
  21. package/dist/components/admin-dashboard.js +9 -0
  22. package/dist/components/edit-post-view.d.ts +9 -0
  23. package/dist/components/edit-post-view.js +12 -0
  24. package/dist/components/index.d.ts +14 -42
  25. package/dist/components/index.js +22 -33
  26. package/dist/components/login-view.d.ts +5 -0
  27. package/dist/components/login-view.js +9 -0
  28. package/dist/components/mcp-tokens-view.d.ts +16 -0
  29. package/dist/components/mcp-tokens-view.js +9 -0
  30. package/dist/components/media-view.d.ts +5 -0
  31. package/dist/components/media-view.js +12 -0
  32. package/dist/components/new-post-view.d.ts +5 -0
  33. package/dist/components/new-post-view.js +12 -0
  34. package/dist/components/posts-list-view.d.ts +5 -0
  35. package/dist/components/posts-list-view.js +9 -0
  36. package/dist/components/users-list-view.d.ts +7 -0
  37. package/dist/components/users-list-view.js +9 -0
  38. package/dist/{i18n-Bc4SYgWx.d.ts → i18n-BhMBRfio.d.ts} +215 -1
  39. package/dist/index.d.ts +18 -18
  40. package/dist/index.js +17 -38
  41. package/dist/lib/theme-actions.d.ts +3 -3
  42. package/dist/lib/theme-actions.js +1 -1
  43. package/dist/metafile-esm.json +1 -1
  44. package/dist/pages/index.d.ts +35 -16
  45. package/dist/pages/index.js +90 -257
  46. package/package.json +26 -14
  47. package/dist/chunk-GXPSAOES.js +0 -2823
  48. package/dist/login-view-BKrSZLJu.d.ts +0 -24
@@ -1,2823 +0,0 @@
1
- 'use client';
2
- import {
3
- ADMIN_SITE_COOKIE,
4
- publicMediaUrl,
5
- setAdminMediaContext,
6
- translate
7
- } from "./chunk-L5NHN3MY.js";
8
- import {
9
- invalidateSiteSettingsCache
10
- } from "./chunk-VXEVLHGL.js";
11
-
12
- // src/components/i18n-provider.tsx
13
- import { createContext, useContext, useMemo } from "react";
14
- import { jsx } from "react/jsx-runtime";
15
- var I18nContext = createContext(null);
16
- function I18nProvider({ locale, dict, children }) {
17
- const value = useMemo(() => ({ locale, dict }), [locale, dict]);
18
- return /* @__PURE__ */ jsx(I18nContext.Provider, { value, children });
19
- }
20
- function useT() {
21
- const ctx = useContext(I18nContext);
22
- if (!ctx) {
23
- throw new Error(
24
- "useT() called outside <I18nProvider>. Wrap the admin layout (or root layout) with <I18nProvider locale={...} dict={...}>."
25
- );
26
- }
27
- return (key, vars) => translate(ctx.dict, key, vars);
28
- }
29
- function useLocale() {
30
- const ctx = useContext(I18nContext);
31
- if (!ctx) throw new Error("useLocale() called outside <I18nProvider>.");
32
- return ctx.locale;
33
- }
34
-
35
- // src/lib/admin-site-client.ts
36
- import { DEFAULT_SITE_ID, isMultiSite } from "ampless";
37
- var cmsConfig = null;
38
- function setAdminCmsConfig(config) {
39
- cmsConfig = config;
40
- }
41
- function readAdminSiteIdFromCookie() {
42
- if (!cmsConfig) return DEFAULT_SITE_ID;
43
- if (!isMultiSite(cmsConfig)) return DEFAULT_SITE_ID;
44
- const sites = cmsConfig.sites ?? {};
45
- if (typeof document !== "undefined") {
46
- const match = document.cookie.match(
47
- new RegExp(`(?:^|;\\s*)${ADMIN_SITE_COOKIE}=([^;]+)`)
48
- );
49
- if (match) {
50
- const v = decodeURIComponent(match[1]);
51
- if (sites[v]) return v;
52
- }
53
- }
54
- const first = Object.keys(sites)[0];
55
- return first ?? DEFAULT_SITE_ID;
56
- }
57
-
58
- // src/lib/amplify-client.ts
59
- import { Amplify } from "aws-amplify";
60
- var configured = false;
61
- function configureAmplify(outputs) {
62
- if (configured) return;
63
- Amplify.configure(outputs, { ssr: true });
64
- configured = true;
65
- }
66
-
67
- // src/lib/posts-provider.ts
68
- import { generateClient } from "aws-amplify/api";
69
- import {
70
- setPostsProvider,
71
- composeSiteIdStatus,
72
- composeSiteIdSlug
73
- } from "ampless";
74
- function encodeBody(value) {
75
- return JSON.stringify(value ?? null);
76
- }
77
- function decodeBody(value) {
78
- if (typeof value !== "string") return value;
79
- try {
80
- return JSON.parse(value);
81
- } catch {
82
- return value;
83
- }
84
- }
85
- function decodeMetadata(value) {
86
- if (value === null || value === void 0) return void 0;
87
- const parsed = typeof value === "string" ? safeJsonParse(value) : value;
88
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
89
- }
90
- function safeJsonParse(value) {
91
- try {
92
- return JSON.parse(value);
93
- } catch {
94
- return value;
95
- }
96
- }
97
- function toCorePost(p) {
98
- return {
99
- postId: p.postId,
100
- siteId: p.siteId,
101
- slug: p.slug,
102
- title: p.title,
103
- excerpt: p.excerpt ?? void 0,
104
- format: p.format ?? "markdown",
105
- body: decodeBody(p.body),
106
- status: p.status ?? "draft",
107
- publishedAt: p.publishedAt ?? void 0,
108
- tags: (p.tags ?? []).filter((t) => typeof t === "string"),
109
- metadata: decodeMetadata(p.metadata)
110
- };
111
- }
112
- function postTagEntries(post) {
113
- if (post.status !== "published" || !post.publishedAt || !post.tags?.length) return [];
114
- return post.tags.map((tag) => ({
115
- siteIdTag: `${post.siteId}#${tag}`,
116
- publishedAtPostId: `${post.publishedAt}#${post.postId}`
117
- }));
118
- }
119
- function entryKey(e) {
120
- return `${e.siteIdTag}|${e.publishedAtPostId}`;
121
- }
122
- var installed = false;
123
- function installAdminPostsProvider() {
124
- if (installed) return;
125
- installed = true;
126
- const client = generateClient();
127
- async function syncPostTags(post, oldPost) {
128
- const oldEntries = oldPost ? postTagEntries(oldPost) : [];
129
- const newEntries = postTagEntries(post);
130
- const oldKeys = new Set(oldEntries.map(entryKey));
131
- const newKeys = new Set(newEntries.map(entryKey));
132
- function fullRow(e) {
133
- return {
134
- siteIdTag: e.siteIdTag,
135
- publishedAtPostId: e.publishedAtPostId,
136
- siteId: post.siteId,
137
- tag: e.siteIdTag.slice(post.siteId.length + 1),
138
- postId: post.postId,
139
- publishedAt: post.publishedAt,
140
- slug: post.slug,
141
- title: post.title,
142
- excerpt: post.excerpt,
143
- tags: post.tags ?? []
144
- };
145
- }
146
- async function upsertPostTag(e) {
147
- const row = fullRow(e);
148
- const upd = await client.models.PostTag.update(row);
149
- if (!upd.errors) return;
150
- const cre = await client.models.PostTag.create(row);
151
- if (cre.errors) {
152
- throw new Error(upd.errors[0]?.message ?? "PostTag.update failed");
153
- }
154
- }
155
- await Promise.all(
156
- oldEntries.filter((e) => !newKeys.has(entryKey(e))).map((e) => client.models.PostTag.delete(e))
157
- );
158
- await Promise.all(
159
- newEntries.filter((e) => !oldKeys.has(entryKey(e))).map(async (e) => {
160
- const cre = await client.models.PostTag.create(fullRow(e));
161
- if (!cre.errors) return;
162
- const upd = await client.models.PostTag.update(fullRow(e));
163
- if (upd.errors)
164
- throw new Error(cre.errors[0]?.message ?? "PostTag.create failed");
165
- })
166
- );
167
- await Promise.all(
168
- newEntries.filter((e) => oldKeys.has(entryKey(e))).map(upsertPostTag)
169
- );
170
- }
171
- const provider = {
172
- async list(opts = {}) {
173
- const siteId = opts.siteId ?? "default";
174
- const status = opts.status ?? "published";
175
- const filter = { siteId: { eq: siteId } };
176
- if (status !== "all") filter.status = { eq: status };
177
- const { data } = await client.models.Post.list({ filter, limit: opts.limit ?? 100 });
178
- return data.map(toCorePost);
179
- },
180
- async get(slug, opts = {}) {
181
- const siteId = opts.siteId ?? "default";
182
- const { data } = await client.models.Post.list({
183
- filter: { siteId: { eq: siteId }, slug: { eq: slug } },
184
- limit: 1
185
- });
186
- return data[0] ? toCorePost(data[0]) : null;
187
- },
188
- async getById(postId, opts = {}) {
189
- const siteId = opts.siteId ?? "default";
190
- const { data } = await client.models.Post.get({ siteId, postId });
191
- return data ? toCorePost(data) : null;
192
- },
193
- async create(input) {
194
- const postId = input.postId ?? `post-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
195
- const { data, errors } = await client.models.Post.create({
196
- siteId: input.siteId,
197
- postId,
198
- slug: input.slug,
199
- title: input.title,
200
- excerpt: input.excerpt,
201
- format: input.format,
202
- body: encodeBody(input.body),
203
- status: input.status,
204
- publishedAt: input.publishedAt,
205
- tags: input.tags,
206
- ...input.metadata !== void 0 && { metadata: encodeBody(input.metadata) },
207
- // Denormalized GSI keys. Must match every change to slug /
208
- // status — see the update() branch below.
209
- siteIdStatus: composeSiteIdStatus(input.siteId, input.status),
210
- siteIdSlug: composeSiteIdSlug(input.siteId, input.slug)
211
- });
212
- if (errors || !data) throw new Error(errors?.[0]?.message ?? "Failed to create post");
213
- const created = toCorePost(data);
214
- await syncPostTags(created, null);
215
- return created;
216
- },
217
- async update(postId, patch, opts = {}) {
218
- const siteId = opts.siteId ?? "default";
219
- const oldPost = await this.getById(postId, { siteId });
220
- const nextStatus = patch.status ?? oldPost?.status;
221
- const nextSlug = patch.slug ?? oldPost?.slug;
222
- const { data, errors } = await client.models.Post.update({
223
- siteId,
224
- postId,
225
- ...patch.slug !== void 0 && { slug: patch.slug },
226
- ...patch.title !== void 0 && { title: patch.title },
227
- ...patch.excerpt !== void 0 && { excerpt: patch.excerpt },
228
- ...patch.format !== void 0 && { format: patch.format },
229
- ...patch.body !== void 0 && { body: encodeBody(patch.body) },
230
- ...patch.status !== void 0 && { status: patch.status },
231
- ...patch.publishedAt !== void 0 && { publishedAt: patch.publishedAt },
232
- ...patch.tags !== void 0 && { tags: patch.tags },
233
- ...patch.metadata !== void 0 && { metadata: encodeBody(patch.metadata) },
234
- ...patch.status !== void 0 && nextStatus && { siteIdStatus: composeSiteIdStatus(siteId, nextStatus) },
235
- ...patch.slug !== void 0 && nextSlug && { siteIdSlug: composeSiteIdSlug(siteId, nextSlug) }
236
- });
237
- if (errors || !data) throw new Error(errors?.[0]?.message ?? "Failed to update post");
238
- const updated = toCorePost(data);
239
- await syncPostTags(updated, oldPost);
240
- return updated;
241
- },
242
- async remove(postId, opts = {}) {
243
- const siteId = opts.siteId ?? "default";
244
- const oldPost = await this.getById(postId, { siteId });
245
- if (oldPost) {
246
- await syncPostTags({ ...oldPost, status: "draft" }, oldPost);
247
- }
248
- const { errors } = await client.models.Post.delete({ siteId, postId });
249
- if (errors) throw new Error(errors[0]?.message ?? "Failed to delete post");
250
- }
251
- };
252
- setPostsProvider(provider);
253
- }
254
-
255
- // src/lib/kv-provider.ts
256
- import { generateClient as generateClient2 } from "aws-amplify/api";
257
- import { setKvStore } from "ampless";
258
- var installed2 = false;
259
- function installAdminKvProvider() {
260
- if (installed2) return;
261
- installed2 = true;
262
- const client = generateClient2();
263
- function requireModel() {
264
- const m = client.models.KvStore;
265
- if (!m) {
266
- throw new Error(
267
- "KvStore model is not available on the AppSync client. Did you redeploy the sandbox? Run `npx ampx sandbox` and wait for it to finish, then reload this page."
268
- );
269
- }
270
- return m;
271
- }
272
- function encodeValue(value) {
273
- return JSON.stringify(value ?? null);
274
- }
275
- function decodeValue(raw) {
276
- if (typeof raw !== "string") return raw;
277
- try {
278
- return JSON.parse(raw);
279
- } catch {
280
- return raw;
281
- }
282
- }
283
- const store = {
284
- async get(pk, sk) {
285
- const model = requireModel();
286
- const { data } = await model.get({ pk, sk });
287
- return data ? decodeValue(data.value) : null;
288
- },
289
- async query(pk) {
290
- const model = requireModel();
291
- const { data } = await model.list({
292
- filter: { pk: { eq: pk } },
293
- limit: 1e3
294
- });
295
- return (data ?? []).map((row) => ({
296
- pk: row.pk,
297
- sk: row.sk,
298
- value: decodeValue(row.value),
299
- ttl: row.ttl ?? void 0
300
- }));
301
- },
302
- async put(pk, sk, value, opts) {
303
- const model = requireModel();
304
- const ttl = opts?.ttlSeconds ? Math.floor(Date.now() / 1e3) + opts.ttlSeconds : void 0;
305
- const existing = await model.get({ pk, sk });
306
- if (existing.data) {
307
- const { errors } = await model.update({
308
- pk,
309
- sk,
310
- value: encodeValue(value),
311
- ttl: ttl ?? null
312
- });
313
- if (errors) throw new Error(errors[0]?.message ?? "KvStore.update failed");
314
- } else {
315
- const { errors } = await model.create({
316
- pk,
317
- sk,
318
- value: encodeValue(value),
319
- ttl
320
- });
321
- if (errors) throw new Error(errors[0]?.message ?? "KvStore.create failed");
322
- }
323
- },
324
- async remove(pk, sk) {
325
- const model = requireModel();
326
- const { errors } = await model.delete({ pk, sk });
327
- if (errors) throw new Error(errors[0]?.message ?? "KvStore.delete failed");
328
- }
329
- };
330
- setKvStore(store);
331
- }
332
-
333
- // src/lib/admin-config-client.ts
334
- var cmsConfig2 = null;
335
- function setAdminCmsConfigClient(config) {
336
- cmsConfig2 = config;
337
- }
338
- function getMediaProcessingDefaults() {
339
- return cmsConfig2?.media?.processing;
340
- }
341
-
342
- // src/components/admin-providers.tsx
343
- import { Fragment, jsx as jsx2 } from "react/jsx-runtime";
344
- function AdminProviders({ outputs, cmsConfig: cmsConfig3, children }) {
345
- configureAmplify(outputs);
346
- setAdminCmsConfig(cmsConfig3);
347
- setAdminCmsConfigClient(cmsConfig3);
348
- setAdminMediaContext(outputs, cmsConfig3);
349
- installAdminPostsProvider();
350
- installAdminKvProvider();
351
- return /* @__PURE__ */ jsx2(Fragment, { children });
352
- }
353
-
354
- // src/components/admin-dashboard.tsx
355
- import { useEffect, useState } from "react";
356
- import Link from "next/link";
357
- import { listPosts } from "ampless";
358
- import { Button, Card, CardContent, CardHeader, CardTitle } from "@ampless/runtime/ui";
359
- import { jsx as jsx3, jsxs } from "react/jsx-runtime";
360
- function AdminDashboard() {
361
- const t = useT();
362
- const [posts, setPosts] = useState([]);
363
- const [loading, setLoading] = useState(true);
364
- useEffect(() => {
365
- listPosts({ status: "all" }).then(setPosts).finally(() => setLoading(false));
366
- }, []);
367
- const published = posts.filter((p) => p.status === "published").length;
368
- const drafts = posts.filter((p) => p.status === "draft").length;
369
- return /* @__PURE__ */ jsxs("div", { className: "mx-auto max-w-7xl p-4 md:p-8", children: [
370
- /* @__PURE__ */ jsxs("div", { className: "mb-6 flex flex-wrap items-center justify-between gap-3 md:mb-8", children: [
371
- /* @__PURE__ */ jsx3("h1", { className: "text-2xl font-bold md:text-3xl", children: t("dashboard.title") }),
372
- /* @__PURE__ */ jsx3(Button, { asChild: true, children: /* @__PURE__ */ jsx3(Link, { href: "/admin/posts/new", children: t("dashboard.newPost") }) })
373
- ] }),
374
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3", children: [
375
- /* @__PURE__ */ jsxs(Card, { children: [
376
- /* @__PURE__ */ jsx3(CardHeader, { children: /* @__PURE__ */ jsx3(CardTitle, { children: t("dashboard.totalPosts") }) }),
377
- /* @__PURE__ */ jsxs(CardContent, { children: [
378
- /* @__PURE__ */ jsx3("p", { className: "text-3xl font-bold", children: loading ? "\u2014" : posts.length }),
379
- /* @__PURE__ */ jsx3("p", { className: "text-sm text-muted-foreground", children: t("dashboard.totalLabel") })
380
- ] })
381
- ] }),
382
- /* @__PURE__ */ jsxs(Card, { children: [
383
- /* @__PURE__ */ jsx3(CardHeader, { children: /* @__PURE__ */ jsx3(CardTitle, { children: t("dashboard.published") }) }),
384
- /* @__PURE__ */ jsx3(CardContent, { children: /* @__PURE__ */ jsx3("p", { className: "text-3xl font-bold", children: loading ? "\u2014" : published }) })
385
- ] }),
386
- /* @__PURE__ */ jsxs(Card, { children: [
387
- /* @__PURE__ */ jsx3(CardHeader, { children: /* @__PURE__ */ jsx3(CardTitle, { children: t("dashboard.drafts") }) }),
388
- /* @__PURE__ */ jsx3(CardContent, { children: /* @__PURE__ */ jsx3("p", { className: "text-3xl font-bold", children: loading ? "\u2014" : drafts }) })
389
- ] })
390
- ] })
391
- ] });
392
- }
393
-
394
- // src/components/posts-list-view.tsx
395
- import { useEffect as useEffect2, useState as useState2 } from "react";
396
- import Link2 from "next/link";
397
- import { listPosts as listPosts2 } from "ampless";
398
- import {
399
- Button as Button2,
400
- Table,
401
- TableBody,
402
- TableCell,
403
- TableHead,
404
- TableHeader,
405
- TableRow
406
- } from "@ampless/runtime/ui";
407
- import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
408
- function PostsList() {
409
- const t = useT();
410
- const [posts, setPosts] = useState2([]);
411
- const [loading, setLoading] = useState2(true);
412
- useEffect2(() => {
413
- const siteId = readAdminSiteIdFromCookie();
414
- listPosts2({ status: "all", siteId }).then(setPosts).finally(() => setLoading(false));
415
- }, []);
416
- return /* @__PURE__ */ jsxs2("div", { className: "mx-auto max-w-7xl p-4 md:p-8", children: [
417
- /* @__PURE__ */ jsxs2("div", { className: "mb-6 flex flex-wrap items-center justify-between gap-3 md:mb-8", children: [
418
- /* @__PURE__ */ jsx4("h1", { className: "text-2xl font-bold md:text-3xl", children: t("posts.list.title") }),
419
- /* @__PURE__ */ jsx4(Button2, { asChild: true, children: /* @__PURE__ */ jsx4(Link2, { href: "/admin/posts/new", children: t("posts.list.newButton") }) })
420
- ] }),
421
- loading ? /* @__PURE__ */ jsx4("p", { className: "text-muted-foreground", children: t("common.loading") }) : posts.length === 0 ? /* @__PURE__ */ jsxs2("div", { className: "rounded-md border p-12 text-center", children: [
422
- /* @__PURE__ */ jsx4("p", { className: "text-muted-foreground", children: t("posts.list.empty") }),
423
- /* @__PURE__ */ jsx4(Button2, { asChild: true, className: "mt-4", children: /* @__PURE__ */ jsx4(Link2, { href: "/admin/posts/new", children: t("posts.list.createFirst") }) })
424
- ] }) : /* @__PURE__ */ jsx4("div", { className: "overflow-x-auto rounded-md border", children: /* @__PURE__ */ jsxs2(Table, { children: [
425
- /* @__PURE__ */ jsx4(TableHeader, { children: /* @__PURE__ */ jsxs2(TableRow, { children: [
426
- /* @__PURE__ */ jsx4(TableHead, { children: t("posts.list.columnTitle") }),
427
- /* @__PURE__ */ jsx4(TableHead, { children: t("posts.list.columnStatus") }),
428
- /* @__PURE__ */ jsx4(TableHead, { children: t("posts.list.columnSlug") }),
429
- /* @__PURE__ */ jsx4(TableHead, { children: t("posts.list.columnUpdated") })
430
- ] }) }),
431
- /* @__PURE__ */ jsx4(TableBody, { children: posts.map((post) => /* @__PURE__ */ jsxs2(TableRow, { children: [
432
- /* @__PURE__ */ jsx4(TableCell, { children: /* @__PURE__ */ jsx4(
433
- Link2,
434
- {
435
- href: `/admin/posts/${post.postId}`,
436
- className: "font-medium hover:underline",
437
- children: post.title
438
- }
439
- ) }),
440
- /* @__PURE__ */ jsx4(TableCell, { children: /* @__PURE__ */ jsx4(
441
- "span",
442
- {
443
- className: post.status === "published" ? "inline-block rounded-full bg-green-100 px-2 py-0.5 text-xs text-green-700" : "inline-block rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-700",
444
- children: t(`common.${post.status}`)
445
- }
446
- ) }),
447
- /* @__PURE__ */ jsx4(TableCell, { className: "font-mono text-xs text-muted-foreground", children: post.slug }),
448
- /* @__PURE__ */ jsx4(TableCell, { className: "text-sm text-muted-foreground", children: post.publishedAt ? new Date(post.publishedAt).toLocaleDateString() : "\u2014" })
449
- ] }, post.postId)) })
450
- ] }) })
451
- ] });
452
- }
453
-
454
- // src/lib/upload.ts
455
- import { uploadData } from "aws-amplify/storage";
456
- import { processImage } from "ampless/media";
457
- function sanitizeName(name) {
458
- return name.replace(/[\x00-\x1f\x7f]/g, "").replace(/[\\/:*?"<>|]/g, "_").replace(/\s+/g, "_").replace(/^\.+/, "_").slice(0, 200) || "upload";
459
- }
460
- async function uploadProcessedImage(file, options) {
461
- const processed = await processImage(file, options);
462
- const safeName = sanitizeName(processed.suggestedName);
463
- const now = /* @__PURE__ */ new Date();
464
- const yyyy = now.getFullYear();
465
- const mm = String(now.getMonth() + 1).padStart(2, "0");
466
- const path = `public/media/${yyyy}/${mm}/${Date.now()}-${safeName}`;
467
- await uploadData({
468
- path,
469
- data: processed.blob,
470
- options: { contentType: processed.mime }
471
- }).result;
472
- return { path, url: publicMediaUrl(path) };
473
- }
474
-
475
- // src/components/image-upload-dialog.tsx
476
- import { useEffect as useEffect3, useRef, useState as useState3 } from "react";
477
- import ReactCrop, { centerCrop, makeAspectCrop } from "react-image-crop";
478
- import "react-image-crop/dist/ReactCrop.css";
479
- import { shouldSkipProcessing } from "ampless/media";
480
- import {
481
- Dialog,
482
- DialogContent,
483
- DialogDescription,
484
- DialogHeader,
485
- DialogTitle,
486
- Button as Button3,
487
- Input,
488
- Label
489
- } from "@ampless/runtime/ui";
490
- import { Fragment as Fragment2, jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
491
- var ASPECTS = {
492
- free: void 0,
493
- "1:1": 1,
494
- "4:3": 4 / 3,
495
- "16:9": 16 / 9,
496
- "3:2": 3 / 2
497
- };
498
- var ASPECT_CHOICES = ["free", "1:1", "4:3", "16:9", "3:2"];
499
- var FORMAT_CHOICES = ["auto", "webp", "jpeg"];
500
- var MAX_DIMENSION_PRESETS = [640, 1024, 1600, 2400, 4e3];
501
- var MIN_DIMENSION = 100;
502
- var MAX_DIMENSION_CEILING = 8e3;
503
- function clampMaxDimension(value, fallback) {
504
- if (!Number.isFinite(value) || value <= 0) return fallback;
505
- return Math.min(MAX_DIMENSION_CEILING, Math.max(MIN_DIMENSION, Math.round(value)));
506
- }
507
- function clampQuality(value) {
508
- if (!Number.isFinite(value)) return 0.85;
509
- return Math.min(1, Math.max(0, value));
510
- }
511
- function resolveFormat(choice, inputMime, losslessForPng) {
512
- if (choice === "auto") {
513
- return {
514
- format: "webp",
515
- lossless: losslessForPng && inputMime === "image/png"
516
- };
517
- }
518
- return { format: choice, lossless: false };
519
- }
520
- function buildInitialCrop(naturalWidth, naturalHeight, aspect) {
521
- if (aspect) {
522
- return centerCrop(
523
- makeAspectCrop({ unit: "%", width: 100 }, aspect, naturalWidth, naturalHeight),
524
- naturalWidth,
525
- naturalHeight
526
- );
527
- }
528
- return { unit: "%", x: 0, y: 0, width: 100, height: 100 };
529
- }
530
- function ImageUploadDialog({
531
- file,
532
- remaining,
533
- busy = false,
534
- defaults,
535
- onConfirm,
536
- onSkip,
537
- onCancel
538
- }) {
539
- const t = useT();
540
- const defaultMaxDimension = defaults?.maxDimension ?? 2400;
541
- const defaultQuality = defaults?.quality ?? 0.85;
542
- const losslessForPng = defaults?.losslessForPng ?? true;
543
- const [original, setOriginal] = useState3(false);
544
- const [aspect, setAspect] = useState3("free");
545
- const [crop, setCrop] = useState3(void 0);
546
- const [percentCrop, setPercentCrop] = useState3(null);
547
- const [naturalSize, setNaturalSize] = useState3(null);
548
- const [formatChoice, setFormatChoice] = useState3("auto");
549
- const [losslessOverride, setLosslessOverride] = useState3(null);
550
- const [quality, setQuality] = useState3(defaultQuality);
551
- const [maxDimension, setMaxDimension] = useState3(defaultMaxDimension);
552
- const [previewUrl, setPreviewUrl] = useState3(null);
553
- const imgRef = useRef(null);
554
- useEffect3(() => {
555
- setOriginal(false);
556
- setAspect("free");
557
- setCrop(void 0);
558
- setPercentCrop(null);
559
- setNaturalSize(null);
560
- setFormatChoice("auto");
561
- setLosslessOverride(null);
562
- setQuality(defaultQuality);
563
- setMaxDimension(defaultMaxDimension);
564
- }, [file, defaultQuality, defaultMaxDimension]);
565
- useEffect3(() => {
566
- if (!naturalSize) return;
567
- const next = buildInitialCrop(naturalSize.width, naturalSize.height, ASPECTS[aspect]);
568
- setCrop(next);
569
- setPercentCrop(next);
570
- }, [aspect, naturalSize]);
571
- useEffect3(() => {
572
- if (!file) {
573
- setPreviewUrl(null);
574
- return;
575
- }
576
- const url = URL.createObjectURL(file);
577
- setPreviewUrl(url);
578
- return () => URL.revokeObjectURL(url);
579
- }, [file]);
580
- if (!file) return null;
581
- const isImage = file.type.startsWith("image/");
582
- const passthrough = !isImage || shouldSkipProcessing(file.type);
583
- const showCropper = !passthrough && !original;
584
- const { format, lossless: autoLossless } = resolveFormat(formatChoice, file.type, losslessForPng);
585
- const lossless = losslessOverride ?? autoLossless;
586
- const showLosslessToggle = !original && !passthrough && format === "webp";
587
- const showQualitySlider = !original && !passthrough && (format === "jpeg" || format === "webp" && !lossless);
588
- function handleImageLoad(e) {
589
- const { naturalWidth, naturalHeight } = e.currentTarget;
590
- setNaturalSize({ width: naturalWidth, height: naturalHeight });
591
- const initial = buildInitialCrop(naturalWidth, naturalHeight, ASPECTS[aspect]);
592
- setCrop(initial);
593
- setPercentCrop(initial);
594
- }
595
- function handleConfirm() {
596
- if (!file || busy) return;
597
- if (original || passthrough) {
598
- onConfirm(file, { original: true });
599
- return;
600
- }
601
- let cropArea = void 0;
602
- if (percentCrop && naturalSize) {
603
- const x = Math.round(percentCrop.x / 100 * naturalSize.width);
604
- const y = Math.round(percentCrop.y / 100 * naturalSize.height);
605
- const width = Math.round(percentCrop.width / 100 * naturalSize.width);
606
- const height = Math.round(percentCrop.height / 100 * naturalSize.height);
607
- if (width > 0 && height > 0 && (x !== 0 || y !== 0 || width !== naturalSize.width || height !== naturalSize.height)) {
608
- cropArea = { x, y, width, height };
609
- }
610
- }
611
- onConfirm(file, {
612
- crop: cropArea,
613
- maxDimension: clampMaxDimension(maxDimension, defaultMaxDimension),
614
- format,
615
- quality: clampQuality(quality),
616
- lossless: format === "webp" ? lossless : false
617
- });
618
- }
619
- return /* @__PURE__ */ jsx5(
620
- Dialog,
621
- {
622
- open: true,
623
- onOpenChange: (open) => {
624
- if (open) return;
625
- onCancel();
626
- },
627
- children: /* @__PURE__ */ jsxs3(DialogContent, { className: "max-h-[90vh] max-w-4xl overflow-y-auto", children: [
628
- /* @__PURE__ */ jsxs3(DialogHeader, { children: [
629
- /* @__PURE__ */ jsx5(DialogTitle, { className: "truncate", children: file.name }),
630
- /* @__PURE__ */ jsxs3(DialogDescription, { children: [
631
- remaining > 1 ? t("media.dialog.remaining", { count: remaining }) : `${formatBytes(file.size)} \xB7 ${file.type || "unknown"}`,
632
- busy && t("media.dialog.uploading")
633
- ] })
634
- ] }),
635
- previewUrl && showCropper && /* @__PURE__ */ jsx5("div", { className: "flex items-center justify-center rounded-md bg-black/90 p-2", children: /* @__PURE__ */ jsx5(
636
- ReactCrop,
637
- {
638
- crop,
639
- aspect: ASPECTS[aspect],
640
- minWidth: 20,
641
- minHeight: 20,
642
- onChange: (_pixel, percent) => {
643
- setCrop(percent);
644
- setPercentCrop(percent);
645
- },
646
- children: /* @__PURE__ */ jsx5(
647
- "img",
648
- {
649
- ref: imgRef,
650
- src: previewUrl,
651
- alt: "preview",
652
- className: "block max-h-[60vh] max-w-full",
653
- onLoad: handleImageLoad
654
- }
655
- )
656
- }
657
- ) }),
658
- previewUrl && !showCropper && isImage && /* @__PURE__ */ jsx5("div", { className: "flex h-48 items-center justify-center rounded-md bg-muted", children: /* @__PURE__ */ jsx5("img", { src: previewUrl, alt: "preview", className: "max-h-full max-w-full object-contain" }) }),
659
- !isImage && // Non-image upload: skip the broken-img preview. Show the
660
- // file's name / size / mime so the admin can confirm before
661
- // committing the bytes to S3.
662
- /* @__PURE__ */ jsxs3("div", { className: "flex h-32 flex-col items-center justify-center gap-1 rounded-md bg-muted text-sm text-muted-foreground", children: [
663
- /* @__PURE__ */ jsx5("span", { className: "font-medium", children: file.name }),
664
- /* @__PURE__ */ jsxs3("span", { className: "font-mono text-xs", children: [
665
- formatBytes(file.size),
666
- " \xB7 ",
667
- file.type || "unknown"
668
- ] })
669
- ] }),
670
- /* @__PURE__ */ jsxs3("div", { className: "space-y-4", children: [
671
- /* @__PURE__ */ jsxs3("label", { className: "flex items-center gap-2 text-sm", children: [
672
- /* @__PURE__ */ jsx5(
673
- "input",
674
- {
675
- type: "checkbox",
676
- checked: original,
677
- disabled: busy,
678
- onChange: (e) => setOriginal(e.target.checked)
679
- }
680
- ),
681
- /* @__PURE__ */ jsx5("span", { children: t("media.dialog.useOriginal") }),
682
- passthrough && /* @__PURE__ */ jsx5("span", { className: "text-xs text-muted-foreground", children: t("media.dialog.passthroughNote") })
683
- ] }),
684
- !original && !passthrough && /* @__PURE__ */ jsxs3(Fragment2, { children: [
685
- /* @__PURE__ */ jsxs3("div", { children: [
686
- /* @__PURE__ */ jsx5(Label, { children: t("media.dialog.aspectRatio") }),
687
- /* @__PURE__ */ jsx5("div", { className: "mt-2 flex flex-wrap gap-2", children: ASPECT_CHOICES.map((choice) => /* @__PURE__ */ jsx5(
688
- Button3,
689
- {
690
- type: "button",
691
- variant: aspect === choice ? "default" : "outline",
692
- size: "sm",
693
- disabled: busy,
694
- onClick: () => setAspect(choice),
695
- children: choice
696
- },
697
- choice
698
- )) })
699
- ] }),
700
- /* @__PURE__ */ jsxs3("div", { children: [
701
- /* @__PURE__ */ jsx5(Label, { children: t("media.dialog.outputFormat") }),
702
- /* @__PURE__ */ jsx5("div", { className: "mt-2 flex flex-wrap gap-2", children: FORMAT_CHOICES.map((choice) => /* @__PURE__ */ jsx5(
703
- Button3,
704
- {
705
- type: "button",
706
- variant: formatChoice === choice ? "default" : "outline",
707
- size: "sm",
708
- disabled: busy,
709
- onClick: () => {
710
- setFormatChoice(choice);
711
- setLosslessOverride(null);
712
- },
713
- children: choice
714
- },
715
- choice
716
- )) })
717
- ] }),
718
- showLosslessToggle && /* @__PURE__ */ jsxs3("label", { className: "flex items-center gap-2 text-sm", children: [
719
- /* @__PURE__ */ jsx5(
720
- "input",
721
- {
722
- type: "checkbox",
723
- checked: lossless,
724
- disabled: busy,
725
- onChange: (e) => setLosslessOverride(e.target.checked)
726
- }
727
- ),
728
- /* @__PURE__ */ jsx5("span", { children: t("media.dialog.losslessWebp") })
729
- ] }),
730
- showQualitySlider && /* @__PURE__ */ jsxs3("div", { children: [
731
- /* @__PURE__ */ jsx5(Label, { children: t("media.dialog.quality", { value: Math.round(quality * 100) }) }),
732
- /* @__PURE__ */ jsx5(
733
- "input",
734
- {
735
- type: "range",
736
- min: 50,
737
- max: 100,
738
- step: 1,
739
- disabled: busy,
740
- value: Math.round(quality * 100),
741
- onChange: (e) => setQuality(Number(e.target.value) / 100),
742
- className: "mt-2 w-full"
743
- }
744
- )
745
- ] }),
746
- /* @__PURE__ */ jsxs3("div", { className: "max-w-xs", children: [
747
- /* @__PURE__ */ jsx5(Label, { htmlFor: "maxDimension", children: t("media.dialog.maxDimension") }),
748
- /* @__PURE__ */ jsx5("div", { className: "mt-2 flex flex-wrap gap-2", children: MAX_DIMENSION_PRESETS.map((preset) => /* @__PURE__ */ jsx5(
749
- Button3,
750
- {
751
- type: "button",
752
- variant: maxDimension === preset ? "default" : "outline",
753
- size: "sm",
754
- disabled: busy,
755
- onClick: () => setMaxDimension(preset),
756
- children: preset
757
- },
758
- preset
759
- )) }),
760
- /* @__PURE__ */ jsx5(
761
- Input,
762
- {
763
- id: "maxDimension",
764
- type: "number",
765
- className: "mt-2",
766
- min: MIN_DIMENSION,
767
- max: MAX_DIMENSION_CEILING,
768
- disabled: busy,
769
- value: maxDimension,
770
- onChange: (e) => setMaxDimension(Number(e.target.value) || defaultMaxDimension)
771
- }
772
- )
773
- ] })
774
- ] })
775
- ] }),
776
- /* @__PURE__ */ jsxs3("div", { className: "flex justify-end gap-2", children: [
777
- /* @__PURE__ */ jsx5(Button3, { variant: "ghost", type: "button", onClick: onCancel, children: t("media.dialog.cancelAll") }),
778
- /* @__PURE__ */ jsx5(Button3, { variant: "outline", type: "button", disabled: busy, onClick: onSkip, children: t("media.dialog.skip") }),
779
- /* @__PURE__ */ jsx5(Button3, { type: "button", disabled: busy, onClick: handleConfirm, children: busy ? t("media.dialog.uploadingButton") : t("media.dialog.upload") })
780
- ] })
781
- ] })
782
- }
783
- );
784
- }
785
- function formatBytes(bytes) {
786
- if (bytes < 1024) return `${bytes} B`;
787
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
788
- return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
789
- }
790
-
791
- // src/components/media-picker.tsx
792
- import { useEffect as useEffect4, useRef as useRef2, useState as useState4 } from "react";
793
- import { list } from "aws-amplify/storage";
794
- import { Upload } from "lucide-react";
795
- import {
796
- Dialog as Dialog2,
797
- DialogContent as DialogContent2,
798
- DialogDescription as DialogDescription2,
799
- DialogHeader as DialogHeader2,
800
- DialogTitle as DialogTitle2,
801
- DialogTrigger,
802
- Button as Button4
803
- } from "@ampless/runtime/ui";
804
- import { Fragment as Fragment3, jsx as jsx6, jsxs as jsxs4 } from "react/jsx-runtime";
805
- function MediaPicker({ trigger, onSelect }) {
806
- const t = useT();
807
- const [open, setOpen] = useState4(false);
808
- const [items, setItems] = useState4([]);
809
- const [loading, setLoading] = useState4(false);
810
- const [error, setError] = useState4(null);
811
- const [pendingUpload, setPendingUpload] = useState4(null);
812
- const [uploading, setUploading] = useState4(false);
813
- const fileInputRef = useRef2(null);
814
- useEffect4(() => {
815
- if (!open) return;
816
- let cancelled = false;
817
- setLoading(true);
818
- setError(null);
819
- list({ path: "public/media/" }).then((result) => {
820
- if (cancelled) return;
821
- setItems(result.items.map((i) => i.path));
822
- }).catch((err) => {
823
- if (!cancelled) setError(err instanceof Error ? err.message : String(err));
824
- }).finally(() => {
825
- if (!cancelled) setLoading(false);
826
- });
827
- return () => {
828
- cancelled = true;
829
- };
830
- }, [open]);
831
- function handlePick(path) {
832
- onSelect(publicMediaUrl(path));
833
- setOpen(false);
834
- }
835
- function handleFileSelected(e) {
836
- const file = e.target.files?.[0];
837
- e.target.value = "";
838
- if (!file) return;
839
- setPendingUpload(file);
840
- }
841
- async function handleUploadConfirm(file, options) {
842
- setUploading(true);
843
- setError(null);
844
- try {
845
- const { url } = await uploadProcessedImage(file, options);
846
- onSelect(url);
847
- setPendingUpload(null);
848
- setOpen(false);
849
- } catch (err) {
850
- setError(err instanceof Error ? err.message : String(err));
851
- } finally {
852
- setUploading(false);
853
- }
854
- }
855
- const pickerOpen = open && !pendingUpload;
856
- return /* @__PURE__ */ jsxs4(Fragment3, { children: [
857
- /* @__PURE__ */ jsxs4(Dialog2, { open: pickerOpen, onOpenChange: (next) => setOpen(next), children: [
858
- /* @__PURE__ */ jsx6(DialogTrigger, { asChild: true, onClick: () => setOpen(true), children: trigger }),
859
- /* @__PURE__ */ jsxs4(DialogContent2, { children: [
860
- /* @__PURE__ */ jsx6(DialogHeader2, { children: /* @__PURE__ */ jsxs4("div", { className: "flex items-center justify-between gap-4", children: [
861
- /* @__PURE__ */ jsxs4("div", { children: [
862
- /* @__PURE__ */ jsx6(DialogTitle2, { children: t("mediaPicker.title") }),
863
- /* @__PURE__ */ jsx6(DialogDescription2, { children: t("mediaPicker.description") })
864
- ] }),
865
- /* @__PURE__ */ jsxs4(
866
- Button4,
867
- {
868
- type: "button",
869
- variant: "outline",
870
- size: "sm",
871
- onClick: () => fileInputRef.current?.click(),
872
- children: [
873
- /* @__PURE__ */ jsx6(Upload, { className: "mr-2 h-3 w-3" }),
874
- t("mediaPicker.uploadNew")
875
- ]
876
- }
877
- )
878
- ] }) }),
879
- /* @__PURE__ */ jsx6(
880
- "input",
881
- {
882
- ref: fileInputRef,
883
- type: "file",
884
- accept: "image/*",
885
- className: "hidden",
886
- onChange: handleFileSelected
887
- }
888
- ),
889
- loading && /* @__PURE__ */ jsx6("p", { className: "text-sm text-muted-foreground", children: t("common.loading") }),
890
- error && /* @__PURE__ */ jsx6("p", { className: "text-sm text-destructive", children: error }),
891
- !loading && items.length === 0 && /* @__PURE__ */ jsxs4("p", { className: "text-sm text-muted-foreground", children: [
892
- t("mediaPicker.empty"),
893
- " ",
894
- t("mediaPicker.emptyHint", { action: t("mediaPicker.emptyAction") })
895
- ] }),
896
- /* @__PURE__ */ jsx6("div", { className: "grid max-h-[60vh] grid-cols-3 gap-3 overflow-auto sm:grid-cols-4", children: items.map((path) => /* @__PURE__ */ jsxs4(
897
- "button",
898
- {
899
- type: "button",
900
- onClick: () => handlePick(path),
901
- className: "group overflow-hidden rounded-md border transition hover:border-primary",
902
- children: [
903
- /* @__PURE__ */ jsx6(
904
- "img",
905
- {
906
- src: publicMediaUrl(path),
907
- alt: path,
908
- className: "aspect-square w-full object-cover"
909
- }
910
- ),
911
- /* @__PURE__ */ jsx6("div", { className: "truncate p-1 text-xs text-muted-foreground", children: path.split("/").pop() })
912
- ]
913
- },
914
- path
915
- )) })
916
- ] })
917
- ] }),
918
- /* @__PURE__ */ jsx6(
919
- ImageUploadDialog,
920
- {
921
- file: pendingUpload,
922
- remaining: pendingUpload ? 1 : 0,
923
- busy: uploading,
924
- defaults: getMediaProcessingDefaults(),
925
- onConfirm: handleUploadConfirm,
926
- onSkip: () => setPendingUpload(null),
927
- onCancel: () => setPendingUpload(null)
928
- }
929
- )
930
- ] });
931
- }
932
-
933
- // src/components/post-form.tsx
934
- import { useRef as useRef3, useState as useState5 } from "react";
935
- import { useRouter } from "next/navigation";
936
- import { Image as ImageIcon3 } from "lucide-react";
937
- import {
938
- createPost,
939
- updatePost,
940
- deletePost,
941
- formatDate
942
- } from "ampless";
943
- import {
944
- renderBody,
945
- tiptapToHtml,
946
- tiptapToMarkdown,
947
- markdownToHtml,
948
- htmlToMarkdown
949
- } from "@ampless/runtime";
950
- import { Button as Button7, Input as Input2, Label as Label2, Textarea } from "@ampless/runtime/ui";
951
-
952
- // src/editor/tiptap-editor.tsx
953
- import { useEditor, EditorContent } from "@tiptap/react";
954
- import StarterKit from "@tiptap/starter-kit";
955
- import Link3 from "@tiptap/extension-link";
956
- import Image from "@tiptap/extension-image";
957
-
958
- // src/editor/toolbar.tsx
959
- import {
960
- Bold,
961
- Italic,
962
- Heading1,
963
- Heading2,
964
- List,
965
- ListOrdered,
966
- Code,
967
- Link as LinkIcon,
968
- Image as ImageIcon
969
- } from "lucide-react";
970
- import { Button as Button5, cn } from "@ampless/runtime/ui";
971
- import { jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
972
- function Toolbar({ editor }) {
973
- const t = useT();
974
- if (!editor) return null;
975
- const tools = [
976
- { name: "bold", icon: Bold, action: () => editor.chain().focus().toggleBold().run(), isActive: () => editor.isActive("bold") },
977
- { name: "italic", icon: Italic, action: () => editor.chain().focus().toggleItalic().run(), isActive: () => editor.isActive("italic") },
978
- { name: "h1", icon: Heading1, action: () => editor.chain().focus().toggleHeading({ level: 1 }).run(), isActive: () => editor.isActive("heading", { level: 1 }) },
979
- { name: "h2", icon: Heading2, action: () => editor.chain().focus().toggleHeading({ level: 2 }).run(), isActive: () => editor.isActive("heading", { level: 2 }) },
980
- { name: "bulletList", icon: List, action: () => editor.chain().focus().toggleBulletList().run(), isActive: () => editor.isActive("bulletList") },
981
- { name: "orderedList", icon: ListOrdered, action: () => editor.chain().focus().toggleOrderedList().run(), isActive: () => editor.isActive("orderedList") },
982
- { name: "code", icon: Code, action: () => editor.chain().focus().toggleCodeBlock().run(), isActive: () => editor.isActive("codeBlock") }
983
- ];
984
- const setLink = () => {
985
- const previousUrl = editor.getAttributes("link").href ?? "";
986
- const url = window.prompt(t("editor.linkPrompt"), previousUrl);
987
- if (url === null) return;
988
- if (url === "") {
989
- editor.chain().focus().extendMarkRange("link").unsetLink().run();
990
- return;
991
- }
992
- editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run();
993
- };
994
- const insertImage = (url) => {
995
- editor.chain().focus().setImage({ src: url }).run();
996
- };
997
- return /* @__PURE__ */ jsxs5("div", { className: "flex flex-wrap gap-1 border-b p-2", children: [
998
- tools.map((tool) => {
999
- const Icon = tool.icon;
1000
- return /* @__PURE__ */ jsx7(
1001
- Button5,
1002
- {
1003
- type: "button",
1004
- variant: "ghost",
1005
- size: "icon",
1006
- onClick: tool.action,
1007
- className: cn(tool.isActive() && "bg-accent text-accent-foreground"),
1008
- children: /* @__PURE__ */ jsx7(Icon, { className: "h-4 w-4" })
1009
- },
1010
- tool.name
1011
- );
1012
- }),
1013
- /* @__PURE__ */ jsx7(
1014
- Button5,
1015
- {
1016
- type: "button",
1017
- variant: "ghost",
1018
- size: "icon",
1019
- onClick: setLink,
1020
- className: cn(editor.isActive("link") && "bg-accent text-accent-foreground"),
1021
- children: /* @__PURE__ */ jsx7(LinkIcon, { className: "h-4 w-4" })
1022
- }
1023
- ),
1024
- /* @__PURE__ */ jsx7(
1025
- MediaPicker,
1026
- {
1027
- onSelect: insertImage,
1028
- trigger: /* @__PURE__ */ jsx7(Button5, { type: "button", variant: "ghost", size: "icon", children: /* @__PURE__ */ jsx7(ImageIcon, { className: "h-4 w-4" }) })
1029
- }
1030
- )
1031
- ] });
1032
- }
1033
-
1034
- // src/editor/image-bubble-menu.tsx
1035
- import { BubbleMenu } from "@tiptap/react/menus";
1036
- import { Trash2, Pencil, ImageIcon as ImageIcon2, Maximize2 } from "lucide-react";
1037
- import { Button as Button6, cn as cn2 } from "@ampless/runtime/ui";
1038
- import { jsx as jsx8, jsxs as jsxs6 } from "react/jsx-runtime";
1039
- function ImageBubbleMenu({ editor }) {
1040
- const t = useT();
1041
- const editAlt = () => {
1042
- const current = editor.getAttributes("image").alt ?? "";
1043
- const alt = window.prompt(t("editor.altPrompt"), current);
1044
- if (alt === null) return;
1045
- editor.chain().focus().updateAttributes("image", { alt }).run();
1046
- };
1047
- const remove2 = () => {
1048
- editor.chain().focus().deleteSelection().run();
1049
- };
1050
- const setDisplay = (display) => {
1051
- const current = editor.getAttributes("image").display ?? null;
1052
- const next = current === display ? null : display;
1053
- editor.chain().focus().updateAttributes("image", { display: next }).run();
1054
- };
1055
- const currentDisplay = editor.getAttributes("image").display ?? null;
1056
- return /* @__PURE__ */ jsx8(
1057
- BubbleMenu,
1058
- {
1059
- editor,
1060
- shouldShow: ({ editor: editor2 }) => editor2.isActive("image"),
1061
- options: { placement: "top" },
1062
- children: /* @__PURE__ */ jsxs6("div", { className: "flex items-center gap-1 rounded-md border bg-popover p-1 shadow", children: [
1063
- /* @__PURE__ */ jsxs6(
1064
- Button6,
1065
- {
1066
- type: "button",
1067
- variant: "ghost",
1068
- size: "sm",
1069
- onClick: () => setDisplay("inline"),
1070
- className: cn2(currentDisplay === "inline" && "bg-accent text-accent-foreground"),
1071
- title: t("editor.image.inlineTitle"),
1072
- children: [
1073
- /* @__PURE__ */ jsx8(ImageIcon2, { className: "mr-1 h-3 w-3" }),
1074
- t("editor.image.inline")
1075
- ]
1076
- }
1077
- ),
1078
- /* @__PURE__ */ jsxs6(
1079
- Button6,
1080
- {
1081
- type: "button",
1082
- variant: "ghost",
1083
- size: "sm",
1084
- onClick: () => setDisplay("lightbox"),
1085
- className: cn2(currentDisplay === "lightbox" && "bg-accent text-accent-foreground"),
1086
- title: t("editor.image.lightboxTitle"),
1087
- children: [
1088
- /* @__PURE__ */ jsx8(Maximize2, { className: "mr-1 h-3 w-3" }),
1089
- t("editor.image.lightbox")
1090
- ]
1091
- }
1092
- ),
1093
- /* @__PURE__ */ jsx8("span", { className: "mx-1 h-4 w-px bg-border" }),
1094
- /* @__PURE__ */ jsxs6(Button6, { type: "button", variant: "ghost", size: "sm", onClick: editAlt, children: [
1095
- /* @__PURE__ */ jsx8(Pencil, { className: "mr-1 h-3 w-3" }),
1096
- t("editor.image.alt")
1097
- ] }),
1098
- /* @__PURE__ */ jsxs6(Button6, { type: "button", variant: "ghost", size: "sm", onClick: remove2, children: [
1099
- /* @__PURE__ */ jsx8(Trash2, { className: "mr-1 h-3 w-3" }),
1100
- t("editor.image.delete")
1101
- ] })
1102
- ] })
1103
- }
1104
- );
1105
- }
1106
-
1107
- // src/editor/tiptap-editor.tsx
1108
- import { jsx as jsx9, jsxs as jsxs7 } from "react/jsx-runtime";
1109
- var AmplessImage = Image.extend({
1110
- addAttributes() {
1111
- return {
1112
- ...this.parent?.(),
1113
- display: {
1114
- default: null,
1115
- parseHTML: (el) => el.getAttribute("data-display"),
1116
- renderHTML: (attrs) => {
1117
- const v = attrs.display;
1118
- return v ? { "data-display": v } : {};
1119
- }
1120
- }
1121
- };
1122
- }
1123
- });
1124
- function TiptapEditor({ initialContent, onChange }) {
1125
- const editor = useEditor({
1126
- extensions: [
1127
- StarterKit,
1128
- Link3.configure({ openOnClick: false }),
1129
- AmplessImage.configure({ inline: false, allowBase64: false })
1130
- ],
1131
- content: initialContent ?? { type: "doc", content: [{ type: "paragraph" }] },
1132
- immediatelyRender: false,
1133
- editorProps: {
1134
- attributes: {
1135
- class: "prose prose-neutral dark:prose-invert max-w-none min-h-[400px] px-4 py-3 focus:outline-none"
1136
- }
1137
- },
1138
- onCreate: ({ editor: editor2 }) => {
1139
- onChange?.(editor2.getJSON());
1140
- },
1141
- onUpdate: ({ editor: editor2 }) => {
1142
- onChange?.(editor2.getJSON());
1143
- }
1144
- });
1145
- return /* @__PURE__ */ jsxs7("div", { className: "rounded-md border", children: [
1146
- /* @__PURE__ */ jsx9(Toolbar, { editor }),
1147
- editor && /* @__PURE__ */ jsx9(ImageBubbleMenu, { editor }),
1148
- /* @__PURE__ */ jsx9(EditorContent, { editor })
1149
- ] });
1150
- }
1151
-
1152
- // src/components/post-form.tsx
1153
- import { jsx as jsx10, jsxs as jsxs8 } from "react/jsx-runtime";
1154
- var EMPTY_TIPTAP_DOC = { type: "doc", content: [{ type: "paragraph" }] };
1155
- var IMAGE_URL_RE = /\.(jpe?g|png|gif|webp|avif|svg|bmp|tiff?)(\?|$)/i;
1156
- var STYLESHEET_URL_RE = /\.css(\?|$)/i;
1157
- var SCRIPT_URL_RE = /\.m?js(\?|$)/i;
1158
- function snippetFor(url, format) {
1159
- const isImage = IMAGE_URL_RE.test(url);
1160
- if (format === "markdown") {
1161
- return isImage ? `![](${url})` : url;
1162
- }
1163
- if (isImage) return `<img src="${url}" alt="" />`;
1164
- if (STYLESHEET_URL_RE.test(url)) return `<link rel="stylesheet" href="${url}" />`;
1165
- if (SCRIPT_URL_RE.test(url)) return `<script src="${url}"></script>`;
1166
- return url;
1167
- }
1168
- function slugify(s) {
1169
- return s.toLowerCase().trim().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-");
1170
- }
1171
- function defaultBodyForFormat(format) {
1172
- if (format === "tiptap") return EMPTY_TIPTAP_DOC;
1173
- return "";
1174
- }
1175
- function PostForm({ post }) {
1176
- const router = useRouter();
1177
- const t = useT();
1178
- const isEdit = !!post;
1179
- const bodyTextareaRef = useRef3(null);
1180
- const [title, setTitle] = useState5(post?.title ?? "");
1181
- const [slug, setSlug] = useState5(post?.slug ?? "");
1182
- const [excerpt, setExcerpt] = useState5(post?.excerpt ?? "");
1183
- const [format, setFormat] = useState5(post?.format ?? "tiptap");
1184
- const [body, setBody] = useState5(post?.body ?? EMPTY_TIPTAP_DOC);
1185
- const [status, setStatus] = useState5(post?.status ?? "draft");
1186
- const [tagsInput, setTagsInput] = useState5((post?.tags ?? []).join(", "));
1187
- const [noLayout, setNoLayout] = useState5(post?.metadata?.no_layout === true);
1188
- const [saving, setSaving] = useState5(false);
1189
- const [error, setError] = useState5(null);
1190
- const [view, setView] = useState5("edit");
1191
- function buildMetadata() {
1192
- const next = { ...post?.metadata ?? {} };
1193
- if (noLayout && format === "html") next.no_layout = true;
1194
- else delete next.no_layout;
1195
- return Object.keys(next).length > 0 ? next : void 0;
1196
- }
1197
- function parseTags(raw) {
1198
- return Array.from(
1199
- new Set(
1200
- raw.split(",").map((t2) => t2.trim()).filter(Boolean)
1201
- )
1202
- );
1203
- }
1204
- function insertMediaSnippet(url) {
1205
- if (format === "tiptap") return;
1206
- const snippet = snippetFor(url, format);
1207
- const ta = bodyTextareaRef.current;
1208
- const current = typeof body === "string" ? body : "";
1209
- if (!ta) {
1210
- setBody(current + snippet);
1211
- return;
1212
- }
1213
- const start = ta.selectionStart ?? current.length;
1214
- const end = ta.selectionEnd ?? current.length;
1215
- const next = current.slice(0, start) + snippet + current.slice(end);
1216
- setBody(next);
1217
- requestAnimationFrame(() => {
1218
- const t2 = bodyTextareaRef.current;
1219
- if (!t2) return;
1220
- t2.focus();
1221
- const pos = start + snippet.length;
1222
- t2.setSelectionRange(pos, pos);
1223
- });
1224
- }
1225
- function changeFormat(next) {
1226
- if (next === format) return;
1227
- let nextBody = body;
1228
- const k = `${format}\u2192${next}`;
1229
- switch (k) {
1230
- case "tiptap\u2192html":
1231
- nextBody = tiptapToHtml(body);
1232
- break;
1233
- case "tiptap\u2192markdown":
1234
- nextBody = tiptapToMarkdown(body);
1235
- break;
1236
- case "html\u2192tiptap":
1237
- nextBody = String(body ?? "");
1238
- break;
1239
- case "markdown\u2192tiptap":
1240
- nextBody = markdownToHtml(String(body ?? ""));
1241
- break;
1242
- case "html\u2192markdown":
1243
- nextBody = htmlToMarkdown(String(body ?? ""));
1244
- break;
1245
- case "markdown\u2192html":
1246
- nextBody = markdownToHtml(String(body ?? ""));
1247
- break;
1248
- default:
1249
- nextBody = defaultBodyForFormat(next);
1250
- }
1251
- setFormat(next);
1252
- setBody(nextBody);
1253
- if (next !== "html") setNoLayout(false);
1254
- }
1255
- async function save(e) {
1256
- e.preventDefault();
1257
- setSaving(true);
1258
- setError(null);
1259
- try {
1260
- const tags = parseTags(tagsInput);
1261
- const metadata = buildMetadata();
1262
- if (isEdit) {
1263
- await updatePost(
1264
- post.postId,
1265
- {
1266
- title,
1267
- slug: slug || slugify(title),
1268
- excerpt: excerpt || void 0,
1269
- format,
1270
- body,
1271
- status,
1272
- publishedAt: status === "published" ? post?.publishedAt ?? (/* @__PURE__ */ new Date()).toISOString() : void 0,
1273
- tags,
1274
- metadata
1275
- },
1276
- { siteId: post.siteId }
1277
- );
1278
- } else {
1279
- await createPost({
1280
- siteId: readAdminSiteIdFromCookie(),
1281
- slug: slug || slugify(title),
1282
- title,
1283
- excerpt: excerpt || void 0,
1284
- format,
1285
- body,
1286
- status,
1287
- publishedAt: status === "published" ? (/* @__PURE__ */ new Date()).toISOString() : void 0,
1288
- tags,
1289
- metadata
1290
- });
1291
- }
1292
- router.push("/admin/posts");
1293
- router.refresh();
1294
- } catch (err) {
1295
- setError(err instanceof Error ? err.message : String(err));
1296
- } finally {
1297
- setSaving(false);
1298
- }
1299
- }
1300
- async function handleDelete() {
1301
- if (!post) return;
1302
- if (!confirm(t("posts.form.deleteConfirm", { title: post.title }))) return;
1303
- setSaving(true);
1304
- try {
1305
- await deletePost(post.postId);
1306
- router.push("/admin/posts");
1307
- router.refresh();
1308
- } catch (err) {
1309
- setError(err instanceof Error ? err.message : String(err));
1310
- setSaving(false);
1311
- }
1312
- }
1313
- const previewPost = {
1314
- postId: post?.postId ?? "preview",
1315
- siteId: post?.siteId ?? readAdminSiteIdFromCookie(),
1316
- slug: slug || slugify(title) || "preview",
1317
- title,
1318
- excerpt: excerpt || void 0,
1319
- format,
1320
- body,
1321
- status,
1322
- publishedAt: status === "published" ? post?.publishedAt ?? (/* @__PURE__ */ new Date()).toISOString() : void 0,
1323
- tags: parseTags(tagsInput)
1324
- };
1325
- return /* @__PURE__ */ jsxs8("form", { onSubmit: save, className: "space-y-6", children: [
1326
- /* @__PURE__ */ jsxs8("div", { className: "flex gap-1 border-b", children: [
1327
- /* @__PURE__ */ jsx10(
1328
- "button",
1329
- {
1330
- type: "button",
1331
- onClick: () => setView("edit"),
1332
- "aria-pressed": view === "edit",
1333
- className: `px-4 py-2 text-sm font-medium transition ${view === "edit" ? "border-b-2 border-[var(--primary)] text-[var(--primary)]" : "text-muted-foreground hover:text-foreground"}`,
1334
- children: t("posts.form.tabEdit")
1335
- }
1336
- ),
1337
- /* @__PURE__ */ jsx10(
1338
- "button",
1339
- {
1340
- type: "button",
1341
- onClick: () => setView("preview"),
1342
- "aria-pressed": view === "preview",
1343
- className: `px-4 py-2 text-sm font-medium transition ${view === "preview" ? "border-b-2 border-[var(--primary)] text-[var(--primary)]" : "text-muted-foreground hover:text-foreground"}`,
1344
- children: t("posts.form.tabPreview")
1345
- }
1346
- )
1347
- ] }),
1348
- view === "preview" && /* @__PURE__ */ jsxs8("article", { className: "space-y-4", children: [
1349
- /* @__PURE__ */ jsxs8("header", { className: "border-b pb-4", children: [
1350
- /* @__PURE__ */ jsx10("h1", { className: "text-3xl font-bold tracking-tight", children: title || /* @__PURE__ */ jsx10("span", { className: "text-muted-foreground italic", children: t("posts.form.previewNoTitle") }) }),
1351
- /* @__PURE__ */ jsxs8("p", { className: "mt-2 text-sm text-muted-foreground", children: [
1352
- previewPost.publishedAt ? /* @__PURE__ */ jsx10("time", { dateTime: previewPost.publishedAt, children: formatDate(previewPost.publishedAt) }) : /* @__PURE__ */ jsx10("span", { children: t("common.draft") }),
1353
- /* @__PURE__ */ jsx10("span", { className: "mx-2", children: "\xB7" }),
1354
- /* @__PURE__ */ jsx10("span", { className: "font-mono text-xs uppercase", children: format })
1355
- ] }),
1356
- excerpt && /* @__PURE__ */ jsx10("p", { className: "mt-3 text-base text-muted-foreground", children: excerpt })
1357
- ] }),
1358
- /* @__PURE__ */ jsx10(
1359
- "div",
1360
- {
1361
- className: "prose prose-neutral dark:prose-invert max-w-none",
1362
- dangerouslySetInnerHTML: { __html: renderBody(previewPost) }
1363
- }
1364
- ),
1365
- previewPost.tags && previewPost.tags.length > 0 && /* @__PURE__ */ jsx10("div", { className: "flex flex-wrap gap-2 border-t pt-4 text-sm", children: previewPost.tags.map((tag) => /* @__PURE__ */ jsxs8(
1366
- "span",
1367
- {
1368
- className: "rounded-full border px-2 py-0.5 text-xs text-muted-foreground",
1369
- children: [
1370
- "#",
1371
- tag
1372
- ]
1373
- },
1374
- tag
1375
- )) }),
1376
- /* @__PURE__ */ jsx10("p", { className: "text-xs text-muted-foreground", children: t("posts.form.previewHint") })
1377
- ] }),
1378
- /* @__PURE__ */ jsxs8("div", { className: view === "edit" ? "space-y-6" : "hidden", children: [
1379
- /* @__PURE__ */ jsxs8("div", { className: "space-y-2", children: [
1380
- /* @__PURE__ */ jsx10(Label2, { htmlFor: "title", children: t("posts.form.title") }),
1381
- /* @__PURE__ */ jsx10(
1382
- Input2,
1383
- {
1384
- id: "title",
1385
- required: true,
1386
- value: title,
1387
- onChange: (e) => {
1388
- setTitle(e.target.value);
1389
- if (!isEdit && !slug) setSlug(slugify(e.target.value));
1390
- }
1391
- }
1392
- )
1393
- ] }),
1394
- /* @__PURE__ */ jsxs8("div", { className: "space-y-2", children: [
1395
- /* @__PURE__ */ jsx10(Label2, { htmlFor: "slug", children: t("posts.form.slug") }),
1396
- /* @__PURE__ */ jsx10(
1397
- Input2,
1398
- {
1399
- id: "slug",
1400
- value: slug,
1401
- onChange: (e) => setSlug(e.target.value),
1402
- placeholder: slugify(title) || t("posts.form.slugPlaceholder")
1403
- }
1404
- )
1405
- ] }),
1406
- /* @__PURE__ */ jsxs8("div", { className: "space-y-2", children: [
1407
- /* @__PURE__ */ jsx10(Label2, { htmlFor: "excerpt", children: t("posts.form.excerpt") }),
1408
- /* @__PURE__ */ jsx10(
1409
- Textarea,
1410
- {
1411
- id: "excerpt",
1412
- rows: 2,
1413
- value: excerpt,
1414
- onChange: (e) => setExcerpt(e.target.value)
1415
- }
1416
- )
1417
- ] }),
1418
- /* @__PURE__ */ jsxs8("div", { className: "space-y-2", children: [
1419
- /* @__PURE__ */ jsx10(Label2, { htmlFor: "format", children: t("posts.form.format") }),
1420
- /* @__PURE__ */ jsxs8(
1421
- "select",
1422
- {
1423
- id: "format",
1424
- value: format,
1425
- onChange: (e) => changeFormat(e.target.value),
1426
- className: "flex h-9 w-full max-w-xs rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm",
1427
- children: [
1428
- /* @__PURE__ */ jsx10("option", { value: "tiptap", children: "Tiptap (rich editor)" }),
1429
- /* @__PURE__ */ jsx10("option", { value: "markdown", children: "Markdown" }),
1430
- /* @__PURE__ */ jsx10("option", { value: "html", children: "HTML" })
1431
- ]
1432
- }
1433
- ),
1434
- /* @__PURE__ */ jsx10("p", { className: "text-xs text-muted-foreground", children: t("posts.form.formatHint") })
1435
- ] }),
1436
- /* @__PURE__ */ jsxs8("div", { className: "space-y-2", children: [
1437
- /* @__PURE__ */ jsxs8("div", { className: "flex items-center justify-between", children: [
1438
- /* @__PURE__ */ jsx10(Label2, { children: t("posts.form.body") }),
1439
- format !== "tiptap" && // For textarea-based formats (markdown / html) there's no
1440
- // embedded toolbar, so we surface the MediaPicker as a
1441
- // standalone button. Selecting an asset inserts a
1442
- // format-aware snippet at the cursor.
1443
- /* @__PURE__ */ jsx10(
1444
- MediaPicker,
1445
- {
1446
- onSelect: insertMediaSnippet,
1447
- trigger: /* @__PURE__ */ jsxs8(Button7, { type: "button", variant: "outline", size: "sm", children: [
1448
- /* @__PURE__ */ jsx10(ImageIcon3, { className: "mr-2 h-3 w-3" }),
1449
- t("posts.form.insertMedia")
1450
- ] })
1451
- }
1452
- )
1453
- ] }),
1454
- format === "tiptap" ? /* @__PURE__ */ jsx10(TiptapEditor, { initialContent: body, onChange: setBody }) : /* @__PURE__ */ jsx10(
1455
- Textarea,
1456
- {
1457
- ref: bodyTextareaRef,
1458
- rows: 20,
1459
- value: typeof body === "string" ? body : "",
1460
- onChange: (e) => setBody(e.target.value),
1461
- className: "font-mono text-xs"
1462
- }
1463
- )
1464
- ] }),
1465
- /* @__PURE__ */ jsxs8("div", { className: "space-y-2", children: [
1466
- /* @__PURE__ */ jsx10(Label2, { htmlFor: "tags", children: t("posts.form.tags") }),
1467
- /* @__PURE__ */ jsx10(
1468
- Input2,
1469
- {
1470
- id: "tags",
1471
- value: tagsInput,
1472
- onChange: (e) => setTagsInput(e.target.value),
1473
- placeholder: t("posts.form.tagsPlaceholder")
1474
- }
1475
- ),
1476
- /* @__PURE__ */ jsx10("p", { className: "text-xs text-muted-foreground", children: t("posts.form.tagsHint") })
1477
- ] }),
1478
- /* @__PURE__ */ jsxs8("div", { className: "space-y-2", children: [
1479
- /* @__PURE__ */ jsx10(Label2, { htmlFor: "status", children: t("posts.form.status") }),
1480
- /* @__PURE__ */ jsxs8(
1481
- "select",
1482
- {
1483
- id: "status",
1484
- value: status,
1485
- onChange: (e) => setStatus(e.target.value),
1486
- className: "flex h-9 w-full max-w-xs rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm",
1487
- children: [
1488
- /* @__PURE__ */ jsx10("option", { value: "draft", children: t("common.draft") }),
1489
- /* @__PURE__ */ jsx10("option", { value: "published", children: t("common.published") })
1490
- ]
1491
- }
1492
- )
1493
- ] }),
1494
- format === "html" && /* @__PURE__ */ jsx10("div", { className: "space-y-2", children: /* @__PURE__ */ jsxs8("label", { className: "flex items-start gap-2 text-sm", children: [
1495
- /* @__PURE__ */ jsx10(
1496
- "input",
1497
- {
1498
- type: "checkbox",
1499
- checked: noLayout,
1500
- onChange: (e) => setNoLayout(e.target.checked),
1501
- className: "mt-1"
1502
- }
1503
- ),
1504
- /* @__PURE__ */ jsxs8("span", { children: [
1505
- /* @__PURE__ */ jsx10("span", { className: "font-medium", children: t("posts.form.noLayout") }),
1506
- /* @__PURE__ */ jsx10("span", { className: "block text-xs text-muted-foreground", children: t("posts.form.noLayoutHint") })
1507
- ] })
1508
- ] }) }),
1509
- error && /* @__PURE__ */ jsx10("p", { className: "text-sm text-destructive", children: error }),
1510
- /* @__PURE__ */ jsxs8("div", { className: "flex items-center gap-2", children: [
1511
- /* @__PURE__ */ jsx10(Button7, { type: "submit", disabled: saving, children: saving ? t("common.saving") : isEdit ? t("posts.form.saveChanges") : t("posts.form.createPost") }),
1512
- isEdit && /* @__PURE__ */ jsx10(Button7, { type: "button", variant: "destructive", onClick: handleDelete, disabled: saving, children: t("posts.form.delete") })
1513
- ] })
1514
- ] })
1515
- ] });
1516
- }
1517
-
1518
- // src/components/new-post-view.tsx
1519
- import { jsx as jsx11, jsxs as jsxs9 } from "react/jsx-runtime";
1520
- function NewPostPage() {
1521
- const t = useT();
1522
- return /* @__PURE__ */ jsxs9("div", { className: "mx-auto max-w-7xl p-4 md:p-8", children: [
1523
- /* @__PURE__ */ jsx11("h1", { className: "mb-6 text-2xl font-bold md:mb-8 md:text-3xl", children: t("posts.form.newTitle") }),
1524
- /* @__PURE__ */ jsx11(PostForm, {})
1525
- ] });
1526
- }
1527
-
1528
- // src/components/edit-post-view.tsx
1529
- import { useEffect as useEffect5, useState as useState6, use } from "react";
1530
- import { notFound } from "next/navigation";
1531
- import { getPostById } from "ampless";
1532
- import { jsx as jsx12, jsxs as jsxs10 } from "react/jsx-runtime";
1533
- function EditPostPage({ params }) {
1534
- const t = useT();
1535
- const { postId } = use(params);
1536
- const [post, setPost] = useState6(null);
1537
- const [loading, setLoading] = useState6(true);
1538
- const [missing, setMissing] = useState6(false);
1539
- useEffect5(() => {
1540
- const siteId = readAdminSiteIdFromCookie();
1541
- getPostById(postId, { siteId }).then((p) => {
1542
- if (!p) setMissing(true);
1543
- else setPost(p);
1544
- }).finally(() => setLoading(false));
1545
- }, [postId]);
1546
- if (loading)
1547
- return /* @__PURE__ */ jsx12("div", { className: "mx-auto max-w-7xl p-4 md:p-8", children: t("common.loading") });
1548
- if (missing) notFound();
1549
- return /* @__PURE__ */ jsxs10("div", { className: "mx-auto max-w-7xl p-4 md:p-8", children: [
1550
- /* @__PURE__ */ jsx12("h1", { className: "mb-6 text-2xl font-bold md:mb-8 md:text-3xl", children: t("posts.form.editTitle") }),
1551
- post && /* @__PURE__ */ jsx12(PostForm, { post })
1552
- ] });
1553
- }
1554
-
1555
- // src/components/media-uploader.tsx
1556
- import { useState as useState7, useEffect as useEffect6, useCallback, useRef as useRef4 } from "react";
1557
- import { uploadData as uploadData2, list as list2, remove, isCancelError } from "aws-amplify/storage";
1558
- import { processImage as processImage2 } from "ampless/media";
1559
- import { Button as Button8, Input as Input3 } from "@ampless/runtime/ui";
1560
- import { Trash2 as Trash22, Copy, Check, FileText, Code2 } from "lucide-react";
1561
- import { jsx as jsx13, jsxs as jsxs11 } from "react/jsx-runtime";
1562
- var IMAGE_EXT_RE = /\.(jpe?g|png|gif|webp|avif|svg|bmp|tiff?)$/i;
1563
- var STYLESHEET_EXT_RE = /\.css$/i;
1564
- var SCRIPT_EXT_RE = /\.m?js$/i;
1565
- function getExtension(path) {
1566
- const dot = path.lastIndexOf(".");
1567
- return dot >= 0 ? path.slice(dot + 1).toUpperCase() : "FILE";
1568
- }
1569
- function snippetFor2(url, path) {
1570
- if (IMAGE_EXT_RE.test(path)) {
1571
- return `<img src="${url}" alt="" />`;
1572
- }
1573
- if (STYLESHEET_EXT_RE.test(path)) {
1574
- return `<link rel="stylesheet" href="${url}" />`;
1575
- }
1576
- if (SCRIPT_EXT_RE.test(path)) {
1577
- return `<script src="${url}"></script>`;
1578
- }
1579
- return url;
1580
- }
1581
- function sanitizeName2(name) {
1582
- return name.replace(/[ -]/g, "").replace(/[\\/:*?"<>|]/g, "_").replace(/\s+/g, "_").replace(/^\.+/, "_").slice(0, 200) || "upload";
1583
- }
1584
- function MediaUploader() {
1585
- const t = useT();
1586
- const [items, setItems] = useState7([]);
1587
- const [queue, setQueue] = useState7([]);
1588
- const [uploading, setUploading] = useState7(false);
1589
- const [error, setError] = useState7(null);
1590
- const [copiedPath, setCopiedPath] = useState7(null);
1591
- const uploadTaskRef = useRef4(null);
1592
- const cancelTokenRef = useRef4({ cancelled: false });
1593
- const refresh = useCallback(async () => {
1594
- try {
1595
- const result = await list2({ path: "public/media/" });
1596
- setItems(
1597
- result.items.map((item) => ({
1598
- path: item.path,
1599
- url: publicMediaUrl(item.path)
1600
- }))
1601
- );
1602
- } catch (err) {
1603
- setError(err instanceof Error ? err.message : String(err));
1604
- }
1605
- }, []);
1606
- useEffect6(() => {
1607
- refresh();
1608
- }, [refresh]);
1609
- function handleFiles(e) {
1610
- const files = Array.from(e.target.files ?? []);
1611
- e.target.value = "";
1612
- if (files.length === 0) return;
1613
- setError(null);
1614
- setQueue((prev) => [...prev, ...files]);
1615
- }
1616
- async function handleDialogConfirm(file, options) {
1617
- const token = { cancelled: false };
1618
- cancelTokenRef.current = token;
1619
- setUploading(true);
1620
- setError(null);
1621
- let advance = true;
1622
- try {
1623
- const processed = await processImage2(file, options);
1624
- if (token.cancelled) {
1625
- advance = false;
1626
- return;
1627
- }
1628
- const safeName = sanitizeName2(processed.suggestedName);
1629
- const now = /* @__PURE__ */ new Date();
1630
- const yyyy = now.getFullYear();
1631
- const mm = String(now.getMonth() + 1).padStart(2, "0");
1632
- const path = `public/media/${yyyy}/${mm}/${Date.now()}-${safeName}`;
1633
- const task = uploadData2({
1634
- path,
1635
- data: processed.blob,
1636
- options: { contentType: processed.mime }
1637
- });
1638
- uploadTaskRef.current = task;
1639
- await task.result;
1640
- await refresh();
1641
- } catch (err) {
1642
- if (isCancelError(err) || token.cancelled) {
1643
- advance = false;
1644
- } else {
1645
- setError(err instanceof Error ? err.message : String(err));
1646
- }
1647
- } finally {
1648
- uploadTaskRef.current = null;
1649
- setUploading(false);
1650
- if (advance) {
1651
- setQueue((prev) => prev.slice(1));
1652
- }
1653
- }
1654
- }
1655
- function handleDialogSkip() {
1656
- if (uploading) return;
1657
- setQueue((prev) => prev.slice(1));
1658
- }
1659
- function handleDialogCancel() {
1660
- cancelTokenRef.current.cancelled = true;
1661
- uploadTaskRef.current?.cancel();
1662
- setQueue([]);
1663
- }
1664
- async function handleDelete(path) {
1665
- if (!confirm(t("media.deleteConfirm"))) return;
1666
- try {
1667
- await remove({ path });
1668
- await refresh();
1669
- } catch (err) {
1670
- setError(err instanceof Error ? err.message : String(err));
1671
- }
1672
- }
1673
- async function handleCopy(item, mode) {
1674
- const text = mode === "url" ? item.url : snippetFor2(item.url, item.path);
1675
- await navigator.clipboard.writeText(text);
1676
- const key = `${item.path}:${mode}`;
1677
- setCopiedPath(key);
1678
- setTimeout(() => setCopiedPath((p) => p === key ? null : p), 1500);
1679
- }
1680
- const currentFile = queue[0] ?? null;
1681
- return /* @__PURE__ */ jsxs11("div", { className: "space-y-6", children: [
1682
- /* @__PURE__ */ jsxs11("div", { className: "rounded-md border p-4", children: [
1683
- /* @__PURE__ */ jsx13(
1684
- Input3,
1685
- {
1686
- type: "file",
1687
- multiple: true,
1688
- onChange: handleFiles,
1689
- disabled: uploading
1690
- }
1691
- ),
1692
- uploading && /* @__PURE__ */ jsx13("p", { className: "mt-2 text-sm text-muted-foreground", children: t("media.uploading") }),
1693
- !uploading && queue.length > 0 && /* @__PURE__ */ jsx13("p", { className: "mt-2 text-sm text-muted-foreground", children: t("media.queued", { count: queue.length }) })
1694
- ] }),
1695
- error && /* @__PURE__ */ jsx13("p", { className: "text-sm text-destructive", children: error }),
1696
- /* @__PURE__ */ jsx13(
1697
- ImageUploadDialog,
1698
- {
1699
- file: currentFile,
1700
- remaining: queue.length,
1701
- busy: uploading,
1702
- defaults: getMediaProcessingDefaults(),
1703
- onConfirm: handleDialogConfirm,
1704
- onSkip: handleDialogSkip,
1705
- onCancel: handleDialogCancel
1706
- }
1707
- ),
1708
- /* @__PURE__ */ jsx13("div", { className: "grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4", children: items.map((item) => {
1709
- const isImage = IMAGE_EXT_RE.test(item.path);
1710
- const isStylesheet = STYLESHEET_EXT_RE.test(item.path);
1711
- const isScript = SCRIPT_EXT_RE.test(item.path);
1712
- const filename = item.path.split("/").pop() ?? "";
1713
- const ext = getExtension(item.path);
1714
- const tagSnippet = snippetFor2(item.url, item.path);
1715
- const tagDiffersFromUrl = tagSnippet !== item.url;
1716
- const urlCopied = copiedPath === `${item.path}:url`;
1717
- const tagCopied = copiedPath === `${item.path}:tag`;
1718
- return /* @__PURE__ */ jsxs11(
1719
- "div",
1720
- {
1721
- className: "group relative overflow-hidden rounded-md border bg-[var(--card)]",
1722
- children: [
1723
- isImage ? (
1724
- // eslint-disable-next-line @next/next/no-img-element
1725
- /* @__PURE__ */ jsx13(
1726
- "img",
1727
- {
1728
- src: item.url,
1729
- alt: item.path,
1730
- className: "aspect-square w-full object-cover"
1731
- }
1732
- )
1733
- ) : /* @__PURE__ */ jsxs11("div", { className: "flex aspect-square w-full flex-col items-center justify-center gap-2 bg-muted text-muted-foreground", children: [
1734
- isStylesheet || isScript ? /* @__PURE__ */ jsx13(Code2, { className: "h-8 w-8" }) : /* @__PURE__ */ jsx13(FileText, { className: "h-8 w-8" }),
1735
- /* @__PURE__ */ jsxs11("span", { className: "font-mono text-xs font-semibold", children: [
1736
- ".",
1737
- ext.toLowerCase()
1738
- ] })
1739
- ] }),
1740
- /* @__PURE__ */ jsxs11("div", { className: "flex items-center justify-between border-t px-2 py-1 text-xs", children: [
1741
- /* @__PURE__ */ jsx13("span", { className: "truncate", title: filename, children: filename }),
1742
- /* @__PURE__ */ jsxs11("div", { className: "flex shrink-0 items-center gap-0.5", children: [
1743
- /* @__PURE__ */ jsx13(
1744
- Button8,
1745
- {
1746
- type: "button",
1747
- variant: "ghost",
1748
- size: "icon",
1749
- className: "h-6 w-6",
1750
- onClick: () => handleCopy(item, "url"),
1751
- title: t("media.copyUrl"),
1752
- children: urlCopied ? /* @__PURE__ */ jsx13(Check, { className: "h-3 w-3" }) : /* @__PURE__ */ jsx13(Copy, { className: "h-3 w-3" })
1753
- }
1754
- ),
1755
- tagDiffersFromUrl && /* @__PURE__ */ jsx13(
1756
- Button8,
1757
- {
1758
- type: "button",
1759
- variant: "ghost",
1760
- size: "icon",
1761
- className: "h-6 w-6",
1762
- onClick: () => handleCopy(item, "tag"),
1763
- title: t("media.copyTag"),
1764
- children: tagCopied ? /* @__PURE__ */ jsx13(Check, { className: "h-3 w-3" }) : /* @__PURE__ */ jsx13(Code2, { className: "h-3 w-3" })
1765
- }
1766
- ),
1767
- /* @__PURE__ */ jsx13(
1768
- Button8,
1769
- {
1770
- type: "button",
1771
- variant: "ghost",
1772
- size: "icon",
1773
- className: "h-6 w-6",
1774
- onClick: () => handleDelete(item.path),
1775
- title: t("media.delete"),
1776
- children: /* @__PURE__ */ jsx13(Trash22, { className: "h-3 w-3" })
1777
- }
1778
- )
1779
- ] })
1780
- ] })
1781
- ]
1782
- },
1783
- item.path
1784
- );
1785
- }) }),
1786
- items.length === 0 && /* @__PURE__ */ jsx13("p", { className: "text-center text-sm text-muted-foreground", children: t("media.empty") })
1787
- ] });
1788
- }
1789
-
1790
- // src/components/media-view.tsx
1791
- import { jsx as jsx14, jsxs as jsxs12 } from "react/jsx-runtime";
1792
- function MediaPage() {
1793
- const t = useT();
1794
- return /* @__PURE__ */ jsxs12("div", { className: "mx-auto max-w-7xl p-4 md:p-8", children: [
1795
- /* @__PURE__ */ jsx14("h1", { className: "mb-6 text-2xl font-bold md:mb-8 md:text-3xl", children: t("media.title") }),
1796
- /* @__PURE__ */ jsx14(MediaUploader, {})
1797
- ] });
1798
- }
1799
-
1800
- // src/components/login-view.tsx
1801
- import { useState as useState8 } from "react";
1802
- import { useRouter as useRouter2 } from "next/navigation";
1803
- import {
1804
- signIn,
1805
- signUp,
1806
- confirmSignUp,
1807
- resetPassword,
1808
- confirmResetPassword
1809
- } from "aws-amplify/auth";
1810
- import {
1811
- Button as Button9,
1812
- Input as Input4,
1813
- Label as Label3,
1814
- Card as Card2,
1815
- CardContent as CardContent2,
1816
- CardHeader as CardHeader2,
1817
- CardTitle as CardTitle2,
1818
- CardDescription
1819
- } from "@ampless/runtime/ui";
1820
- import { Fragment as Fragment4, jsx as jsx15, jsxs as jsxs13 } from "react/jsx-runtime";
1821
- function LoginPage() {
1822
- const router = useRouter2();
1823
- const t = useT();
1824
- const [mode, setMode] = useState8("signIn");
1825
- const [email, setEmail] = useState8("");
1826
- const [password, setPassword] = useState8("");
1827
- const [code, setCode] = useState8("");
1828
- const [error, setError] = useState8(null);
1829
- const [info, setInfo] = useState8(null);
1830
- const [loading, setLoading] = useState8(false);
1831
- function go(next) {
1832
- setMode(next);
1833
- setError(null);
1834
- setInfo(null);
1835
- setCode("");
1836
- if (next === "signIn" || next === "signUp" || next === "forgot") setPassword("");
1837
- }
1838
- async function handleSubmit(e) {
1839
- e.preventDefault();
1840
- setError(null);
1841
- setInfo(null);
1842
- setLoading(true);
1843
- try {
1844
- if (mode === "signIn") {
1845
- const result = await signIn({ username: email, password });
1846
- if (result.isSignedIn) {
1847
- router.push("/admin");
1848
- router.refresh();
1849
- } else {
1850
- setError(t("auth.additionalStep", { step: result.nextStep.signInStep }));
1851
- }
1852
- } else if (mode === "signUp") {
1853
- await signUp({
1854
- username: email,
1855
- password,
1856
- options: { userAttributes: { email } }
1857
- });
1858
- go("confirm");
1859
- } else if (mode === "confirm") {
1860
- await confirmSignUp({ username: email, confirmationCode: code });
1861
- const result = await signIn({ username: email, password });
1862
- if (result.isSignedIn) {
1863
- router.push("/admin");
1864
- router.refresh();
1865
- }
1866
- } else if (mode === "forgot") {
1867
- await resetPassword({ username: email });
1868
- setMode("reset");
1869
- setInfo(t("auth.forgot.codeSent"));
1870
- } else if (mode === "reset") {
1871
- await confirmResetPassword({
1872
- username: email,
1873
- confirmationCode: code,
1874
- newPassword: password
1875
- });
1876
- const result = await signIn({ username: email, password });
1877
- if (result.isSignedIn) {
1878
- router.push("/admin");
1879
- router.refresh();
1880
- } else {
1881
- setMode("signIn");
1882
- setInfo(t("auth.reset.passwordUpdated"));
1883
- }
1884
- }
1885
- } catch (err) {
1886
- setError(err instanceof Error ? err.message : String(err));
1887
- } finally {
1888
- setLoading(false);
1889
- }
1890
- }
1891
- const showEmail = mode !== "confirm" && mode !== "reset";
1892
- const showPassword = mode === "signIn" || mode === "signUp" || mode === "reset";
1893
- const showCode = mode === "confirm" || mode === "reset";
1894
- return /* @__PURE__ */ jsx15("main", { className: "flex min-h-screen items-center justify-center bg-muted/30 p-4", children: /* @__PURE__ */ jsxs13(Card2, { className: "w-full max-w-md", children: [
1895
- /* @__PURE__ */ jsxs13(CardHeader2, { children: [
1896
- /* @__PURE__ */ jsx15(CardTitle2, { children: t(`auth.${mode}.title`) }),
1897
- /* @__PURE__ */ jsx15(CardDescription, { children: t(`auth.${mode}.description`) })
1898
- ] }),
1899
- /* @__PURE__ */ jsx15(CardContent2, { children: /* @__PURE__ */ jsxs13("form", { onSubmit: handleSubmit, className: "space-y-4", children: [
1900
- showEmail && /* @__PURE__ */ jsxs13("div", { className: "space-y-2", children: [
1901
- /* @__PURE__ */ jsx15(Label3, { htmlFor: "email", children: t("auth.common.email") }),
1902
- /* @__PURE__ */ jsx15(
1903
- Input4,
1904
- {
1905
- id: "email",
1906
- type: "email",
1907
- required: true,
1908
- value: email,
1909
- onChange: (e) => setEmail(e.target.value),
1910
- autoComplete: "email"
1911
- }
1912
- )
1913
- ] }),
1914
- showCode && /* @__PURE__ */ jsxs13("div", { className: "space-y-2", children: [
1915
- /* @__PURE__ */ jsx15(Label3, { htmlFor: "code", children: t("auth.common.code") }),
1916
- /* @__PURE__ */ jsx15(
1917
- Input4,
1918
- {
1919
- id: "code",
1920
- required: true,
1921
- value: code,
1922
- onChange: (e) => setCode(e.target.value),
1923
- autoComplete: "one-time-code"
1924
- }
1925
- )
1926
- ] }),
1927
- showPassword && /* @__PURE__ */ jsxs13("div", { className: "space-y-2", children: [
1928
- /* @__PURE__ */ jsx15(Label3, { htmlFor: "password", children: mode === "reset" ? t("auth.common.newPassword") : t("auth.common.password") }),
1929
- /* @__PURE__ */ jsx15(
1930
- Input4,
1931
- {
1932
- id: "password",
1933
- type: "password",
1934
- required: true,
1935
- minLength: 8,
1936
- value: password,
1937
- onChange: (e) => setPassword(e.target.value),
1938
- autoComplete: mode === "signIn" ? "current-password" : "new-password"
1939
- }
1940
- ),
1941
- (mode === "signUp" || mode === "reset") && /* @__PURE__ */ jsx15("p", { className: "text-xs text-muted-foreground", children: t("auth.common.passwordHint") })
1942
- ] }),
1943
- info && /* @__PURE__ */ jsx15("p", { className: "text-sm text-muted-foreground", children: info }),
1944
- error && /* @__PURE__ */ jsx15("p", { className: "text-sm text-destructive", children: error }),
1945
- /* @__PURE__ */ jsx15(Button9, { type: "submit", className: "w-full", disabled: loading, children: loading ? t("auth.common.working") : t(`auth.${mode}.submit`) }),
1946
- /* @__PURE__ */ jsxs13("div", { className: "space-y-1 text-center text-sm", children: [
1947
- mode === "signIn" && /* @__PURE__ */ jsxs13(Fragment4, { children: [
1948
- /* @__PURE__ */ jsx15("p", { children: /* @__PURE__ */ jsx15(
1949
- "button",
1950
- {
1951
- type: "button",
1952
- className: "text-primary hover:underline",
1953
- onClick: () => go("forgot"),
1954
- children: t("auth.signIn.forgotPassword")
1955
- }
1956
- ) }),
1957
- /* @__PURE__ */ jsx15("p", { children: /* @__PURE__ */ jsx15(
1958
- "button",
1959
- {
1960
- type: "button",
1961
- className: "text-primary hover:underline",
1962
- onClick: () => go("signUp"),
1963
- children: t("auth.signIn.createAccount")
1964
- }
1965
- ) })
1966
- ] }),
1967
- (mode === "signUp" || mode === "forgot" || mode === "reset") && /* @__PURE__ */ jsx15("p", { children: /* @__PURE__ */ jsx15(
1968
- "button",
1969
- {
1970
- type: "button",
1971
- className: "text-primary hover:underline",
1972
- onClick: () => go("signIn"),
1973
- children: t("auth.signUp.backToSignIn")
1974
- }
1975
- ) }),
1976
- mode === "reset" && /* @__PURE__ */ jsx15("p", { children: /* @__PURE__ */ jsx15(
1977
- "button",
1978
- {
1979
- type: "button",
1980
- className: "text-primary hover:underline",
1981
- onClick: () => go("forgot"),
1982
- children: t("auth.reset.resendCode")
1983
- }
1984
- ) })
1985
- ] })
1986
- ] }) })
1987
- ] }) });
1988
- }
1989
-
1990
- // src/components/sidebar.tsx
1991
- import { useEffect as useEffect7, useState as useState9 } from "react";
1992
- import Link4 from "next/link";
1993
- import { usePathname } from "next/navigation";
1994
- import { signOut } from "aws-amplify/auth";
1995
- import {
1996
- LayoutDashboard,
1997
- FileText as FileText2,
1998
- Image as Image2,
1999
- Globe,
2000
- Users,
2001
- LogOut,
2002
- ExternalLink,
2003
- Menu,
2004
- X
2005
- } from "lucide-react";
2006
- import { Button as Button10, cn as cn3 } from "@ampless/runtime/ui";
2007
- import { Fragment as Fragment5, jsx as jsx16, jsxs as jsxs14 } from "react/jsx-runtime";
2008
- var navItems = [
2009
- { href: "/admin", key: "sidebar.dashboard", icon: LayoutDashboard },
2010
- { href: "/admin/posts", key: "sidebar.posts", icon: FileText2 },
2011
- { href: "/admin/media", key: "sidebar.media", icon: Image2 },
2012
- { href: "/admin/sites", key: "sidebar.sites", icon: Globe },
2013
- { href: "/admin/users", key: "sidebar.users", icon: Users, adminOnly: true }
2014
- ];
2015
- function Sidebar({
2016
- email,
2017
- siteSelector,
2018
- isAdmin
2019
- }) {
2020
- const pathname = usePathname();
2021
- const t = useT();
2022
- const [open, setOpen] = useState9(false);
2023
- useEffect7(() => {
2024
- setOpen(false);
2025
- }, [pathname]);
2026
- useEffect7(() => {
2027
- if (!open) return;
2028
- const prev = document.body.style.overflow;
2029
- document.body.style.overflow = "hidden";
2030
- return () => {
2031
- document.body.style.overflow = prev;
2032
- };
2033
- }, [open]);
2034
- return /* @__PURE__ */ jsxs14(Fragment5, { children: [
2035
- /* @__PURE__ */ jsxs14("header", { className: "sticky top-0 z-30 flex h-14 items-center justify-between border-b bg-background px-4 md:hidden", children: [
2036
- /* @__PURE__ */ jsx16(Link4, { href: "/admin", className: "font-semibold", children: t("sidebar.brand") }),
2037
- /* @__PURE__ */ jsx16(
2038
- Button10,
2039
- {
2040
- variant: "ghost",
2041
- size: "icon",
2042
- "aria-label": t("sidebar.openMenu"),
2043
- "aria-expanded": open,
2044
- onClick: () => setOpen(true),
2045
- children: /* @__PURE__ */ jsx16(Menu, { className: "h-5 w-5" })
2046
- }
2047
- )
2048
- ] }),
2049
- open && /* @__PURE__ */ jsx16(
2050
- "div",
2051
- {
2052
- className: "fixed inset-0 z-40 bg-black/40 md:hidden",
2053
- "aria-hidden": "true",
2054
- onClick: () => setOpen(false)
2055
- }
2056
- ),
2057
- /* @__PURE__ */ jsxs14(
2058
- "aside",
2059
- {
2060
- className: cn3(
2061
- "fixed inset-y-0 left-0 z-50 flex w-60 flex-col border-r bg-muted/30 transition-transform md:sticky md:top-0 md:h-screen md:translate-x-0",
2062
- open ? "translate-x-0" : "-translate-x-full md:translate-x-0"
2063
- ),
2064
- "aria-label": t("sidebar.brand"),
2065
- children: [
2066
- /* @__PURE__ */ jsxs14("div", { className: "flex items-center justify-between border-b p-4", children: [
2067
- /* @__PURE__ */ jsx16(Link4, { href: "/admin", className: "font-semibold", children: t("sidebar.brand") }),
2068
- /* @__PURE__ */ jsx16(
2069
- Button10,
2070
- {
2071
- variant: "ghost",
2072
- size: "icon",
2073
- className: "md:hidden",
2074
- "aria-label": t("sidebar.closeMenu"),
2075
- onClick: () => setOpen(false),
2076
- children: /* @__PURE__ */ jsx16(X, { className: "h-5 w-5" })
2077
- }
2078
- )
2079
- ] }),
2080
- siteSelector ? /* @__PURE__ */ jsx16("div", { className: "border-b", children: siteSelector }) : null,
2081
- /* @__PURE__ */ jsx16("nav", { className: "flex-1 space-y-1 overflow-y-auto p-2", children: navItems.map((item) => {
2082
- if (item.adminOnly && !isAdmin) return null;
2083
- const Icon = item.icon;
2084
- const isActive = pathname === item.href || item.href !== "/admin" && pathname?.startsWith(item.href);
2085
- return /* @__PURE__ */ jsxs14(
2086
- Link4,
2087
- {
2088
- href: item.href,
2089
- className: cn3(
2090
- "flex items-center gap-3 rounded-md px-3 py-2 text-sm transition-colors",
2091
- isActive ? "bg-accent text-accent-foreground" : "text-muted-foreground hover:bg-accent hover:text-accent-foreground"
2092
- ),
2093
- children: [
2094
- /* @__PURE__ */ jsx16(Icon, { className: "h-4 w-4" }),
2095
- t(item.key)
2096
- ]
2097
- },
2098
- item.href
2099
- );
2100
- }) }),
2101
- /* @__PURE__ */ jsxs14("div", { className: "border-t p-2 space-y-1", children: [
2102
- /* @__PURE__ */ jsxs14(
2103
- Link4,
2104
- {
2105
- href: "/",
2106
- target: "_blank",
2107
- className: "flex items-center gap-3 rounded-md px-3 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground",
2108
- children: [
2109
- /* @__PURE__ */ jsx16(ExternalLink, { className: "h-4 w-4" }),
2110
- t("sidebar.viewSite")
2111
- ]
2112
- }
2113
- ),
2114
- /* @__PURE__ */ jsx16("div", { className: "px-3 py-2 text-xs text-muted-foreground truncate", children: email }),
2115
- /* @__PURE__ */ jsxs14(
2116
- Button10,
2117
- {
2118
- variant: "ghost",
2119
- size: "sm",
2120
- className: "w-full justify-start gap-3",
2121
- onClick: async () => {
2122
- await signOut();
2123
- window.location.href = "/login";
2124
- },
2125
- children: [
2126
- /* @__PURE__ */ jsx16(LogOut, { className: "h-4 w-4" }),
2127
- t("sidebar.signOut")
2128
- ]
2129
- }
2130
- )
2131
- ] })
2132
- ]
2133
- }
2134
- )
2135
- ] });
2136
- }
2137
-
2138
- // src/components/site-selector.tsx
2139
- import { useRouter as useRouter3 } from "next/navigation";
2140
- import { jsx as jsx17, jsxs as jsxs15 } from "react/jsx-runtime";
2141
- function SiteSelector({ current, sites }) {
2142
- const router = useRouter3();
2143
- const t = useT();
2144
- function onChange(e) {
2145
- const next = e.target.value;
2146
- document.cookie = `${ADMIN_SITE_COOKIE}=${encodeURIComponent(next)}; Path=/; Max-Age=${60 * 60 * 24 * 365}; SameSite=Lax`;
2147
- router.refresh();
2148
- }
2149
- return /* @__PURE__ */ jsxs15("div", { className: "px-3 py-2", children: [
2150
- /* @__PURE__ */ jsx17("label", { className: "block text-xs uppercase tracking-wide text-muted-foreground mb-1", children: t("sites.selector.label") }),
2151
- /* @__PURE__ */ jsx17(
2152
- "select",
2153
- {
2154
- value: current,
2155
- onChange,
2156
- className: "w-full rounded-md border bg-background px-2 py-1.5 text-sm",
2157
- children: sites.map((s) => /* @__PURE__ */ jsx17("option", { value: s.id, children: s.name }, s.id))
2158
- }
2159
- )
2160
- ] });
2161
- }
2162
-
2163
- // src/components/site-settings-form.tsx
2164
- import { useState as useState10 } from "react";
2165
- import { useRouter as useRouter4 } from "next/navigation";
2166
- import { setSiteSetting } from "ampless";
2167
- import { Button as Button11, Input as Input5, Label as Label4, Textarea as Textarea2 } from "@ampless/runtime/ui";
2168
- import { jsx as jsx18, jsxs as jsxs16 } from "react/jsx-runtime";
2169
- var KEYS = [
2170
- "site.name",
2171
- "site.url",
2172
- "site.description",
2173
- "media.imageDisplay",
2174
- "media.imageMaxWidth",
2175
- "dateFormat",
2176
- "timezone"
2177
- ];
2178
- function SiteSettingsForm({ siteId, initial, fallback }) {
2179
- const router = useRouter4();
2180
- const t = useT();
2181
- const [values, setValues] = useState10(initial);
2182
- const [saving, setSaving] = useState10(false);
2183
- const [error, setError] = useState10(null);
2184
- const [info, setInfo] = useState10(null);
2185
- function update(key, value) {
2186
- setValues((prev) => ({ ...prev, [key]: value }));
2187
- }
2188
- async function save(e) {
2189
- e.preventDefault();
2190
- setSaving(true);
2191
- setError(null);
2192
- setInfo(null);
2193
- try {
2194
- await Promise.all(
2195
- KEYS.map((key) => {
2196
- const value = values[key];
2197
- if (value === void 0 || value === "") return Promise.resolve();
2198
- return setSiteSetting(siteId, key, value);
2199
- })
2200
- );
2201
- setInfo(t("sites.edit.saved"));
2202
- router.refresh();
2203
- } catch (err) {
2204
- setError(err instanceof Error ? err.message : String(err));
2205
- } finally {
2206
- setSaving(false);
2207
- }
2208
- }
2209
- return /* @__PURE__ */ jsxs16("form", { onSubmit: save, className: "space-y-6 max-w-xl", children: [
2210
- /* @__PURE__ */ jsxs16("fieldset", { className: "space-y-4", children: [
2211
- /* @__PURE__ */ jsx18("legend", { className: "text-sm font-medium uppercase tracking-wide text-muted-foreground", children: t("sites.edit.site") }),
2212
- /* @__PURE__ */ jsxs16("div", { className: "space-y-2", children: [
2213
- /* @__PURE__ */ jsx18(Label4, { htmlFor: "name", children: t("common.name") }),
2214
- /* @__PURE__ */ jsx18(
2215
- Input5,
2216
- {
2217
- id: "name",
2218
- value: values["site.name"] ?? "",
2219
- placeholder: fallback["site.name"] ?? "",
2220
- onChange: (e) => update("site.name", e.target.value)
2221
- }
2222
- )
2223
- ] }),
2224
- /* @__PURE__ */ jsxs16("div", { className: "space-y-2", children: [
2225
- /* @__PURE__ */ jsx18(Label4, { htmlFor: "url", children: t("common.url") }),
2226
- /* @__PURE__ */ jsx18(
2227
- Input5,
2228
- {
2229
- id: "url",
2230
- value: values["site.url"] ?? "",
2231
- placeholder: fallback["site.url"] ?? "",
2232
- onChange: (e) => update("site.url", e.target.value)
2233
- }
2234
- )
2235
- ] }),
2236
- /* @__PURE__ */ jsxs16("div", { className: "space-y-2", children: [
2237
- /* @__PURE__ */ jsx18(Label4, { htmlFor: "description", children: t("common.description") }),
2238
- /* @__PURE__ */ jsx18(
2239
- Textarea2,
2240
- {
2241
- id: "description",
2242
- value: values["site.description"] ?? "",
2243
- placeholder: fallback["site.description"] ?? "",
2244
- rows: 2,
2245
- onChange: (e) => update("site.description", e.target.value)
2246
- }
2247
- )
2248
- ] })
2249
- ] }),
2250
- /* @__PURE__ */ jsxs16("fieldset", { className: "space-y-4", children: [
2251
- /* @__PURE__ */ jsx18("legend", { className: "text-sm font-medium uppercase tracking-wide text-muted-foreground", children: t("sites.edit.media") }),
2252
- /* @__PURE__ */ jsxs16("div", { className: "space-y-2", children: [
2253
- /* @__PURE__ */ jsx18(Label4, { htmlFor: "imageDisplay", children: t("sites.edit.imageDisplay") }),
2254
- /* @__PURE__ */ jsxs16(
2255
- "select",
2256
- {
2257
- id: "imageDisplay",
2258
- className: "w-full rounded-md border bg-background px-2 py-1.5 text-sm",
2259
- value: values["media.imageDisplay"] ?? "",
2260
- onChange: (e) => update("media.imageDisplay", e.target.value),
2261
- children: [
2262
- /* @__PURE__ */ jsx18("option", { value: "", children: t("sites.edit.defaultPlaceholder", {
2263
- value: fallback["media.imageDisplay"] ?? "inline"
2264
- }) }),
2265
- /* @__PURE__ */ jsx18("option", { value: "inline", children: t("sites.edit.imageDisplayInline") }),
2266
- /* @__PURE__ */ jsx18("option", { value: "lightbox", children: t("sites.edit.imageDisplayLightbox") })
2267
- ]
2268
- }
2269
- )
2270
- ] }),
2271
- /* @__PURE__ */ jsxs16("div", { className: "space-y-2", children: [
2272
- /* @__PURE__ */ jsx18(Label4, { htmlFor: "imageMaxWidth", children: t("sites.edit.imageMaxWidth") }),
2273
- /* @__PURE__ */ jsx18(
2274
- Input5,
2275
- {
2276
- id: "imageMaxWidth",
2277
- value: values["media.imageMaxWidth"] ?? "",
2278
- placeholder: fallback["media.imageMaxWidth"] ?? "100%",
2279
- onChange: (e) => update("media.imageMaxWidth", e.target.value)
2280
- }
2281
- )
2282
- ] })
2283
- ] }),
2284
- /* @__PURE__ */ jsxs16("fieldset", { className: "space-y-4", children: [
2285
- /* @__PURE__ */ jsx18("legend", { className: "text-sm font-medium uppercase tracking-wide text-muted-foreground", children: t("sites.edit.dateDisplay") }),
2286
- /* @__PURE__ */ jsxs16("div", { className: "space-y-2", children: [
2287
- /* @__PURE__ */ jsx18(Label4, { htmlFor: "dateFormat", children: t("sites.edit.dateFormat") }),
2288
- /* @__PURE__ */ jsxs16(
2289
- "select",
2290
- {
2291
- id: "dateFormat",
2292
- className: "w-full rounded-md border bg-background px-2 py-1.5 text-sm",
2293
- value: values["dateFormat"] ?? "",
2294
- onChange: (e) => update("dateFormat", e.target.value),
2295
- children: [
2296
- /* @__PURE__ */ jsx18("option", { value: "", children: t("sites.edit.defaultPlaceholder", {
2297
- value: fallback["dateFormat"] ?? "iso"
2298
- }) }),
2299
- /* @__PURE__ */ jsx18("option", { value: "iso", children: t("sites.edit.dateFormatIso") }),
2300
- /* @__PURE__ */ jsx18("option", { value: "long", children: t("sites.edit.dateFormatLong") }),
2301
- /* @__PURE__ */ jsx18("option", { value: "locale", children: t("sites.edit.dateFormatLocale") })
2302
- ]
2303
- }
2304
- )
2305
- ] }),
2306
- /* @__PURE__ */ jsxs16("div", { className: "space-y-2", children: [
2307
- /* @__PURE__ */ jsx18(Label4, { htmlFor: "timezone", children: t("sites.edit.timezone") }),
2308
- /* @__PURE__ */ jsx18(
2309
- Input5,
2310
- {
2311
- id: "timezone",
2312
- value: values["timezone"] ?? "",
2313
- placeholder: fallback["timezone"] ?? "UTC",
2314
- onChange: (e) => update("timezone", e.target.value)
2315
- }
2316
- )
2317
- ] })
2318
- ] }),
2319
- info && /* @__PURE__ */ jsx18("p", { className: "text-sm text-muted-foreground", children: info }),
2320
- error && /* @__PURE__ */ jsx18("p", { className: "text-sm text-destructive", children: error }),
2321
- /* @__PURE__ */ jsx18(Button11, { type: "submit", disabled: saving, children: saving ? t("common.saving") : t("sites.edit.saveButton") })
2322
- ] });
2323
- }
2324
-
2325
- // src/components/theme-settings-form.tsx
2326
- import { useState as useState11 } from "react";
2327
- import { useRouter as useRouter5 } from "next/navigation";
2328
- import {
2329
- setSiteSetting as setSiteSetting2,
2330
- deleteSiteSetting,
2331
- themeSettingKey,
2332
- validateThemeValue,
2333
- resolveLocalized,
2334
- parseLinkList,
2335
- stringifyLinkList
2336
- } from "ampless";
2337
- import { Button as Button12, Input as Input6, Label as Label5 } from "@ampless/runtime/ui";
2338
- import { jsx as jsx19, jsxs as jsxs17 } from "react/jsx-runtime";
2339
- var CACHE_REBUILD_DELAY_MS = 8e3;
2340
- function ThemeSettingsForm({
2341
- siteId,
2342
- manifest,
2343
- activeTheme,
2344
- themeOptions,
2345
- initial
2346
- }) {
2347
- const router = useRouter5();
2348
- const t = useT();
2349
- const locale = useLocale();
2350
- const [state, setState] = useState11({ values: initial, touched: {} });
2351
- const [pendingTheme, setPendingTheme] = useState11(activeTheme);
2352
- const [optimisticActive, setOptimisticActive] = useState11(activeTheme);
2353
- const [saving, setSaving] = useState11(false);
2354
- const [switching, setSwitching] = useState11(false);
2355
- const [error, setError] = useState11(null);
2356
- const [info, setInfo] = useState11(null);
2357
- const [invalid, setInvalid] = useState11({});
2358
- function update(key, value) {
2359
- setState((prev) => ({
2360
- values: { ...prev.values, [key]: value },
2361
- touched: { ...prev.touched, [key]: true }
2362
- }));
2363
- }
2364
- function scheduleCacheInvalidation() {
2365
- setTimeout(async () => {
2366
- try {
2367
- await invalidateSiteSettingsCache(siteId);
2368
- } catch (err) {
2369
- console.warn("[theme] cache invalidation failed", err);
2370
- }
2371
- }, CACHE_REBUILD_DELAY_MS);
2372
- }
2373
- function scheduleHardReload() {
2374
- setTimeout(async () => {
2375
- try {
2376
- await invalidateSiteSettingsCache(siteId);
2377
- } catch (err) {
2378
- console.warn("[theme] cache invalidation failed", err);
2379
- }
2380
- window.location.reload();
2381
- }, CACHE_REBUILD_DELAY_MS);
2382
- }
2383
- async function switchTheme(e) {
2384
- e.preventDefault();
2385
- if (pendingTheme === optimisticActive) return;
2386
- setSwitching(true);
2387
- setError(null);
2388
- setInfo(null);
2389
- try {
2390
- await setSiteSetting2(siteId, "theme.active", pendingTheme);
2391
- setOptimisticActive(pendingTheme);
2392
- setInfo(t("theme.switched", { theme: pendingTheme }));
2393
- scheduleHardReload();
2394
- } catch (err) {
2395
- console.error("[theme] switch failed", err);
2396
- setError(err instanceof Error ? err.message : String(err));
2397
- } finally {
2398
- setSwitching(false);
2399
- }
2400
- }
2401
- async function save(e) {
2402
- e.preventDefault();
2403
- setSaving(true);
2404
- setError(null);
2405
- setInfo(null);
2406
- setInvalid({});
2407
- const newInvalid = {};
2408
- const writes = [];
2409
- for (const field of manifest.fields) {
2410
- if (!state.touched[field.key]) continue;
2411
- const raw = (state.values[field.key] ?? "").trim();
2412
- const storeKey = themeSettingKey(field.key);
2413
- if (raw === "") {
2414
- writes.push(deleteSiteSetting(siteId, storeKey));
2415
- continue;
2416
- }
2417
- const validated = validateThemeValue(field, raw);
2418
- if (validated === null) {
2419
- newInvalid[field.key] = true;
2420
- continue;
2421
- }
2422
- writes.push(setSiteSetting2(siteId, storeKey, validated));
2423
- }
2424
- if (Object.keys(newInvalid).length > 0) {
2425
- setInvalid(newInvalid);
2426
- setSaving(false);
2427
- setError(t("theme.invalidValues"));
2428
- return;
2429
- }
2430
- try {
2431
- await Promise.all(writes);
2432
- setInfo(t("theme.saved"));
2433
- setState((prev) => ({ values: prev.values, touched: {} }));
2434
- scheduleCacheInvalidation();
2435
- } catch (err) {
2436
- console.error("[theme] save failed", err);
2437
- setError(err instanceof Error ? err.message : String(err));
2438
- } finally {
2439
- setSaving(false);
2440
- }
2441
- }
2442
- const groups = groupFields(manifest.fields);
2443
- return /* @__PURE__ */ jsxs17("div", { className: "space-y-8", children: [
2444
- /* @__PURE__ */ jsxs17("form", { onSubmit: switchTheme, className: "max-w-xl space-y-3 rounded-md border p-4", children: [
2445
- /* @__PURE__ */ jsxs17("div", { className: "space-y-1", children: [
2446
- /* @__PURE__ */ jsx19(Label5, { htmlFor: "active-theme", className: "text-sm font-medium", children: t("theme.activeLabel") }),
2447
- /* @__PURE__ */ jsxs17("p", { className: "text-xs text-muted-foreground", children: [
2448
- t("theme.currentlyActive", { theme: optimisticActive }),
2449
- optimisticActive !== activeTheme && t("theme.propagating")
2450
- ] })
2451
- ] }),
2452
- /* @__PURE__ */ jsx19(
2453
- "select",
2454
- {
2455
- id: "active-theme",
2456
- className: "w-full rounded-md border bg-background px-2 py-1.5 text-sm",
2457
- value: pendingTheme,
2458
- onChange: (e) => setPendingTheme(e.target.value),
2459
- children: themeOptions.map((opt) => /* @__PURE__ */ jsxs17("option", { value: opt.value, children: [
2460
- resolveLocalized(opt.label, locale),
2461
- " (",
2462
- opt.value,
2463
- ")"
2464
- ] }, opt.value))
2465
- }
2466
- ),
2467
- (() => {
2468
- const desc = themeOptions.find((o) => o.value === pendingTheme)?.description;
2469
- return desc ? /* @__PURE__ */ jsx19("p", { className: "text-xs text-muted-foreground", children: resolveLocalized(desc, locale) }) : null;
2470
- })(),
2471
- /* @__PURE__ */ jsx19(
2472
- Button12,
2473
- {
2474
- type: "submit",
2475
- disabled: switching || pendingTheme === optimisticActive,
2476
- variant: pendingTheme === optimisticActive ? "outline" : "default",
2477
- children: switching ? t("theme.switching") : t("theme.switchButton")
2478
- }
2479
- )
2480
- ] }),
2481
- /* @__PURE__ */ jsxs17("div", { className: "space-y-2", children: [
2482
- /* @__PURE__ */ jsx19(Label5, { className: "text-sm font-medium", children: t("theme.previewLabel") }),
2483
- /* @__PURE__ */ jsx19(
2484
- "iframe",
2485
- {
2486
- src: `/?previewTheme=${encodeURIComponent(pendingTheme)}`,
2487
- title: t("theme.previewLabel"),
2488
- className: "h-[600px] w-full rounded-md border bg-[var(--background)]"
2489
- },
2490
- pendingTheme
2491
- ),
2492
- /* @__PURE__ */ jsx19("p", { className: "text-xs text-muted-foreground", children: t("theme.previewHint") })
2493
- ] }),
2494
- /* @__PURE__ */ jsxs17("form", { onSubmit: save, className: "max-w-xl space-y-6", children: [
2495
- /* @__PURE__ */ jsxs17("div", { children: [
2496
- /* @__PURE__ */ jsx19("h2", { className: "text-lg font-semibold", children: t("theme.customizationHeading", {
2497
- theme: resolveLocalized(manifest.label, locale)
2498
- }) }),
2499
- manifest.description && /* @__PURE__ */ jsx19("p", { className: "text-sm text-muted-foreground", children: resolveLocalized(manifest.description, locale) }),
2500
- /* @__PURE__ */ jsx19("p", { className: "mt-1 text-xs text-muted-foreground", children: t("theme.customizationHint") })
2501
- ] }),
2502
- groups.map(({ key, name, fields }) => /* @__PURE__ */ jsxs17("fieldset", { className: "space-y-4", children: [
2503
- /* @__PURE__ */ jsx19("legend", { className: "text-sm font-medium uppercase tracking-wide text-muted-foreground", children: resolveLocalized(name, locale) }),
2504
- fields.map((field) => /* @__PURE__ */ jsx19(
2505
- FieldRow,
2506
- {
2507
- field,
2508
- value: state.values[field.key] ?? "",
2509
- invalid: !!invalid[field.key],
2510
- onChange: (v) => update(field.key, v)
2511
- },
2512
- field.key
2513
- ))
2514
- ] }, key)),
2515
- info && /* @__PURE__ */ jsx19("p", { className: "text-sm text-muted-foreground", children: info }),
2516
- error && /* @__PURE__ */ jsx19("p", { className: "text-sm text-destructive", children: error }),
2517
- /* @__PURE__ */ jsx19(Button12, { type: "submit", disabled: saving, children: saving ? t("theme.saving") : t("theme.saveButton") })
2518
- ] })
2519
- ] });
2520
- }
2521
- function groupFields(fields) {
2522
- const map = /* @__PURE__ */ new Map();
2523
- for (const field of fields) {
2524
- const g = field.group ?? "General";
2525
- const k = typeof g === "string" ? g : JSON.stringify(g);
2526
- const existing = map.get(k);
2527
- if (existing) {
2528
- existing.fields.push(field);
2529
- } else {
2530
- map.set(k, { name: g, fields: [field] });
2531
- }
2532
- }
2533
- return Array.from(map.entries()).map(([key, { name, fields: fields2 }]) => ({ key, name, fields: fields2 }));
2534
- }
2535
- function FieldRow({ field, value, invalid, onChange }) {
2536
- const t = useT();
2537
- const locale = useLocale();
2538
- const id = `theme-${field.key}`;
2539
- const labelEl = /* @__PURE__ */ jsx19(Label5, { htmlFor: id, className: invalid ? "text-destructive" : void 0, children: resolveLocalized(field.label, locale) });
2540
- const description = field.description ? /* @__PURE__ */ jsx19("p", { className: "text-xs text-muted-foreground", children: resolveLocalized(field.description, locale) }) : null;
2541
- switch (field.type) {
2542
- case "color":
2543
- return /* @__PURE__ */ jsx19(ColorField, { field, id, labelEl, description, value, invalid, onChange });
2544
- case "length":
2545
- return /* @__PURE__ */ jsxs17("div", { className: "space-y-2", children: [
2546
- labelEl,
2547
- description,
2548
- /* @__PURE__ */ jsx19(
2549
- Input6,
2550
- {
2551
- id,
2552
- value,
2553
- placeholder: field.default,
2554
- onChange: (e) => onChange(e.target.value),
2555
- "aria-invalid": invalid,
2556
- className: "font-mono text-xs"
2557
- }
2558
- ),
2559
- /* @__PURE__ */ jsx19("p", { className: "text-xs text-muted-foreground", children: t("theme.lengthHelp") })
2560
- ] });
2561
- case "select":
2562
- case "fontFamily":
2563
- return /* @__PURE__ */ jsxs17("div", { className: "space-y-2", children: [
2564
- labelEl,
2565
- description,
2566
- /* @__PURE__ */ jsxs17(
2567
- "select",
2568
- {
2569
- id,
2570
- className: "w-full rounded-md border bg-background px-2 py-1.5 text-sm",
2571
- value: value || "",
2572
- onChange: (e) => onChange(e.target.value),
2573
- "aria-invalid": invalid,
2574
- children: [
2575
- /* @__PURE__ */ jsx19("option", { value: "", children: t("common.default") }),
2576
- field.options.map((opt) => /* @__PURE__ */ jsx19("option", { value: opt.value, children: resolveLocalized(opt.label, locale) }, opt.value))
2577
- ]
2578
- }
2579
- )
2580
- ] });
2581
- case "image":
2582
- return /* @__PURE__ */ jsxs17("div", { className: "space-y-2", children: [
2583
- labelEl,
2584
- description,
2585
- /* @__PURE__ */ jsx19(
2586
- Input6,
2587
- {
2588
- id,
2589
- value,
2590
- placeholder: field.default || t("theme.imagePlaceholder"),
2591
- onChange: (e) => onChange(e.target.value),
2592
- "aria-invalid": invalid
2593
- }
2594
- )
2595
- ] });
2596
- case "text":
2597
- return /* @__PURE__ */ jsxs17("div", { className: "space-y-2", children: [
2598
- labelEl,
2599
- description,
2600
- /* @__PURE__ */ jsx19(
2601
- Input6,
2602
- {
2603
- id,
2604
- value,
2605
- placeholder: field.default,
2606
- maxLength: field.maxLength,
2607
- onChange: (e) => onChange(e.target.value),
2608
- "aria-invalid": invalid
2609
- }
2610
- )
2611
- ] });
2612
- case "linkList":
2613
- return /* @__PURE__ */ jsx19(
2614
- LinkListField,
2615
- {
2616
- field,
2617
- labelEl,
2618
- description,
2619
- value,
2620
- onChange
2621
- }
2622
- );
2623
- }
2624
- }
2625
- function LinkListField({ field, labelEl, description, value, onChange }) {
2626
- const items = parseLinkList(value);
2627
- const max = field.maxItems ?? 50;
2628
- function commit(next) {
2629
- onChange(stringifyLinkList(next));
2630
- }
2631
- function update(idx, patch) {
2632
- commit(items.map((it, i) => i === idx ? { ...it, ...patch } : it));
2633
- }
2634
- function add() {
2635
- if (items.length >= max) return;
2636
- commit([...items, { label: "", url: "" }]);
2637
- }
2638
- function remove2(idx) {
2639
- commit(items.filter((_, i) => i !== idx));
2640
- }
2641
- function move(idx, delta) {
2642
- const target = idx + delta;
2643
- if (target < 0 || target >= items.length) return;
2644
- const next = items.slice();
2645
- const [moved] = next.splice(idx, 1);
2646
- next.splice(target, 0, moved);
2647
- commit(next);
2648
- }
2649
- return /* @__PURE__ */ jsxs17("div", { className: "space-y-2", children: [
2650
- labelEl,
2651
- description,
2652
- /* @__PURE__ */ jsxs17("div", { className: "space-y-2 rounded-md border bg-muted/20 p-3", children: [
2653
- items.length === 0 && /* @__PURE__ */ jsx19("p", { className: "text-xs text-muted-foreground", children: "No links yet." }),
2654
- items.map((item, idx) => {
2655
- const isTagRef = /^tag:/.test(item.url.trim());
2656
- return /* @__PURE__ */ jsxs17("div", { className: "flex flex-wrap items-start gap-2", children: [
2657
- /* @__PURE__ */ jsxs17("div", { className: "grid flex-1 grid-cols-1 gap-2 sm:grid-cols-2", children: [
2658
- /* @__PURE__ */ jsx19(
2659
- Input6,
2660
- {
2661
- value: item.label,
2662
- placeholder: "Label",
2663
- onChange: (e) => update(idx, { label: e.target.value })
2664
- }
2665
- ),
2666
- /* @__PURE__ */ jsx19(
2667
- Input6,
2668
- {
2669
- value: item.url,
2670
- placeholder: "/path or https://\u2026 or tag:name",
2671
- onChange: (e) => update(idx, { url: e.target.value }),
2672
- className: isTagRef ? "font-mono text-xs" : void 0
2673
- }
2674
- )
2675
- ] }),
2676
- /* @__PURE__ */ jsxs17("div", { className: "flex shrink-0 items-center gap-1", children: [
2677
- /* @__PURE__ */ jsx19(
2678
- Button12,
2679
- {
2680
- type: "button",
2681
- variant: "ghost",
2682
- size: "icon",
2683
- onClick: () => move(idx, -1),
2684
- disabled: idx === 0,
2685
- "aria-label": "Move up",
2686
- children: "\u2191"
2687
- }
2688
- ),
2689
- /* @__PURE__ */ jsx19(
2690
- Button12,
2691
- {
2692
- type: "button",
2693
- variant: "ghost",
2694
- size: "icon",
2695
- onClick: () => move(idx, 1),
2696
- disabled: idx === items.length - 1,
2697
- "aria-label": "Move down",
2698
- children: "\u2193"
2699
- }
2700
- ),
2701
- /* @__PURE__ */ jsx19(
2702
- Button12,
2703
- {
2704
- type: "button",
2705
- variant: "ghost",
2706
- size: "icon",
2707
- onClick: () => remove2(idx),
2708
- "aria-label": "Remove",
2709
- children: "\xD7"
2710
- }
2711
- )
2712
- ] })
2713
- ] }, idx);
2714
- }),
2715
- /* @__PURE__ */ jsx19(
2716
- Button12,
2717
- {
2718
- type: "button",
2719
- variant: "outline",
2720
- size: "sm",
2721
- onClick: add,
2722
- disabled: items.length >= max,
2723
- children: "+ Add link"
2724
- }
2725
- ),
2726
- /* @__PURE__ */ jsxs17("p", { className: "text-xs text-muted-foreground", children: [
2727
- "Tip: use ",
2728
- /* @__PURE__ */ jsx19("code", { children: "tag:<name>" }),
2729
- " as a URL to render a list of posts with that tag instead of a single link."
2730
- ] })
2731
- ] })
2732
- ] });
2733
- }
2734
- function ColorField({
2735
- field,
2736
- id,
2737
- labelEl,
2738
- description,
2739
- value,
2740
- invalid,
2741
- onChange
2742
- }) {
2743
- const effective = value || field.default;
2744
- const hex = useColorAsHex(effective);
2745
- return /* @__PURE__ */ jsxs17("div", { className: "space-y-2", children: [
2746
- labelEl,
2747
- description,
2748
- /* @__PURE__ */ jsxs17("div", { className: "flex items-center gap-2", children: [
2749
- /* @__PURE__ */ jsx19(
2750
- "input",
2751
- {
2752
- type: "color",
2753
- value: hex,
2754
- onChange: (e) => onChange(e.target.value),
2755
- className: "h-9 w-12 cursor-pointer rounded border border-input bg-background p-0",
2756
- "aria-label": `${field.label} swatch`
2757
- }
2758
- ),
2759
- /* @__PURE__ */ jsx19(
2760
- Input6,
2761
- {
2762
- id,
2763
- value,
2764
- placeholder: field.default,
2765
- onChange: (e) => onChange(e.target.value),
2766
- "aria-invalid": invalid,
2767
- className: "font-mono text-xs"
2768
- }
2769
- )
2770
- ] }),
2771
- /* @__PURE__ */ jsxs17("div", { className: "flex items-center gap-2", children: [
2772
- /* @__PURE__ */ jsx19(
2773
- "span",
2774
- {
2775
- className: "inline-block h-4 w-4 rounded border",
2776
- style: { background: effective },
2777
- "aria-hidden": true
2778
- }
2779
- ),
2780
- /* @__PURE__ */ jsx19("code", { className: "text-xs text-muted-foreground", children: effective })
2781
- ] })
2782
- ] });
2783
- }
2784
- function useColorAsHex(value) {
2785
- if (typeof document === "undefined") return "#000000";
2786
- const m = /^#([0-9a-fA-F]{6})$/.exec(value);
2787
- if (m) return value.toLowerCase();
2788
- try {
2789
- const ctx = document.createElement("canvas").getContext("2d");
2790
- if (!ctx) return "#000000";
2791
- ctx.fillStyle = "#000000";
2792
- ctx.fillStyle = value;
2793
- const out = ctx.fillStyle;
2794
- return /^#[0-9a-fA-F]{6}$/.test(out) ? out : "#000000";
2795
- } catch {
2796
- return "#000000";
2797
- }
2798
- }
2799
-
2800
- export {
2801
- I18nProvider,
2802
- useT,
2803
- useLocale,
2804
- setAdminCmsConfig,
2805
- readAdminSiteIdFromCookie,
2806
- AdminProviders,
2807
- AdminDashboard,
2808
- PostsList,
2809
- sanitizeName,
2810
- uploadProcessedImage,
2811
- ImageUploadDialog,
2812
- MediaPicker,
2813
- PostForm,
2814
- NewPostPage,
2815
- EditPostPage,
2816
- MediaUploader,
2817
- MediaPage,
2818
- LoginPage,
2819
- Sidebar,
2820
- SiteSelector,
2821
- SiteSettingsForm,
2822
- ThemeSettingsForm
2823
- };