create-nextblock 0.15.5 → 0.15.9

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 (79) hide show
  1. package/package.json +50 -26
  2. package/templates/nextblock-template/app/ToasterProvider.tsx +26 -17
  3. package/templates/nextblock-template/app/actions/contactSellerActions.test.ts +280 -0
  4. package/templates/nextblock-template/app/actions/contactSellerActions.ts +222 -0
  5. package/templates/nextblock-template/app/actions/email-retry.test.ts +62 -0
  6. package/templates/nextblock-template/app/actions/email.ts +241 -110
  7. package/templates/nextblock-template/app/actions/formActions.ts +245 -116
  8. package/templates/nextblock-template/app/actions/interactions.ts +489 -396
  9. package/templates/nextblock-template/app/actions/threadActions.ts +166 -0
  10. package/templates/nextblock-template/app/api/checkout/route.ts +162 -146
  11. package/templates/nextblock-template/app/api/cron/reset-sandbox/route.ts +14 -0
  12. package/templates/nextblock-template/app/api/cron/reset-sandbox/sandboxResetSql.ts +664 -1
  13. package/templates/nextblock-template/app/checkout/page.tsx +57 -52
  14. package/templates/nextblock-template/app/cms/CmsClientLayout.tsx +552 -529
  15. package/templates/nextblock-template/app/cms/blocks/editors/FormBlockEditor.tsx +304 -181
  16. package/templates/nextblock-template/app/cms/components/ContactReminderBanner.tsx +75 -0
  17. package/templates/nextblock-template/app/cms/components/PaymentsReminderBanner.tsx +58 -0
  18. package/templates/nextblock-template/app/cms/components/VisibilityControl.tsx +542 -528
  19. package/templates/nextblock-template/app/cms/inquiries/actions.ts +66 -0
  20. package/templates/nextblock-template/app/cms/inquiries/page.tsx +12 -0
  21. package/templates/nextblock-template/app/cms/interactions/page.tsx +12 -51
  22. package/templates/nextblock-template/app/cms/layout.tsx +101 -73
  23. package/templates/nextblock-template/app/cms/messages/MessagesClient.tsx +661 -0
  24. package/templates/nextblock-template/app/cms/messages/actions.ts +404 -0
  25. package/templates/nextblock-template/app/cms/messages/loadInbox.ts +333 -0
  26. package/templates/nextblock-template/app/cms/messages/page.tsx +87 -0
  27. package/templates/nextblock-template/app/cms/messages/require-admin.ts +37 -0
  28. package/templates/nextblock-template/app/cms/products/[id]/edit/page.tsx +370 -362
  29. package/templates/nextblock-template/app/cms/revisions/service.ts +20 -0
  30. package/templates/nextblock-template/app/cms/settings/email/components/EmailForm.tsx +227 -185
  31. package/templates/nextblock-template/app/layout.tsx +671 -667
  32. package/templates/nextblock-template/app/lib/seo.ts +319 -311
  33. package/templates/nextblock-template/app/product/[slug]/page.tsx +502 -482
  34. package/templates/nextblock-template/app/providers.tsx +96 -96
  35. package/templates/nextblock-template/app/thread/ThreadView.tsx +164 -0
  36. package/templates/nextblock-template/app/thread/[token]/route.ts +57 -0
  37. package/templates/nextblock-template/app/thread/layout.tsx +15 -0
  38. package/templates/nextblock-template/app/thread/page.tsx +98 -0
  39. package/templates/nextblock-template/components/BlockRenderer.tsx +312 -296
  40. package/templates/nextblock-template/components/ContactSellerSection.tsx +188 -0
  41. package/templates/nextblock-template/components/PostCommentsSection.tsx +378 -369
  42. package/templates/nextblock-template/components/ProductReviewsSection.tsx +426 -419
  43. package/templates/nextblock-template/components/StaffReplies.tsx +102 -0
  44. package/templates/nextblock-template/components/blocks/renderers/CartBlockRenderer.tsx +18 -17
  45. package/templates/nextblock-template/components/blocks/renderers/CheckoutBlockRenderer.tsx +20 -19
  46. package/templates/nextblock-template/components/blocks/renderers/FeaturedProductBlockRenderer.tsx +25 -22
  47. package/templates/nextblock-template/components/blocks/renderers/FormBlockRenderer.tsx +385 -381
  48. package/templates/nextblock-template/components/blocks/renderers/ProductDetailsBlockRenderer.tsx +157 -92
  49. package/templates/nextblock-template/components/blocks/renderers/ProductGridBlockRenderer.tsx +34 -31
  50. package/templates/nextblock-template/components/blocks/renderers/SectionBlockRenderer.tsx +612 -600
  51. package/templates/nextblock-template/components/commerce/PaymentReadinessBoundary.tsx +32 -0
  52. package/templates/nextblock-template/docs/05-DEVELOPER-GUIDE.md +25 -19
  53. package/templates/nextblock-template/docs/06-CLI-AND-SCAFFOLDING.md +1 -1
  54. package/templates/nextblock-template/docs/08-NEXTBLOCK-CORTEX-AI-ARCHITECTURE.md +2 -2
  55. package/templates/nextblock-template/docs/12-VERCEL-DEPLOYMENT.md +32 -9
  56. package/templates/nextblock-template/docs/14-MESSAGES-INBOX.md +309 -0
  57. package/templates/nextblock-template/docs/README.md +42 -41
  58. package/templates/nextblock-template/docs/TECHNICAL_SPECIFICATION.md +540 -542
  59. package/templates/nextblock-template/docs/assets/lighthouse-scores.png +0 -0
  60. package/templates/nextblock-template/lib/blocks/blockColors.test.ts +22 -2
  61. package/templates/nextblock-template/lib/blocks/blockColors.ts +44 -1
  62. package/templates/nextblock-template/lib/blocks/blockRegistry.ts +761 -753
  63. package/templates/nextblock-template/lib/cms/contact-reminder.ts +64 -0
  64. package/templates/nextblock-template/lib/cms/payments-reminder.ts +98 -0
  65. package/templates/nextblock-template/lib/cms/unread-messages.ts +42 -0
  66. package/templates/nextblock-template/lib/commerce/seller-contact.ts +162 -0
  67. package/templates/nextblock-template/lib/config/email-settings.ts +323 -254
  68. package/templates/nextblock-template/lib/config/email-tls.test.ts +57 -0
  69. package/templates/nextblock-template/lib/email/placeholder-address.test.ts +59 -0
  70. package/templates/nextblock-template/lib/email/placeholder-address.ts +39 -0
  71. package/templates/nextblock-template/lib/messages/thread-reference.test.ts +70 -0
  72. package/templates/nextblock-template/lib/messages/thread-token.test.ts +93 -0
  73. package/templates/nextblock-template/lib/messages/thread-token.ts +157 -0
  74. package/templates/nextblock-template/lib/messages/threads.ts +579 -0
  75. package/templates/nextblock-template/lib/setup/migrations-bundle.ts +20 -0
  76. package/templates/nextblock-template/lib/site-url.test.ts +89 -0
  77. package/templates/nextblock-template/lib/site-url.ts +102 -48
  78. package/templates/nextblock-template/package.json +14 -1
  79. package/templates/nextblock-template/public/assets/nextblock-banner.jpg +0 -0
