@prenta/admin 1.0.0 → 1.1.0

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 (117) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/AdminRoot.d.ts.map +1 -1
  3. package/dist/AdminRoot.js +5 -56
  4. package/dist/AdminRoot.js.map +1 -1
  5. package/dist/__tests__/components/breakpoint-controls.render.test.js +4 -4
  6. package/dist/__tests__/components/breakpoint-controls.render.test.js.map +1 -1
  7. package/dist/__tests__/lib/open-public-site-tab.test.d.ts +2 -0
  8. package/dist/__tests__/lib/open-public-site-tab.test.d.ts.map +1 -0
  9. package/dist/__tests__/lib/open-public-site-tab.test.js +64 -0
  10. package/dist/__tests__/lib/open-public-site-tab.test.js.map +1 -0
  11. package/dist/__tests__/lib/view-site-chrome.test.d.ts +2 -0
  12. package/dist/__tests__/lib/view-site-chrome.test.d.ts.map +1 -0
  13. package/dist/__tests__/lib/view-site-chrome.test.js +59 -0
  14. package/dist/__tests__/lib/view-site-chrome.test.js.map +1 -0
  15. package/dist/__tests__/router/admin-routes.test.js +4 -0
  16. package/dist/__tests__/router/admin-routes.test.js.map +1 -1
  17. package/dist/__tests__/views/canvas-surface-shared.test.js +0 -16
  18. package/dist/__tests__/views/canvas-surface-shared.test.js.map +1 -1
  19. package/dist/__tests__/views/editor-top-bar.render.test.js +44 -22
  20. package/dist/__tests__/views/editor-top-bar.render.test.js.map +1 -1
  21. package/dist/__tests__/views/page-section-editor.test.js +30 -9
  22. package/dist/__tests__/views/page-section-editor.test.js.map +1 -1
  23. package/dist/__tests__/views/post-section-editor.test.js +23 -0
  24. package/dist/__tests__/views/post-section-editor.test.js.map +1 -1
  25. package/dist/components/BreakpointPicker.d.ts +3 -2
  26. package/dist/components/BreakpointPicker.d.ts.map +1 -1
  27. package/dist/components/BreakpointPicker.js +5 -3
  28. package/dist/components/BreakpointPicker.js.map +1 -1
  29. package/dist/components/CanvasEditTip.js +1 -1
  30. package/dist/components/CanvasEditTip.js.map +1 -1
  31. package/dist/lib/editor-preview.d.ts +4 -1
  32. package/dist/lib/editor-preview.d.ts.map +1 -1
  33. package/dist/lib/editor-preview.js +4 -1
  34. package/dist/lib/editor-preview.js.map +1 -1
  35. package/dist/lib/open-public-site-tab.d.ts +14 -0
  36. package/dist/lib/open-public-site-tab.d.ts.map +1 -0
  37. package/dist/lib/open-public-site-tab.js +46 -0
  38. package/dist/lib/open-public-site-tab.js.map +1 -0
  39. package/dist/lib/view-site-chrome.d.ts +16 -0
  40. package/dist/lib/view-site-chrome.d.ts.map +1 -0
  41. package/dist/lib/view-site-chrome.js +15 -0
  42. package/dist/lib/view-site-chrome.js.map +1 -0
  43. package/dist/router/admin-routes.d.ts.map +1 -1
  44. package/dist/router/admin-routes.js +0 -2
  45. package/dist/router/admin-routes.js.map +1 -1
  46. package/dist/views/page-editor/EditorCanvas.d.ts +1 -2
  47. package/dist/views/page-editor/EditorCanvas.d.ts.map +1 -1
  48. package/dist/views/page-editor/EditorCanvas.js +2 -2
  49. package/dist/views/page-editor/EditorCanvas.js.map +1 -1
  50. package/dist/views/page-editor/EditorTopBar.d.ts +13 -17
  51. package/dist/views/page-editor/EditorTopBar.d.ts.map +1 -1
  52. package/dist/views/page-editor/EditorTopBar.js +19 -21
  53. package/dist/views/page-editor/EditorTopBar.js.map +1 -1
  54. package/dist/views/page-editor/PageSectionEditor.d.ts +1 -7
  55. package/dist/views/page-editor/PageSectionEditor.d.ts.map +1 -1
  56. package/dist/views/page-editor/PageSectionEditor.js +29 -95
  57. package/dist/views/page-editor/PageSectionEditor.js.map +1 -1
  58. package/dist/views/page-editor/StructureNotice.d.ts +2 -5
  59. package/dist/views/page-editor/StructureNotice.d.ts.map +1 -1
  60. package/dist/views/page-editor/StructureNotice.js +6 -10
  61. package/dist/views/page-editor/StructureNotice.js.map +1 -1
  62. package/dist/views/post-editor/PostEditorCanvas.d.ts +1 -3
  63. package/dist/views/post-editor/PostEditorCanvas.d.ts.map +1 -1
  64. package/dist/views/post-editor/PostEditorCanvas.js +3 -3
  65. package/dist/views/post-editor/PostEditorCanvas.js.map +1 -1
  66. package/dist/views/post-editor/PostSectionEditor.d.ts +1 -15
  67. package/dist/views/post-editor/PostSectionEditor.d.ts.map +1 -1
  68. package/dist/views/post-editor/PostSectionEditor.js +30 -88
  69. package/dist/views/post-editor/PostSectionEditor.js.map +1 -1
  70. package/package.json +4 -4
  71. package/src/AdminRoot.tsx +0 -70
  72. package/src/__tests__/components/breakpoint-controls.render.test.tsx +6 -4
  73. package/src/__tests__/lib/open-public-site-tab.test.ts +74 -0
  74. package/src/__tests__/lib/view-site-chrome.test.ts +65 -0
  75. package/src/__tests__/router/admin-routes.test.ts +5 -0
  76. package/src/__tests__/views/canvas-surface-shared.test.ts +0 -19
  77. package/src/__tests__/views/editor-top-bar.render.test.tsx +85 -22
  78. package/src/__tests__/views/page-section-editor.test.tsx +42 -9
  79. package/src/__tests__/views/post-section-editor.test.tsx +35 -0
  80. package/src/components/BreakpointPicker.tsx +6 -3
  81. package/src/components/CanvasEditTip.tsx +2 -2
  82. package/src/lib/editor-preview.ts +4 -1
  83. package/src/lib/open-public-site-tab.ts +57 -0
  84. package/src/lib/view-site-chrome.ts +34 -0
  85. package/src/router/admin-routes.ts +0 -2
  86. package/src/styles/theme.css +4 -4
  87. package/src/views/page-editor/EditorCanvas.tsx +1 -6
  88. package/src/views/page-editor/EditorTopBar.tsx +81 -82
  89. package/src/views/page-editor/PageSectionEditor.tsx +77 -157
  90. package/src/views/page-editor/StructureNotice.tsx +7 -42
  91. package/src/views/post-editor/PostEditorCanvas.tsx +2 -8
  92. package/src/views/post-editor/PostSectionEditor.tsx +66 -138
  93. package/dist/__tests__/views/use-site-preview.render.test.d.ts +0 -2
  94. package/dist/__tests__/views/use-site-preview.render.test.d.ts.map +0 -1
  95. package/dist/__tests__/views/use-site-preview.render.test.js +0 -120
  96. package/dist/__tests__/views/use-site-preview.render.test.js.map +0 -1
  97. package/dist/views/page-editor/PagePreview.d.ts +0 -13
  98. package/dist/views/page-editor/PagePreview.d.ts.map +0 -1
  99. package/dist/views/page-editor/PagePreview.js +0 -46
  100. package/dist/views/page-editor/PagePreview.js.map +0 -1
  101. package/dist/views/page-editor/SitePreviewFrame.d.ts +0 -43
  102. package/dist/views/page-editor/SitePreviewFrame.d.ts.map +0 -1
  103. package/dist/views/page-editor/SitePreviewFrame.js +0 -165
  104. package/dist/views/page-editor/SitePreviewFrame.js.map +0 -1
  105. package/dist/views/page-editor/useSitePreview.d.ts +0 -47
  106. package/dist/views/page-editor/useSitePreview.d.ts.map +0 -1
  107. package/dist/views/page-editor/useSitePreview.js +0 -96
  108. package/dist/views/page-editor/useSitePreview.js.map +0 -1
  109. package/dist/views/post-editor/PostPreview.d.ts +0 -14
  110. package/dist/views/post-editor/PostPreview.d.ts.map +0 -1
  111. package/dist/views/post-editor/PostPreview.js +0 -63
  112. package/dist/views/post-editor/PostPreview.js.map +0 -1
  113. package/src/__tests__/views/use-site-preview.render.test.tsx +0 -164
  114. package/src/views/page-editor/PagePreview.tsx +0 -105
  115. package/src/views/page-editor/SitePreviewFrame.tsx +0 -250
  116. package/src/views/page-editor/useSitePreview.ts +0 -158
  117. package/src/views/post-editor/PostPreview.tsx +0 -125
@@ -1,105 +0,0 @@
1
- 'use client'
2
-
3
- import { useEffect, useState } from 'react'
4
- import { AlertTriangle, Loader2, Pencil, X } from 'lucide-react'
5
- import { fetchPageForEditor, type EditorPage } from '../../lib/page-editor-service.js'
6
- import { SectionRenderer } from './sections/index.js'
7
-
8
- interface PagePreviewProps {
9
- documentId: string
10
- onNavigate: (path: string) => void
11
- }
12
-
13
- /**
14
- * Clean, chrome-free render of a page using the SAME section renderers as
15
- * the editor canvas — so the preview reflects what will actually ship.
16
- * Only visible sections are rendered (hidden sections are omitted, exactly
17
- * as the public page would behave).
18
- */
19
- export function PagePreview({ documentId, onNavigate }: PagePreviewProps) {
20
- const [page, setPage] = useState<EditorPage | null>(null)
21
- const [loading, setLoading] = useState(true)
22
- const [error, setError] = useState<string | null>(null)
23
-
24
- useEffect(() => {
25
- let cancelled = false
26
- setLoading(true)
27
- fetchPageForEditor(documentId)
28
- .then((p) => !cancelled && setPage(p))
29
- .catch((err) => !cancelled && setError(err instanceof Error ? err.message : 'Failed to load'))
30
- .finally(() => !cancelled && setLoading(false))
31
- return () => {
32
- cancelled = true
33
- }
34
- }, [documentId])
35
-
36
- if (loading) {
37
- return (
38
- <div className="bg-background flex h-full items-center justify-center">
39
- <Loader2 className="text-muted-foreground h-6 w-6 animate-spin" aria-hidden />
40
- <span className="sr-only">Loading preview…</span>
41
- </div>
42
- )
43
- }
44
-
45
- if (error || !page) {
46
- return (
47
- <div className="bg-background flex h-full items-center justify-center p-6">
48
- <div className="border-destructive/30 bg-destructive/5 flex max-w-md items-center gap-3 rounded-lg border p-4">
49
- <AlertTriangle className="text-destructive shrink-0" size={20} aria-hidden />
50
- <p className="text-foreground text-sm font-medium">{error ?? 'Page not found.'}</p>
51
- </div>
52
- </div>
53
- )
54
- }
55
-
56
- const visible = page.sections.filter((s) => s.visible)
57
-
58
- return (
59
- <div className="flex h-full flex-col">
60
- {/* Slim preview bar — the only chrome; the page itself renders clean.
61
- This view opens in its own browser tab, so actions are tab-scoped. */}
62
- <div className="bg-card border-border flex h-12 shrink-0 items-center justify-between border-b px-4">
63
- <button
64
- type="button"
65
- onClick={() => {
66
- // Opened via the editor's "Preview" (script-opened tab) → close
67
- // it. Opened by navigating to the URL directly (no opener, so
68
- // `window.close()` is a no-op) → fall back to the editor so the
69
- // button is never dead.
70
- if (window.opener) window.close()
71
- else onNavigate(`/pages/${documentId}/edit`)
72
- }}
73
- className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1.5 text-sm"
74
- aria-label="Close preview tab"
75
- >
76
- <X className="h-4 w-4" aria-hidden />
77
- Close
78
- </button>
79
- <span className="text-muted-foreground text-xs">
80
- Preview · {page.title || 'Untitled'} {page.path}
81
- </span>
82
- <button
83
- type="button"
84
- onClick={() => onNavigate(`/pages/${documentId}/edit`)}
85
- className="bg-primary text-primary-foreground hover:bg-primary/90 inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium"
86
- >
87
- <Pencil className="h-3.5 w-3.5" aria-hidden />
88
- Open editor
89
- </button>
90
- </div>
91
-
92
- {/* The canvas is intentionally white regardless of the admin theme:
93
- it emulates the public page surface, not admin chrome. */}
94
- <div className="prenta-canvas bg-card flex-1 overflow-auto">
95
- {visible.length === 0 ? (
96
- <div className="text-muted-foreground flex h-full items-center justify-center text-sm">
97
- This page has no visible sections yet.
98
- </div>
99
- ) : (
100
- visible.map((section) => <SectionRenderer key={section.id} section={section} />)
101
- )}
102
- </div>
103
- </div>
104
- )
105
- }
@@ -1,250 +0,0 @@
1
- 'use client'
2
-
3
- import { useEffect, useLayoutEffect, useRef, useState } from 'react'
4
- import { Loader2 } from 'lucide-react'
5
- import { injectPreviewEditChrome } from '../../lib/canvas-edit-chrome.js'
6
- import {
7
- canvasOriginFromSrc,
8
- isPreviewBridgeMessage,
9
- isPreviewEditMessage,
10
- isPreviewRequestMediaMessage,
11
- PREVIEW_BRIDGE_VERSION,
12
- PREVIEW_SECTIONS_DEBOUNCE_MS,
13
- toPreviewSectionPayload,
14
- type PreviewHighlightMessage,
15
- type PreviewModeMessage,
16
- type PreviewSectionPayload,
17
- type PreviewSectionsMessage,
18
- } from '../../lib/preview-bridge.js'
19
- import { getViewport, type ViewportId } from './viewports.js'
20
-
21
- export interface CanvasEditPayload {
22
- sectionId: string
23
- fieldPath: string
24
- value: string
25
- }
26
-
27
- export interface CanvasMediaRequestPayload {
28
- sectionId: string
29
- fieldPath: string
30
- }
31
-
32
- interface SitePreviewFrameProps {
33
- /** Canvas draft URL; null while the preview token is still minting. */
34
- src: string | null
35
- viewport: ViewportId
36
- /** Changing this remounts the iframe so it reloads the persisted draft. */
37
- reloadKey: number
38
- title?: string
39
- /** Currently selected section in the editor — pushed to the canvas as a highlight. */
40
- selectedId?: string | null
41
- /** Live editor sections — debounced push after canvas ready (Phase 3). */
42
- sections?: PreviewSectionPayload[]
43
- /**
44
- * Increment after a canvas-originated text edit so the next sections push is
45
- * skipped (avoids remounting a focused contenteditable).
46
- */
47
- suppressSectionsEcho?: number
48
- /** Canvas → admin: section (and optional field) clicked in the real design. */
49
- onSelectSection?: (sectionId: string | null, fieldPath?: string) => void
50
- /** Canvas → admin: inline text edit (Stage 3). */
51
- onCanvasEdit?: (edit: CanvasEditPayload) => void
52
- /** Canvas → admin: open media picker for a field (Stage 3 wave B). */
53
- onCanvasRequestMedia?: (request: CanvasMediaRequestPayload) => void
54
- }
55
-
56
- /**
57
- * Inline branded preview surface — Next builder route in an iframe at the
58
- * selected viewport's *true* CSS width, CSS-`transform: scale()`'d to fit
59
- * (never crop). Stage 3: mode / edit / request-media + suppress-echo for
60
- * canvas-originated text edits.
61
- */
62
- export function SitePreviewFrame({
63
- src,
64
- viewport,
65
- reloadKey,
66
- title = 'Site preview',
67
- selectedId = null,
68
- sections,
69
- suppressSectionsEcho = 0,
70
- onSelectSection,
71
- onCanvasEdit,
72
- onCanvasRequestMedia,
73
- }: SitePreviewFrameProps) {
74
- const vp = getViewport(viewport)
75
- const containerRef = useRef<HTMLDivElement>(null)
76
- const sentinelRef = useRef<HTMLDivElement>(null)
77
- const iframeRef = useRef<HTMLIFrameElement>(null)
78
- const [scale, setScale] = useState(1)
79
- const [frameHeight, setFrameHeight] = useState(600)
80
- const [loaded, setLoaded] = useState(false)
81
- const [canvasReady, setCanvasReady] = useState(false)
82
- const canvasOrigin = canvasOriginFromSrc(src)
83
- const lastSuppressRef = useRef(suppressSectionsEcho)
84
-
85
- /**
86
- * Measure from a zero-height sentinel, never `clientWidth - 48`.
87
- *
88
- * The 48 was `p-6` written down a second time, in a second unit, four
89
- * hundred lines from the class it mirrors. It disagrees with reality the
90
- * moment a scrollbar appears, and it rots silently if the gutter ever
91
- * changes — nothing fails, the preview just scales slightly wrong.
92
- *
93
- * The sentinel is subject to the same padding, the same scrollbar and the
94
- * same host scaling as the frame, so its `offsetWidth` IS the usable width
95
- * and there is no arithmetic to get wrong. Same rule as `CanvasSurface`,
96
- * which is where this was first learned; this file is the third copy of the
97
- * arithmetic and the last one to go.
98
- *
99
- * Height still comes from the container, because the sentinel is
100
- * deliberately zero-height and can say nothing about it — but it is read as
101
- * `clientHeight - (clientWidth - sentinelWidth)`, deriving the vertical
102
- * gutter from the measured horizontal one rather than hardcoding it again.
103
- * That holds for the symmetric `p-6` this uses and degrades to the old
104
- * behaviour rather than breaking if it ever stops being symmetric.
105
- */
106
- useLayoutEffect(() => {
107
- const container = containerRef.current
108
- const sentinel = sentinelRef.current
109
- if (!container || !sentinel) return
110
- const recompute = () => {
111
- const availableW = sentinel.offsetWidth
112
- if (availableW <= 0) return
113
- const gutter = Math.max(0, container.clientWidth - availableW)
114
- const availableH = container.clientHeight - gutter
115
- const next = Math.min(1, availableW / vp.width)
116
- setScale(next > 0 ? next : 1)
117
- setFrameHeight(availableH > 0 ? availableH : 600)
118
- }
119
- recompute()
120
- const ro = new ResizeObserver(recompute)
121
- ro.observe(container)
122
- ro.observe(sentinel)
123
- return () => ro.disconnect()
124
- }, [vp.width])
125
-
126
- useEffect(() => {
127
- setLoaded(false)
128
- setCanvasReady(false)
129
- }, [src, reloadKey])
130
-
131
- // Canvas → admin: ready handshake + select + edit + request-media.
132
- useEffect(() => {
133
- if (!canvasOrigin) return
134
- const onMessage = (event: MessageEvent) => {
135
- if (event.origin !== canvasOrigin) return
136
- if (!isPreviewBridgeMessage(event.data)) return
137
- if (event.data.type === 'prenta-preview:ready') {
138
- setCanvasReady(true)
139
- return
140
- }
141
- if (event.data.type === 'prenta-preview:select' && onSelectSection) {
142
- onSelectSection(event.data.sectionId, event.data.fieldPath)
143
- return
144
- }
145
- if (isPreviewEditMessage(event.data) && onCanvasEdit) {
146
- onCanvasEdit({
147
- sectionId: event.data.sectionId,
148
- fieldPath: event.data.fieldPath,
149
- value: event.data.value,
150
- })
151
- return
152
- }
153
- if (isPreviewRequestMediaMessage(event.data) && onCanvasRequestMedia) {
154
- onCanvasRequestMedia({
155
- sectionId: event.data.sectionId,
156
- fieldPath: event.data.fieldPath,
157
- })
158
- }
159
- }
160
- window.addEventListener('message', onMessage)
161
- return () => window.removeEventListener('message', onMessage)
162
- }, [canvasOrigin, onSelectSection, onCanvasEdit, onCanvasRequestMedia])
163
-
164
- // Admin → canvas: enable inline editing once the canvas is ready.
165
- useEffect(() => {
166
- if (!canvasOrigin || !loaded || !canvasReady) return
167
- const win = iframeRef.current?.contentWindow
168
- if (!win) return
169
- const msg: PreviewModeMessage = {
170
- type: 'prenta-preview:mode',
171
- v: PREVIEW_BRIDGE_VERSION,
172
- editing: true,
173
- }
174
- win.postMessage(msg, canvasOrigin)
175
- // Same-origin only — cross-origin previews skip silently.
176
- injectPreviewEditChrome(iframeRef.current)
177
- }, [canvasOrigin, loaded, canvasReady, reloadKey])
178
-
179
- // Admin → canvas: highlight the selected section.
180
- useEffect(() => {
181
- if (!canvasOrigin || !loaded || !canvasReady) return
182
- const win = iframeRef.current?.contentWindow
183
- if (!win) return
184
- const msg: PreviewHighlightMessage = {
185
- type: 'prenta-preview:highlight',
186
- v: PREVIEW_BRIDGE_VERSION,
187
- sectionId: selectedId,
188
- }
189
- win.postMessage(msg, canvasOrigin)
190
- }, [canvasOrigin, selectedId, loaded, canvasReady, reloadKey])
191
-
192
- // Admin → canvas: live section content (debounced). Skip one cycle after
193
- // canvas-originated text edits so contenteditable does not remount.
194
- useEffect(() => {
195
- if (!canvasOrigin || !loaded || !canvasReady || !sections) return
196
- if (suppressSectionsEcho !== lastSuppressRef.current) {
197
- lastSuppressRef.current = suppressSectionsEcho
198
- return
199
- }
200
- const win = iframeRef.current?.contentWindow
201
- if (!win) return
202
- const timer = window.setTimeout(() => {
203
- const msg: PreviewSectionsMessage = {
204
- type: 'prenta-preview:sections',
205
- v: PREVIEW_BRIDGE_VERSION,
206
- sections: sections.map(toPreviewSectionPayload),
207
- }
208
- win.postMessage(msg, canvasOrigin)
209
- }, PREVIEW_SECTIONS_DEBOUNCE_MS)
210
- return () => window.clearTimeout(timer)
211
- }, [canvasOrigin, loaded, canvasReady, sections, reloadKey, suppressSectionsEcho])
212
-
213
- return (
214
- <div ref={containerRef} className="bg-muted relative h-full overflow-hidden p-6">
215
- {/*
216
- * Zero-height sentinel — see the measurement effect above. Must stay the
217
- * first child and must stay zero-height. `absolute` would defeat it: it
218
- * has to sit in the padding box to inherit the gutter it is measuring.
219
- */}
220
- <div ref={sentinelRef} aria-hidden className="h-0" />
221
- {(!src || !loaded) && (
222
- <div
223
- className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-2"
224
- aria-live="polite"
225
- >
226
- <Loader2 className="text-muted-foreground h-6 w-6 animate-spin" aria-hidden />
227
- <span className="text-muted-foreground text-sm">Loading site preview…</span>
228
- </div>
229
- )}
230
- {src && (
231
- <div className="mx-auto" style={{ width: vp.width * scale, height: frameHeight }}>
232
- <iframe
233
- key={reloadKey}
234
- ref={iframeRef}
235
- src={src}
236
- title={title}
237
- onLoad={() => setLoaded(true)}
238
- className="border-border bg-card rounded-xl border shadow-sm"
239
- style={{
240
- width: vp.width,
241
- height: frameHeight / scale,
242
- transform: `scale(${scale})`,
243
- transformOrigin: 'top left',
244
- }}
245
- />
246
- </div>
247
- )}
248
- </div>
249
- )
250
- }
@@ -1,158 +0,0 @@
1
- 'use client'
2
-
3
- import { useCallback, useEffect, useRef, useState } from 'react'
4
- import { toast } from 'sonner'
5
- import {
6
- buildPublicPreviewUrl,
7
- createPreviewToken,
8
- resolveSiteUrl,
9
- } from '../../lib/preview-link.js'
10
- import type { SaveState } from './EditorTopBar.js'
11
-
12
- interface UseSitePreviewOptions {
13
- collection: string
14
- documentId?: string | null
15
- slug?: string | null
16
- /** Explicit public path (`data.path`); wins over slug when set. */
17
- path?: string | null
18
- /** Collection URL prefix (e.g. `blog`). Empty/null for top-level pages. */
19
- urlPrefix?: string | null
20
- /**
21
- * Origin of the Next editing canvas (same host as the admin in Astro-split
22
- * and 100% Next builds). Defaults to `window.location.origin` so Site
23
- * preview loads the Next builder, not the Astro public apex.
24
- */
25
- canvasUrl?: string | null
26
- /**
27
- * @deprecated Prefer {@link canvasUrl}. Kept as a fallback when `canvasUrl`
28
- * is unset and `window` is unavailable. "View on site" still uses the
29
- * public apex via {@link buildPublicPreviewUrl} at the call site.
30
- */
31
- siteUrl?: string | null
32
- dirty: boolean
33
- saveState: SaveState
34
- /** Persist the draft; resolves `false` when the save failed. */
35
- saveDraft: () => Promise<boolean>
36
- /** Open Site preview on load when the document is saved (has id + slug). */
37
- defaultActive?: boolean
38
- }
39
-
40
- export interface SitePreviewState {
41
- /** Whether the inline iframe preview replaces the editor canvas. */
42
- active: boolean
43
- /** Canvas draft URL (`/<slug>?preview=<jwt>`); null while the token mints. */
44
- url: string | null
45
- /** Bumped after each completed save so the iframe reloads the fresh draft. */
46
- reloadKey: number
47
- toggle: () => void
48
- }
49
-
50
- /** Prefer the Next canvas origin (admin host); fall back to siteUrl only offline. */
51
- function resolveCanvasOrigin(canvasUrl?: string | null, siteUrl?: string | null): string {
52
- if (canvasUrl) return resolveSiteUrl(canvasUrl)
53
- if (typeof window !== 'undefined' && window.location?.origin) {
54
- return window.location.origin
55
- }
56
- return resolveSiteUrl(siteUrl)
57
- }
58
-
59
- /**
60
- * Inline branded preview — drives an in-editor iframe that renders the draft
61
- * through the consumer's Next builder route (same `?preview=<token>` contract
62
- * as "View on site"), so editors see actual site CSS without leaving the
63
- * admin. On Astro-split deploys the canvas is the CMS host, not the public
64
- * Astro apex. Saves first when dirty, and reloads the frame after each save.
65
- */
66
- export function useSitePreview({
67
- collection,
68
- documentId,
69
- slug,
70
- path,
71
- urlPrefix,
72
- canvasUrl,
73
- siteUrl,
74
- dirty,
75
- saveState,
76
- saveDraft,
77
- defaultActive = false,
78
- }: UseSitePreviewOptions): SitePreviewState {
79
- const [active, setActive] = useState(false)
80
- const [url, setUrl] = useState<string | null>(null)
81
- const [reloadKey, setReloadKey] = useState(0)
82
- const tokenRef = useRef<string | null>(null)
83
- const prevSaveState = useRef(saveState)
84
- const autoOpenRef = useRef(false)
85
-
86
- const activatePreview = useCallback(async () => {
87
- if (!documentId || !slug) {
88
- toast.error('Save the page before opening the site preview')
89
- return false
90
- }
91
- setActive(true)
92
- setUrl(null)
93
- try {
94
- if (dirty) {
95
- const ok = await saveDraft()
96
- if (!ok) {
97
- setActive(false)
98
- return false
99
- }
100
- }
101
- const { token } = await createPreviewToken(collection, documentId)
102
- tokenRef.current = token
103
- setUrl(
104
- buildPublicPreviewUrl({
105
- siteUrl: resolveCanvasOrigin(canvasUrl, siteUrl),
106
- urlPrefix: urlPrefix ?? '',
107
- slug,
108
- path,
109
- token,
110
- }),
111
- )
112
- return true
113
- } catch (err) {
114
- toast.error(err instanceof Error ? err.message : 'Failed to open site preview')
115
- setActive(false)
116
- return false
117
- }
118
- }, [collection, documentId, slug, path, urlPrefix, canvasUrl, siteUrl, dirty, saveDraft])
119
-
120
- // Opt-in default: open the iframe once a saved document is loaded.
121
- useEffect(() => {
122
- if (!defaultActive || autoOpenRef.current) return
123
- if (!documentId || !slug) return
124
- autoOpenRef.current = true
125
- void activatePreview()
126
- }, [defaultActive, documentId, slug, activatePreview])
127
-
128
- // After a save completes while the preview is open, rebuild the URL (the
129
- // slug/path may have changed in settings — the token is bound to the document
130
- // id, not the path) and reload the frame.
131
- useEffect(() => {
132
- if (active && prevSaveState.current === 'saving' && saveState === 'saved') {
133
- if (tokenRef.current && slug) {
134
- setUrl(
135
- buildPublicPreviewUrl({
136
- siteUrl: resolveCanvasOrigin(canvasUrl, siteUrl),
137
- urlPrefix: urlPrefix ?? '',
138
- slug,
139
- path,
140
- token: tokenRef.current,
141
- }),
142
- )
143
- }
144
- setReloadKey((k) => k + 1)
145
- }
146
- prevSaveState.current = saveState
147
- }, [active, saveState, slug, path, canvasUrl, siteUrl, urlPrefix])
148
-
149
- const toggle = useCallback(() => {
150
- if (active) {
151
- setActive(false)
152
- return
153
- }
154
- void activatePreview()
155
- }, [active, activatePreview])
156
-
157
- return { active, url, reloadKey, toggle }
158
- }
@@ -1,125 +0,0 @@
1
- 'use client'
2
-
3
- import { useEffect, useState } from 'react'
4
- import { AlertTriangle, Loader2, Pencil, X } from 'lucide-react'
5
- import {
6
- fetchPostForEditor,
7
- fetchTemplateForEditor,
8
- type EditorPost,
9
- type PostHeaderConfig,
10
- } from '../../lib/post-editor-service.js'
11
- import { defaultPostHeader } from '@prenta/core/page-sections'
12
- import { SectionRenderer, type PostRenderContext } from '../page-editor/sections/index.js'
13
- import { PostHeader } from './PostHeader.js'
14
-
15
- interface PostPreviewProps {
16
- postType: string
17
- documentId: string
18
- session?: any
19
- onNavigate: (path: string) => void
20
- }
21
-
22
- /**
23
- * Chrome-free render of a post using the same header + section renderers as
24
- * the editor canvas, so the preview reflects what ships. Only visible
25
- * sections render (hidden ones are omitted, like the public page).
26
- */
27
- export function PostPreview({ postType, documentId, session, onNavigate }: PostPreviewProps) {
28
- const [post, setPost] = useState<EditorPost | null>(null)
29
- const [header, setHeader] = useState<PostHeaderConfig>(defaultPostHeader())
30
- const [loading, setLoading] = useState(true)
31
- const [error, setError] = useState<string | null>(null)
32
-
33
- useEffect(() => {
34
- let cancelled = false
35
- setLoading(true)
36
- fetchTemplateForEditor(postType)
37
- .then((t) => !cancelled && setHeader(t.header))
38
- .catch(() => {
39
- /* default header */
40
- })
41
- fetchPostForEditor(postType, documentId)
42
- .then((p) => !cancelled && setPost(p))
43
- .catch((err) => !cancelled && setError(err instanceof Error ? err.message : 'Failed to load'))
44
- .finally(() => !cancelled && setLoading(false))
45
- return () => {
46
- cancelled = true
47
- }
48
- }, [postType, documentId])
49
-
50
- if (loading) {
51
- return (
52
- <div className="bg-background flex h-full items-center justify-center">
53
- <Loader2 className="text-muted-foreground h-6 w-6 animate-spin" aria-hidden />
54
- <span className="sr-only">Loading preview…</span>
55
- </div>
56
- )
57
- }
58
-
59
- if (error || !post) {
60
- return (
61
- <div className="bg-background flex h-full items-center justify-center p-6">
62
- <div className="border-destructive/30 bg-destructive/5 flex max-w-md items-center gap-3 rounded-lg border p-4">
63
- <AlertTriangle className="text-destructive shrink-0" size={20} aria-hidden />
64
- <p className="text-foreground text-sm font-medium">{error ?? 'Post not found.'}</p>
65
- </div>
66
- </div>
67
- )
68
- }
69
-
70
- const context: PostRenderContext = {
71
- title: post.title,
72
- excerpt: post.excerpt,
73
- body: post.body,
74
- featuredImageUrl: post.featuredImage,
75
- publishDate: post.publishDate ?? post.updatedAt ?? null,
76
- category: post.category,
77
- author: { name: session?.user?.name || session?.user?.email },
78
- }
79
- const visible = post.sections.filter((s) => s.visible)
80
-
81
- // `window.close()` only works for tabs JS opened (the "View preview" action
82
- // opens this view via window.open). When the user reached it through in-app
83
- // navigation there is no opener, so close() is a silent no-op — fall back to
84
- // the editor after a tick so the Close button always does something.
85
- const handleClose = () => {
86
- window.close()
87
- setTimeout(() => {
88
- onNavigate(`/posts/${postType}/${documentId}/edit`)
89
- }, 120)
90
- }
91
-
92
- return (
93
- <div className="flex h-full flex-col">
94
- {/* Slim preview bar. This view opens in its own browser tab, so
95
- actions are tab-scoped. */}
96
- <div className="bg-card border-border flex h-12 shrink-0 items-center justify-between border-b px-4">
97
- <button
98
- type="button"
99
- onClick={handleClose}
100
- className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1.5 text-sm"
101
- aria-label="Close preview tab"
102
- >
103
- <X className="h-4 w-4" aria-hidden />
104
- Close
105
- </button>
106
- <span className="text-muted-foreground text-xs">Preview · {post.title || 'Untitled'}</span>
107
- <button
108
- type="button"
109
- onClick={() => onNavigate(`/posts/${postType}/${documentId}/edit`)}
110
- className="bg-primary text-primary-foreground hover:bg-primary/90 inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium"
111
- >
112
- <Pencil className="h-3.5 w-3.5" aria-hidden />
113
- Open editor
114
- </button>
115
- </div>
116
-
117
- <div className="prenta-canvas bg-card flex-1 overflow-auto">
118
- <PostHeader config={header} context={context} />
119
- {visible.map((section) => (
120
- <SectionRenderer key={section.id} section={section} context={context} />
121
- ))}
122
- </div>
123
- </div>
124
- )
125
- }