@@ -1,528 +1,542 @@
1
- "use client";
2
-
3
- /**
4
- * Top-bar visibility control for pages, posts and products.
5
- *
6
- * This is the only place in the CMS that can change what the public sees. It is
7
- * deliberately NOT part of the content form: editing settings autosaves into the
8
- * Live Draft, while publishing writes straight to the row. Two decisions, two
9
- * controls — see `app/actions/visibilityActions.ts`.
10
- *
11
- * The pill is read-only on purpose. A <select> implies every option is equivalent
12
- * and instantly applied, which is exactly the behaviour this replaces; naming the
13
- * transitions as verbs in a menu lets each one carry its own confirmation.
14
- */
15
-
16
- import * as React from "react";
17
- import { useRouter } from "next/navigation";
18
- import { toast } from "react-hot-toast";
19
- import {
20
- Button,
21
- Checkbox,
22
- Dialog,
23
- DialogContent,
24
- DialogDescription,
25
- DialogFooter,
26
- DialogHeader,
27
- DialogTitle,
28
- DropdownMenu,
29
- DropdownMenuContent,
30
- DropdownMenuItem,
31
- DropdownMenuLabel,
32
- DropdownMenuSeparator,
33
- DropdownMenuTrigger,
34
- Input,
35
- Label,
36
- } from "@nextblock-cms/ui";
37
- import {
38
- LIVE_STATUS,
39
- resolveVisibilityState,
40
- type PublishableType,
41
- type VisibilityState,
42
- } from "@nextblock-cms/utils";
43
- import {
44
- CalendarClock,
45
- ChevronDown,
46
- Link2,
47
- Loader2,
48
- Archive,
49
- EyeOff,
50
- Globe,
51
- } from "lucide-react";
52
- import {
53
- getSiblingVisibility,
54
- setContentVisibility,
55
- type SiblingVisibility,
56
- type VisibilityIntent,
57
- } from "../../actions/visibilityActions";
58
- import { publishVisualEditingDraft, publishVisualEditingProductDraft } from "../../actions/visualEditingActions";
59
-
60
- interface LanguageOption {
61
- id: number;
62
- name: string;
63
- code: string;
64
- }
65
-
66
- export interface VisibilityControlProps {
67
- type: PublishableType;
68
- id: number | string;
69
- /** Live row status — never the draft overlay. */
70
- status: string;
71
- /** Live row published_at; a future value means "scheduled". */
72
- publishedAt: string | null;
73
- /** Root-relative public URL, e.g. "/about" or "/article/hello". */
74
- publicPath: string;
75
- /** Display name of the language this row is written in. */
76
- languageName?: string;
77
- translationGroupId?: string | null;
78
- languages?: LanguageOption[];
79
- /** True when unpublished content edits exist in the Live Draft. */
80
- hasDraft?: boolean;
81
- /**
82
- * Why this content cannot go public yet, if it can't — e.g. a product whose
83
- * payment provider isn't configured. Blocks publish and schedule, and is shown
84
- * verbatim, so write it as an explanation the editor can act on.
85
- */
86
- publishBlockedReason?: string | null;
87
- }
88
-
89
- const STATE_LABEL: Record<VisibilityState, string> = {
90
- draft: "Draft",
91
- scheduled: "Scheduled",
92
- published: "Published",
93
- archived: "Archived",
94
- };
95
-
96
- const STATE_STYLE: Record<VisibilityState, string> = {
97
- draft:
98
- "border-border bg-muted text-muted-foreground",
99
- scheduled:
100
- "border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",
101
- published:
102
- "border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400",
103
- archived:
104
- "border-dashed border-border bg-transparent text-muted-foreground",
105
- };
106
-
107
- const DOT_STYLE: Record<VisibilityState, string> = {
108
- draft: "bg-muted-foreground/70",
109
- scheduled: "bg-amber-500",
110
- published: "bg-emerald-500",
111
- archived: "bg-muted-foreground/50",
112
- };
113
-
114
- /** `datetime-local` wants "YYYY-MM-DDTHH:mm" in LOCAL time, not an ISO string. */
115
- function toDateTimeLocal(value: string | null): string {
116
- if (!value) return "";
117
- const date = new Date(value);
118
- if (Number.isNaN(date.getTime())) return "";
119
- const pad = (n: number) => String(n).padStart(2, "0");
120
- return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(
121
- date.getHours()
122
- )}:${pad(date.getMinutes())}`;
123
- }
124
-
125
- function defaultScheduleValue(): string {
126
- const soon = new Date();
127
- soon.setDate(soon.getDate() + 1);
128
- soon.setMinutes(0, 0, 0);
129
- return toDateTimeLocal(soon.toISOString());
130
- }
131
-
132
- export default function VisibilityControl({
133
- type,
134
- id,
135
- status,
136
- publishedAt,
137
- publicPath,
138
- languageName,
139
- translationGroupId,
140
- languages = [],
141
- hasDraft = false,
142
- publishBlockedReason = null,
143
- }: VisibilityControlProps) {
144
- const router = useRouter();
145
- const liveStatus = LIVE_STATUS[type];
146
- const state = resolveVisibilityState({ status, publishedAt, liveStatus });
147
-
148
- const [dialog, setDialog] = React.useState<null | "publish" | "schedule" | "unpublish" | "archive">(null);
149
- const [isBusy, setIsBusy] = React.useState(false);
150
- const [error, setError] = React.useState<string | null>(null);
151
- const [alsoPublishDraft, setAlsoPublishDraft] = React.useState(true);
152
- const [scheduleValue, setScheduleValue] = React.useState(() => toDateTimeLocal(publishedAt) || defaultScheduleValue());
153
- const [siblings, setSiblings] = React.useState<SiblingVisibility[] | null>(null);
154
-
155
- // The schedule date is formatted in the viewer's timezone, which the server
156
- // doesn't know — render it only after mount so the two never disagree.
157
- const [mounted, setMounted] = React.useState(false);
158
- React.useEffect(() => setMounted(true), []);
159
-
160
- const scheduleLabel = React.useMemo(() => {
161
- if (!mounted || !publishedAt) return null;
162
- const date = new Date(publishedAt);
163
- if (Number.isNaN(date.getTime())) return null;
164
- return new Intl.DateTimeFormat(undefined, {
165
- month: "short",
166
- day: "numeric",
167
- hour: "numeric",
168
- minute: "2-digit",
169
- timeZoneName: "short",
170
- }).format(date);
171
- }, [mounted, publishedAt]);
172
-
173
- const label = state === "scheduled" && scheduleLabel ? `Goes live ${scheduleLabel}` : STATE_LABEL[state];
174
-
175
- const languageNameById = React.useMemo(
176
- () => new Map(languages.map((language) => [language.id, `${language.name} (${language.code.toUpperCase()})`])),
177
- [languages]
178
- );
179
-
180
- const openPublishDialog = React.useCallback(() => {
181
- setError(publishBlockedReason);
182
- setAlsoPublishDraft(true);
183
- setSiblings(null);
184
- setDialog("publish");
185
-
186
- if (translationGroupId) {
187
- void getSiblingVisibility(type, translationGroupId, id).then(setSiblings);
188
- }
189
- }, [id, publishBlockedReason, translationGroupId, type]);
190
-
191
- const run = async (intent: VisibilityIntent, opts?: { publishDraft?: boolean }) => {
192
- setIsBusy(true);
193
- setError(null);
194
- try {
195
- const result = await setContentVisibility(type, id, intent);
196
- if (result.error) {
197
- setError(result.error);
198
- return;
199
- }
200
-
201
- // Publishing the row and publishing pending edits are separate operations;
202
- // the dialog offers to do both so a never-live page doesn't go public
203
- // showing content the editor has already replaced.
204
- if (opts?.publishDraft && hasDraft) {
205
- const draftResult =
206
- type === "product"
207
- ? await publishVisualEditingProductDraft(String(id))
208
- : await publishVisualEditingDraft(type, Number(id));
209
-
210
- if (draftResult && "error" in draftResult && draftResult.error) {
211
- toast.error(`Visibility updated, but the edits didn't publish: ${draftResult.error}`);
212
- setDialog(null);
213
- router.refresh();
214
- return;
215
- }
216
-
217
- // Partial success: the edits went live but the revision didn't record.
218
- if (draftResult && "success" in draftResult && draftResult.warning) {
219
- toast.error(draftResult.warning, { duration: 8000 });
220
- }
221
- }
222
-
223
- toast.success(
224
- intent.action === "publish"
225
- ? "Published."
226
- : intent.action === "schedule"
227
- ? "Scheduled."
228
- : intent.action === "unpublish"
229
- ? "Unpublished."
230
- : "Archived."
231
- );
232
- setDialog(null);
233
- router.refresh();
234
- } catch (err) {
235
- setError(err instanceof Error ? err.message : "Something went wrong.");
236
- } finally {
237
- setIsBusy(false);
238
- }
239
- };
240
-
241
- const copyPublicUrl = async () => {
242
- const url = typeof window === "undefined" ? publicPath : new URL(publicPath, window.location.origin).toString();
243
- try {
244
- await navigator.clipboard.writeText(url);
245
- toast.success("Public URL copied.");
246
- } catch {
247
- toast.error("Couldn't copy the URL.");
248
- }
249
- };
250
-
251
- const typeLabel = type === "product" ? "product" : type;
252
- const busySpinner = <Loader2 className="mr-2 h-4 w-4 animate-spin" />;
253
-
254
- return (
255
- <div className="flex items-center gap-2">
256
- <span
257
- className={`inline-flex items-center gap-2 whitespace-nowrap rounded-full border px-2.5 py-1 text-xs font-semibold ${STATE_STYLE[state]}`}
258
- title={
259
- state === "published"
260
- ? `Live at ${publicPath}`
261
- : state === "scheduled"
262
- ? "Not public yet goes live automatically"
263
- : "Not visible to the public"
264
- }
265
- >
266
- <span className={`h-1.5 w-1.5 rounded-full ${DOT_STYLE[state]}`} aria-hidden="true" />
267
- {label}
268
- </span>
269
-
270
- {hasDraft && (
271
- <span className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-full border border-dashed border-amber-500/50 px-2.5 py-1 text-xs font-medium text-amber-700 dark:text-amber-300">
272
- <span className="h-1.5 w-1.5 rounded-full bg-amber-500" aria-hidden="true" />
273
- Unpublished edits
274
- </span>
275
- )}
276
-
277
- <div className="flex items-center">
278
- {state !== "published" && (
279
- <Button
280
- size="sm"
281
- className="rounded-r-none"
282
- onClick={openPublishDialog}
283
- disabled={isBusy}
284
- >
285
- <Globe className="mr-2 h-4 w-4" />
286
- {state === "scheduled" ? "Publish now" : "Publish…"}
287
- </Button>
288
- )}
289
- <DropdownMenu>
290
- <DropdownMenuTrigger asChild>
291
- <Button
292
- size="sm"
293
- variant={state === "published" ? "outline" : "default"}
294
- className={state === "published" ? "" : "-ml-px rounded-l-none px-2"}
295
- aria-label="Visibility options"
296
- disabled={isBusy}
297
- >
298
- {state === "published" && <span className="mr-1">Visibility</span>}
299
- <ChevronDown className="h-4 w-4" />
300
- </Button>
301
- </DropdownMenuTrigger>
302
- <DropdownMenuContent align="end" className="w-64">
303
- <DropdownMenuLabel>Visibility</DropdownMenuLabel>
304
- <DropdownMenuSeparator />
305
- <DropdownMenuItem
306
- onSelect={() => {
307
- setError(publishBlockedReason);
308
- setScheduleValue(toDateTimeLocal(publishedAt) || defaultScheduleValue());
309
- setDialog("schedule");
310
- }}
311
- >
312
- <CalendarClock className="mr-2 h-4 w-4" />
313
- {state === "scheduled" ? "Reschedule…" : "Schedule…"}
314
- </DropdownMenuItem>
315
- <DropdownMenuItem onSelect={() => void copyPublicUrl()}>
316
- <Link2 className="mr-2 h-4 w-4" />
317
- Copy public URL
318
- </DropdownMenuItem>
319
- {(state === "published" || state === "scheduled") && (
320
- <>
321
- <DropdownMenuSeparator />
322
- <DropdownMenuItem
323
- className="text-destructive focus:text-destructive"
324
- onSelect={() => {
325
- setError(null);
326
- setDialog("unpublish");
327
- }}
328
- >
329
- <EyeOff className="mr-2 h-4 w-4" />
330
- Unpublish
331
- </DropdownMenuItem>
332
- </>
333
- )}
334
- {state !== "archived" && (
335
- <DropdownMenuItem
336
- className="text-destructive focus:text-destructive"
337
- onSelect={() => {
338
- setError(null);
339
- setDialog("archive");
340
- }}
341
- >
342
- <Archive className="mr-2 h-4 w-4" />
343
- Archive
344
- </DropdownMenuItem>
345
- )}
346
- </DropdownMenuContent>
347
- </DropdownMenu>
348
- </div>
349
-
350
- {/* ---- Publish ---- */}
351
- <Dialog open={dialog === "publish"} onOpenChange={(open) => !open && setDialog(null)}>
352
- <DialogContent>
353
- <DialogHeader>
354
- <DialogTitle>Make this {typeLabel} public?</DialogTitle>
355
- <DialogDescription>
356
- Anyone with the link will be able to see it, and search engines can index it.
357
- </DialogDescription>
358
- </DialogHeader>
359
-
360
- <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 rounded-md border bg-muted/40 p-3 text-sm">
361
- <dt className="text-xs uppercase tracking-wide text-muted-foreground">URL</dt>
362
- <dd className="font-mono text-xs break-all">{publicPath}</dd>
363
- {languageName && (
364
- <>
365
- <dt className="text-xs uppercase tracking-wide text-muted-foreground">Language</dt>
366
- <dd>{languageName}</dd>
367
- </>
368
- )}
369
- <dt className="text-xs uppercase tracking-wide text-muted-foreground">Goes live</dt>
370
- <dd>Immediately</dd>
371
- </dl>
372
-
373
- {hasDraft && (
374
- <label className="flex items-start gap-3 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-sm">
375
- <Checkbox
376
- checked={alsoPublishDraft}
377
- onCheckedChange={(checked) => setAlsoPublishDraft(checked === true)}
378
- className="mt-0.5"
379
- />
380
- <span>
381
- Publish your unpublished edits at the same time — otherwise the older live version
382
- is what goes public.
383
- </span>
384
- </label>
385
- )}
386
-
387
- {siblings && siblings.some((sibling) => sibling.state !== "published") && (
388
- <div className="space-y-1.5 text-sm text-muted-foreground">
389
- {siblings
390
- .filter((sibling) => sibling.state !== "published")
391
- .map((sibling) => (
392
- <p key={String(sibling.id)}>
393
- <span className="font-semibold text-amber-600 dark:text-amber-400">!</span>{" "}
394
- The {languageNameById.get(sibling.languageId) ?? "other language"} version is
395
- still {STATE_LABEL[sibling.state].toLowerCase()}.
396
- </p>
397
- ))}
398
- </div>
399
- )}
400
-
401
- {error && <p className="text-sm text-destructive">{error}</p>}
402
-
403
- <DialogFooter className="mt-2 gap-2">
404
- <Button variant="outline" onClick={() => setDialog(null)} disabled={isBusy}>
405
- Cancel
406
- </Button>
407
- <Button
408
- onClick={() => void run({ action: "publish" }, { publishDraft: alsoPublishDraft })}
409
- disabled={isBusy || Boolean(publishBlockedReason)}
410
- >
411
- {isBusy && busySpinner}
412
- Publish {typeLabel}
413
- </Button>
414
- </DialogFooter>
415
- </DialogContent>
416
- </Dialog>
417
-
418
- {/* ---- Schedule ---- */}
419
- <Dialog open={dialog === "schedule"} onOpenChange={(open) => !open && setDialog(null)}>
420
- <DialogContent>
421
- <DialogHeader>
422
- <DialogTitle>Schedule this {typeLabel}</DialogTitle>
423
- <DialogDescription>
424
- It stays private until the moment you pick, then goes live on its own. Times are in
425
- your own timezone.
426
- </DialogDescription>
427
- </DialogHeader>
428
-
429
- <div className="space-y-2">
430
- <Label htmlFor="visibility-schedule">Go live on</Label>
431
- <Input
432
- id="visibility-schedule"
433
- type="datetime-local"
434
- value={scheduleValue}
435
- onChange={(event) => setScheduleValue(event.target.value)}
436
- />
437
- </div>
438
-
439
- {error && <p className="text-sm text-destructive">{error}</p>}
440
-
441
- <DialogFooter className="mt-2 gap-2">
442
- <Button variant="outline" onClick={() => setDialog(null)} disabled={isBusy}>
443
- Cancel
444
- </Button>
445
- <Button
446
- onClick={() => {
447
- if (publishBlockedReason) {
448
- setError(publishBlockedReason);
449
- return;
450
- }
451
- const local = new Date(scheduleValue);
452
- if (Number.isNaN(local.getTime())) {
453
- setError("That isn't a valid date and time.");
454
- return;
455
- }
456
- void run({ action: "schedule", publishedAt: local.toISOString() });
457
- }}
458
- disabled={isBusy || !scheduleValue || Boolean(publishBlockedReason)}
459
- >
460
- {isBusy && busySpinner}
461
- Schedule
462
- </Button>
463
- </DialogFooter>
464
- </DialogContent>
465
- </Dialog>
466
-
467
- {/* ---- Unpublish ---- */}
468
- <Dialog open={dialog === "unpublish"} onOpenChange={(open) => !open && setDialog(null)}>
469
- <DialogContent>
470
- <DialogHeader>
471
- <DialogTitle>Take this {typeLabel} off the live site?</DialogTitle>
472
- <DialogDescription>
473
- Visitors will get a 404 at{" "}
474
- <span className="font-mono text-xs">{publicPath}</span>. Your content and any
475
- unpublished edits are kept you can publish it again at any time. Check your
476
- navigation menus for links pointing here.
477
- </DialogDescription>
478
- </DialogHeader>
479
-
480
- {error && <p className="text-sm text-destructive">{error}</p>}
481
-
482
- <DialogFooter className="mt-2 gap-2">
483
- <Button variant="outline" onClick={() => setDialog(null)} disabled={isBusy}>
484
- Cancel
485
- </Button>
486
- <Button
487
- variant="destructive"
488
- onClick={() => void run({ action: "unpublish" })}
489
- disabled={isBusy}
490
- >
491
- {isBusy && busySpinner}
492
- Unpublish
493
- </Button>
494
- </DialogFooter>
495
- </DialogContent>
496
- </Dialog>
497
-
498
- {/* ---- Archive ---- */}
499
- <Dialog open={dialog === "archive"} onOpenChange={(open) => !open && setDialog(null)}>
500
- <DialogContent>
501
- <DialogHeader>
502
- <DialogTitle>Archive this {typeLabel}?</DialogTitle>
503
- <DialogDescription>
504
- It comes off the live site and drops out of the default {typeLabel} list. Nothing is
505
- deleted, and you can publish it again later.
506
- </DialogDescription>
507
- </DialogHeader>
508
-
509
- {error && <p className="text-sm text-destructive">{error}</p>}
510
-
511
- <DialogFooter className="mt-2 gap-2">
512
- <Button variant="outline" onClick={() => setDialog(null)} disabled={isBusy}>
513
- Cancel
514
- </Button>
515
- <Button
516
- variant="destructive"
517
- onClick={() => void run({ action: "archive" })}
518
- disabled={isBusy}
519
- >
520
- {isBusy && busySpinner}
521
- Archive
522
- </Button>
523
- </DialogFooter>
524
- </DialogContent>
525
- </Dialog>
526
- </div>
527
- );
528
- }
1
+ "use client";
2
+
3
+ /**
4
+ * Top-bar visibility control for pages, posts and products.
5
+ *
6
+ * This is the only place in the CMS that can change what the public sees. It is
7
+ * deliberately NOT part of the content form: editing settings autosaves into the
8
+ * Live Draft, while publishing writes straight to the row. Two decisions, two
9
+ * controls — see `app/actions/visibilityActions.ts`.
10
+ *
11
+ * The pill is read-only on purpose. A <select> implies every option is equivalent
12
+ * and instantly applied, which is exactly the behaviour this replaces; naming the
13
+ * transitions as verbs in a menu lets each one carry its own confirmation.
14
+ */
15
+
16
+ import * as React from "react";
17
+ import { useRouter } from "next/navigation";
18
+ import { toast } from "react-hot-toast";
19
+ import {
20
+ Button,
21
+ Checkbox,
22
+ Dialog,
23
+ DialogContent,
24
+ DialogDescription,
25
+ DialogFooter,
26
+ DialogHeader,
27
+ DialogTitle,
28
+ DropdownMenu,
29
+ DropdownMenuContent,
30
+ DropdownMenuItem,
31
+ DropdownMenuLabel,
32
+ DropdownMenuSeparator,
33
+ DropdownMenuTrigger,
34
+ Input,
35
+ Label,
36
+ } from "@nextblock-cms/ui";
37
+ import {
38
+ LIVE_STATUS,
39
+ resolveVisibilityState,
40
+ type PublishableType,
41
+ type VisibilityState,
42
+ } from "@nextblock-cms/utils";
43
+ import {
44
+ AlertTriangle,
45
+ CalendarClock,
46
+ ChevronDown,
47
+ Link2,
48
+ Loader2,
49
+ Archive,
50
+ EyeOff,
51
+ Globe,
52
+ } from "lucide-react";
53
+ import {
54
+ getSiblingVisibility,
55
+ setContentVisibility,
56
+ type SiblingVisibility,
57
+ type VisibilityIntent,
58
+ } from "../../actions/visibilityActions";
59
+ import { publishVisualEditingDraft, publishVisualEditingProductDraft } from "../../actions/visualEditingActions";
60
+
61
+ interface LanguageOption {
62
+ id: number;
63
+ name: string;
64
+ code: string;
65
+ }
66
+
67
+ export interface VisibilityControlProps {
68
+ type: PublishableType;
69
+ id: number | string;
70
+ /** Live row status — never the draft overlay. */
71
+ status: string;
72
+ /** Live row published_at; a future value means "scheduled". */
73
+ publishedAt: string | null;
74
+ /** Root-relative public URL, e.g. "/about" or "/article/hello". */
75
+ publicPath: string;
76
+ /** Display name of the language this row is written in. */
77
+ languageName?: string;
78
+ translationGroupId?: string | null;
79
+ languages?: LanguageOption[];
80
+ /** True when unpublished content edits exist in the Live Draft. */
81
+ hasDraft?: boolean;
82
+ /**
83
+ * A caution to show before this content goes public e.g. a product whose payment
84
+ * provider isn't configured, which publishes fine but cannot be bought yet. Shown
85
+ * verbatim as an amber callout in the publish and schedule dialogs; it never blocks
86
+ * the action, so write it as a consequence the editor can weigh, not a refusal.
87
+ */
88
+ publishWarning?: string | null;
89
+ }
90
+
91
+ const STATE_LABEL: Record<VisibilityState, string> = {
92
+ draft: "Draft",
93
+ scheduled: "Scheduled",
94
+ published: "Published",
95
+ archived: "Archived",
96
+ };
97
+
98
+ const STATE_STYLE: Record<VisibilityState, string> = {
99
+ draft:
100
+ "border-border bg-muted text-muted-foreground",
101
+ scheduled:
102
+ "border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",
103
+ published:
104
+ "border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400",
105
+ archived:
106
+ "border-dashed border-border bg-transparent text-muted-foreground",
107
+ };
108
+
109
+ const DOT_STYLE: Record<VisibilityState, string> = {
110
+ draft: "bg-muted-foreground/70",
111
+ scheduled: "bg-amber-500",
112
+ published: "bg-emerald-500",
113
+ archived: "bg-muted-foreground/50",
114
+ };
115
+
116
+ /** `datetime-local` wants "YYYY-MM-DDTHH:mm" in LOCAL time, not an ISO string. */
117
+ function toDateTimeLocal(value: string | null): string {
118
+ if (!value) return "";
119
+ const date = new Date(value);
120
+ if (Number.isNaN(date.getTime())) return "";
121
+ const pad = (n: number) => String(n).padStart(2, "0");
122
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(
123
+ date.getHours()
124
+ )}:${pad(date.getMinutes())}`;
125
+ }
126
+
127
+ function defaultScheduleValue(): string {
128
+ const soon = new Date();
129
+ soon.setDate(soon.getDate() + 1);
130
+ soon.setMinutes(0, 0, 0);
131
+ return toDateTimeLocal(soon.toISOString());
132
+ }
133
+
134
+ export default function VisibilityControl({
135
+ type,
136
+ id,
137
+ status,
138
+ publishedAt,
139
+ publicPath,
140
+ languageName,
141
+ translationGroupId,
142
+ languages = [],
143
+ hasDraft = false,
144
+ publishWarning = null,
145
+ }: VisibilityControlProps) {
146
+ const router = useRouter();
147
+ const liveStatus = LIVE_STATUS[type];
148
+ const state = resolveVisibilityState({ status, publishedAt, liveStatus });
149
+
150
+ const [dialog, setDialog] = React.useState<null | "publish" | "schedule" | "unpublish" | "archive">(null);
151
+ const [isBusy, setIsBusy] = React.useState(false);
152
+ const [error, setError] = React.useState<string | null>(null);
153
+ const [alsoPublishDraft, setAlsoPublishDraft] = React.useState(true);
154
+ const [scheduleValue, setScheduleValue] = React.useState(() => toDateTimeLocal(publishedAt) || defaultScheduleValue());
155
+ const [siblings, setSiblings] = React.useState<SiblingVisibility[] | null>(null);
156
+
157
+ // The schedule date is formatted in the viewer's timezone, which the server
158
+ // doesn't know — render it only after mount so the two never disagree.
159
+ const [mounted, setMounted] = React.useState(false);
160
+ React.useEffect(() => setMounted(true), []);
161
+
162
+ const scheduleLabel = React.useMemo(() => {
163
+ if (!mounted || !publishedAt) return null;
164
+ const date = new Date(publishedAt);
165
+ if (Number.isNaN(date.getTime())) return null;
166
+ return new Intl.DateTimeFormat(undefined, {
167
+ month: "short",
168
+ day: "numeric",
169
+ hour: "numeric",
170
+ minute: "2-digit",
171
+ timeZoneName: "short",
172
+ }).format(date);
173
+ }, [mounted, publishedAt]);
174
+
175
+ const label = state === "scheduled" && scheduleLabel ? `Goes live ${scheduleLabel}` : STATE_LABEL[state];
176
+
177
+ const languageNameById = React.useMemo(
178
+ () => new Map(languages.map((language) => [language.id, `${language.name} (${language.code.toUpperCase()})`])),
179
+ [languages]
180
+ );
181
+
182
+ const openPublishDialog = React.useCallback(() => {
183
+ // A warning is not an error: seeding it into `error` renders it destructive-red and
184
+ // `run()` clears it on the next attempt. It belongs in the dialog body instead.
185
+ setError(null);
186
+ setAlsoPublishDraft(true);
187
+ setSiblings(null);
188
+ setDialog("publish");
189
+
190
+ if (translationGroupId) {
191
+ void getSiblingVisibility(type, translationGroupId, id).then(setSiblings);
192
+ }
193
+ }, [id, translationGroupId, type]);
194
+
195
+ const run = async (intent: VisibilityIntent, opts?: { publishDraft?: boolean }) => {
196
+ setIsBusy(true);
197
+ setError(null);
198
+ try {
199
+ const result = await setContentVisibility(type, id, intent);
200
+ if (result.error) {
201
+ setError(result.error);
202
+ return;
203
+ }
204
+
205
+ // Publishing the row and publishing pending edits are separate operations;
206
+ // the dialog offers to do both so a never-live page doesn't go public
207
+ // showing content the editor has already replaced.
208
+ if (opts?.publishDraft && hasDraft) {
209
+ const draftResult =
210
+ type === "product"
211
+ ? await publishVisualEditingProductDraft(String(id))
212
+ : await publishVisualEditingDraft(type, Number(id));
213
+
214
+ if (draftResult && "error" in draftResult && draftResult.error) {
215
+ toast.error(`Visibility updated, but the edits didn't publish: ${draftResult.error}`);
216
+ setDialog(null);
217
+ router.refresh();
218
+ return;
219
+ }
220
+
221
+ // Partial success: the edits went live but the revision didn't record.
222
+ if (draftResult && "success" in draftResult && draftResult.warning) {
223
+ toast.error(draftResult.warning, { duration: 8000 });
224
+ }
225
+ }
226
+
227
+ toast.success(
228
+ intent.action === "publish"
229
+ ? "Published."
230
+ : intent.action === "schedule"
231
+ ? "Scheduled."
232
+ : intent.action === "unpublish"
233
+ ? "Unpublished."
234
+ : "Archived."
235
+ );
236
+ setDialog(null);
237
+ router.refresh();
238
+ } catch (err) {
239
+ setError(err instanceof Error ? err.message : "Something went wrong.");
240
+ } finally {
241
+ setIsBusy(false);
242
+ }
243
+ };
244
+
245
+ const copyPublicUrl = async () => {
246
+ const url = typeof window === "undefined" ? publicPath : new URL(publicPath, window.location.origin).toString();
247
+ try {
248
+ await navigator.clipboard.writeText(url);
249
+ toast.success("Public URL copied.");
250
+ } catch {
251
+ toast.error("Couldn't copy the URL.");
252
+ }
253
+ };
254
+
255
+ const typeLabel = type === "product" ? "product" : type;
256
+ const busySpinner = <Loader2 className="mr-2 h-4 w-4 animate-spin" />;
257
+
258
+ // Amber, not destructive: publishing is still allowed. Same treatment as the
259
+ // "publish your unpublished edits too" opt-in below, which is the other caution
260
+ // shown in this dialog.
261
+ const publishWarningCallout = (
262
+ <div className="flex items-start gap-3 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-sm">
263
+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400" />
264
+ <span>{publishWarning}</span>
265
+ </div>
266
+ );
267
+
268
+ return (
269
+ <div className="flex items-center gap-2">
270
+ <span
271
+ className={`inline-flex items-center gap-2 whitespace-nowrap rounded-full border px-2.5 py-1 text-xs font-semibold ${STATE_STYLE[state]}`}
272
+ title={
273
+ state === "published"
274
+ ? `Live at ${publicPath}`
275
+ : state === "scheduled"
276
+ ? "Not public yet — goes live automatically"
277
+ : "Not visible to the public"
278
+ }
279
+ >
280
+ <span className={`h-1.5 w-1.5 rounded-full ${DOT_STYLE[state]}`} aria-hidden="true" />
281
+ {label}
282
+ </span>
283
+
284
+ {hasDraft && (
285
+ <span className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-full border border-dashed border-amber-500/50 px-2.5 py-1 text-xs font-medium text-amber-700 dark:text-amber-300">
286
+ <span className="h-1.5 w-1.5 rounded-full bg-amber-500" aria-hidden="true" />
287
+ Unpublished edits
288
+ </span>
289
+ )}
290
+
291
+ <div className="flex items-center">
292
+ {state !== "published" && (
293
+ <Button
294
+ size="sm"
295
+ className="rounded-r-none"
296
+ onClick={openPublishDialog}
297
+ disabled={isBusy}
298
+ >
299
+ <Globe className="mr-2 h-4 w-4" />
300
+ {state === "scheduled" ? "Publish now" : "Publish…"}
301
+ </Button>
302
+ )}
303
+ <DropdownMenu>
304
+ <DropdownMenuTrigger asChild>
305
+ <Button
306
+ size="sm"
307
+ variant={state === "published" ? "outline" : "default"}
308
+ className={state === "published" ? "" : "-ml-px rounded-l-none px-2"}
309
+ aria-label="Visibility options"
310
+ disabled={isBusy}
311
+ >
312
+ {state === "published" && <span className="mr-1">Visibility</span>}
313
+ <ChevronDown className="h-4 w-4" />
314
+ </Button>
315
+ </DropdownMenuTrigger>
316
+ <DropdownMenuContent align="end" className="w-64">
317
+ <DropdownMenuLabel>Visibility</DropdownMenuLabel>
318
+ <DropdownMenuSeparator />
319
+ <DropdownMenuItem
320
+ onSelect={() => {
321
+ setError(null);
322
+ setScheduleValue(toDateTimeLocal(publishedAt) || defaultScheduleValue());
323
+ setDialog("schedule");
324
+ }}
325
+ >
326
+ <CalendarClock className="mr-2 h-4 w-4" />
327
+ {state === "scheduled" ? "Reschedule…" : "Schedule…"}
328
+ </DropdownMenuItem>
329
+ <DropdownMenuItem onSelect={() => void copyPublicUrl()}>
330
+ <Link2 className="mr-2 h-4 w-4" />
331
+ Copy public URL
332
+ </DropdownMenuItem>
333
+ {(state === "published" || state === "scheduled") && (
334
+ <>
335
+ <DropdownMenuSeparator />
336
+ <DropdownMenuItem
337
+ className="text-destructive focus:text-destructive"
338
+ onSelect={() => {
339
+ setError(null);
340
+ setDialog("unpublish");
341
+ }}
342
+ >
343
+ <EyeOff className="mr-2 h-4 w-4" />
344
+ Unpublish
345
+ </DropdownMenuItem>
346
+ </>
347
+ )}
348
+ {state !== "archived" && (
349
+ <DropdownMenuItem
350
+ className="text-destructive focus:text-destructive"
351
+ onSelect={() => {
352
+ setError(null);
353
+ setDialog("archive");
354
+ }}
355
+ >
356
+ <Archive className="mr-2 h-4 w-4" />
357
+ Archive
358
+ </DropdownMenuItem>
359
+ )}
360
+ </DropdownMenuContent>
361
+ </DropdownMenu>
362
+ </div>
363
+
364
+ {/* ---- Publish ---- */}
365
+ <Dialog open={dialog === "publish"} onOpenChange={(open) => !open && setDialog(null)}>
366
+ <DialogContent>
367
+ <DialogHeader>
368
+ <DialogTitle>Make this {typeLabel} public?</DialogTitle>
369
+ <DialogDescription>
370
+ Anyone with the link will be able to see it, and search engines can index it.
371
+ </DialogDescription>
372
+ </DialogHeader>
373
+
374
+ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 rounded-md border bg-muted/40 p-3 text-sm">
375
+ <dt className="text-xs uppercase tracking-wide text-muted-foreground">URL</dt>
376
+ <dd className="font-mono text-xs break-all">{publicPath}</dd>
377
+ {languageName && (
378
+ <>
379
+ <dt className="text-xs uppercase tracking-wide text-muted-foreground">Language</dt>
380
+ <dd>{languageName}</dd>
381
+ </>
382
+ )}
383
+ <dt className="text-xs uppercase tracking-wide text-muted-foreground">Goes live</dt>
384
+ <dd>Immediately</dd>
385
+ </dl>
386
+
387
+ {hasDraft && (
388
+ <label className="flex items-start gap-3 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-sm">
389
+ <Checkbox
390
+ checked={alsoPublishDraft}
391
+ onCheckedChange={(checked) => setAlsoPublishDraft(checked === true)}
392
+ className="mt-0.5"
393
+ />
394
+ <span>
395
+ Publish your unpublished edits at the same time — otherwise the older live version
396
+ is what goes public.
397
+ </span>
398
+ </label>
399
+ )}
400
+
401
+ {siblings && siblings.some((sibling) => sibling.state !== "published") && (
402
+ <div className="space-y-1.5 text-sm text-muted-foreground">
403
+ {siblings
404
+ .filter((sibling) => sibling.state !== "published")
405
+ .map((sibling) => (
406
+ <p key={String(sibling.id)}>
407
+ <span className="font-semibold text-amber-600 dark:text-amber-400">!</span>{" "}
408
+ The {languageNameById.get(sibling.languageId) ?? "other language"} version is
409
+ still {STATE_LABEL[sibling.state].toLowerCase()}.
410
+ </p>
411
+ ))}
412
+ </div>
413
+ )}
414
+
415
+ {publishWarning && publishWarningCallout}
416
+
417
+ {error && <p className="text-sm text-destructive">{error}</p>}
418
+
419
+ <DialogFooter className="mt-2 gap-2">
420
+ <Button variant="outline" onClick={() => setDialog(null)} disabled={isBusy}>
421
+ Cancel
422
+ </Button>
423
+ <Button
424
+ onClick={() => void run({ action: "publish" }, { publishDraft: alsoPublishDraft })}
425
+ disabled={isBusy}
426
+ >
427
+ {isBusy && busySpinner}
428
+ {publishWarning ? `Publish anyway` : `Publish ${typeLabel}`}
429
+ </Button>
430
+ </DialogFooter>
431
+ </DialogContent>
432
+ </Dialog>
433
+
434
+ {/* ---- Schedule ---- */}
435
+ <Dialog open={dialog === "schedule"} onOpenChange={(open) => !open && setDialog(null)}>
436
+ <DialogContent>
437
+ <DialogHeader>
438
+ <DialogTitle>Schedule this {typeLabel}</DialogTitle>
439
+ <DialogDescription>
440
+ It stays private until the moment you pick, then goes live on its own. Times are in
441
+ your own timezone.
442
+ </DialogDescription>
443
+ </DialogHeader>
444
+
445
+ <div className="space-y-2">
446
+ <Label htmlFor="visibility-schedule">Go live on</Label>
447
+ <Input
448
+ id="visibility-schedule"
449
+ type="datetime-local"
450
+ value={scheduleValue}
451
+ onChange={(event) => setScheduleValue(event.target.value)}
452
+ />
453
+ </div>
454
+
455
+ {publishWarning && publishWarningCallout}
456
+
457
+ {error && <p className="text-sm text-destructive">{error}</p>}
458
+
459
+ <DialogFooter className="mt-2 gap-2">
460
+ <Button variant="outline" onClick={() => setDialog(null)} disabled={isBusy}>
461
+ Cancel
462
+ </Button>
463
+ <Button
464
+ onClick={() => {
465
+ const local = new Date(scheduleValue);
466
+ if (Number.isNaN(local.getTime())) {
467
+ setError("That isn't a valid date and time.");
468
+ return;
469
+ }
470
+ void run({ action: "schedule", publishedAt: local.toISOString() });
471
+ }}
472
+ disabled={isBusy || !scheduleValue}
473
+ >
474
+ {isBusy && busySpinner}
475
+ {publishWarning ? "Schedule anyway" : "Schedule"}
476
+ </Button>
477
+ </DialogFooter>
478
+ </DialogContent>
479
+ </Dialog>
480
+
481
+ {/* ---- Unpublish ---- */}
482
+ <Dialog open={dialog === "unpublish"} onOpenChange={(open) => !open && setDialog(null)}>
483
+ <DialogContent>
484
+ <DialogHeader>
485
+ <DialogTitle>Take this {typeLabel} off the live site?</DialogTitle>
486
+ <DialogDescription>
487
+ Visitors will get a 404 at{" "}
488
+ <span className="font-mono text-xs">{publicPath}</span>. Your content and any
489
+ unpublished edits are kept — you can publish it again at any time. Check your
490
+ navigation menus for links pointing here.
491
+ </DialogDescription>
492
+ </DialogHeader>
493
+
494
+ {error && <p className="text-sm text-destructive">{error}</p>}
495
+
496
+ <DialogFooter className="mt-2 gap-2">
497
+ <Button variant="outline" onClick={() => setDialog(null)} disabled={isBusy}>
498
+ Cancel
499
+ </Button>
500
+ <Button
501
+ variant="destructive"
502
+ onClick={() => void run({ action: "unpublish" })}
503
+ disabled={isBusy}
504
+ >
505
+ {isBusy && busySpinner}
506
+ Unpublish
507
+ </Button>
508
+ </DialogFooter>
509
+ </DialogContent>
510
+ </Dialog>
511
+
512
+ {/* ---- Archive ---- */}
513
+ <Dialog open={dialog === "archive"} onOpenChange={(open) => !open && setDialog(null)}>
514
+ <DialogContent>
515
+ <DialogHeader>
516
+ <DialogTitle>Archive this {typeLabel}?</DialogTitle>
517
+ <DialogDescription>
518
+ It comes off the live site and drops out of the default {typeLabel} list. Nothing is
519
+ deleted, and you can publish it again later.
520
+ </DialogDescription>
521
+ </DialogHeader>
522
+
523
+ {error && <p className="text-sm text-destructive">{error}</p>}
524
+
525
+ <DialogFooter className="mt-2 gap-2">
526
+ <Button variant="outline" onClick={() => setDialog(null)} disabled={isBusy}>
527
+ Cancel
528
+ </Button>
529
+ <Button
530
+ variant="destructive"
531
+ onClick={() => void run({ action: "archive" })}
532
+ disabled={isBusy}
533
+ >
534
+ {isBusy && busySpinner}
535
+ Archive
536
+ </Button>
537
+ </DialogFooter>
538
+ </DialogContent>
539
+ </Dialog>
540
+ </div>
541
+ );
542
+ }