Raw
1 import { DndContext, DragOverlay } from "@dnd-kit/core"
2 import { Badge, Button, usePrompt } from "@medusajs/ui"
3 import {
4 ComponentType,
5 Fragment,
6 ReactNode,
7 useCallback,
8 useEffect,
9 useId,
10 useMemo,
11 useState,
12 } from "react"
13 import { createPortal } from "react-dom"
14 import { useTranslation } from "react-i18next"
15 import { Outlet } from "react-router-dom"
16 import { useExtension } from "../../providers/extension-provider/use-extension"
17 import {
18 useLayoutCustomizerActiveEditor,
19 useLayoutCustomizerTriggerHost,
20 useLayoutEditRequest,
21 } from "../../hooks/use-layout-customizer-trigger-host"
22 import {
23 DisplayEntry,
24 RawEntry,
25 buildCoreEntries,
26 buildDisplayEntries,
27 extractSectionElements,
28 } from "./entries"
29 import { type LayoutEditContextValue } from "../../providers/layout-edit-provider/layout-edit-context"
30 import { LayoutEditProvider } from "../../providers/layout-edit-provider/layout-edit-provider"
31 import { LayoutEntry } from "./entry"
32 import { SectionDropzone } from "./section-dropzone"
33 import { EntryContent, SortableEntry } from "./sortable-entry"
34 import type {
35 LayoutPreference,
36 LayoutControlSize,
37 SectionNameFor,
38 Layouts,
39 WidgetPreference,
40 LayoutComponentProps,
41 } from "./types"
42 import { useLayoutDnd } from "../../hooks/use-layout-dnd"
43 import {
44 useLayoutPreference,
45 type LayoutScope,
46 } from "../../hooks/use-layout-preference"
47 import { CUSTOMIZE_IDS, LAYOUT_CONTROLS_LOCATION } from "./constants"
48
49 export type LayoutComposerProps<TLayoutId extends Layouts, TData> = {
50 /**
51 * The prefix used to derive widget injection zones, typically corresponds to the page.
52 * E.g. `"login"`, `"product.list"`, `"product.details"` etc.
53 */
54 widgetsZonePrefix: string
55 /**
56 * The id of the layout that should be used to render the page. E.g `"core:two-column"` or `"core:single-column"`.
57 */
58 preferredLayoutId: TLayoutId
59 /**
60 * The content to render in each section of the layout, keyed by the
61 * section names valid for `preferredLayoutId`.
62 */
63 sections: Record<SectionNameFor<TLayoutId>, ReactNode>
64 /**
65 * Data passed to the layout components(core + widgets) as props
66 */
67 data?: TData
68 /**
69 * Whether to render an `Outlet` after the layout, used to render modals such as drawers and dialogs.
70 *
71 * @default true
72 */
73 hasOutlet?: boolean
74 /**
75 * Stable id of the host this composer customizes (see `CUSTOMIZE_IDS`). The
76 * central `CustomizerMenu` lists it and, when chosen, drives this composer
77 * into edit mode. Composers for different hosts must use distinct ids; only
78 * one composer per id is mounted at a time.
79 *
80 * @default CUSTOMIZE_IDS.PAGE
81 */
82 customizeId?: string
83 /**
84 * Visual density of each entry's edit-mode overlay.
85 * @default "default"
86 */
87 controlSize?: LayoutControlSize
88 /**
89 * Skip widget injection zones entirely: no registered widgets are resolved
90 * for `widgetsZonePrefix`, so only the core `sections` entries are composed.
91 * Used by surfaces that are purely reorderable nav (e.g. the sidebars) where
92 * extensions shouldn't inject content.
93 *
94 * @default false
95 */
96 disableWidgets?: boolean
97 /**
98 * Optional props to pass to the layout component.
99 */
100 layoutProps?: Omit<LayoutComponentProps, "sections" | "data">
101 }
102
103 /**
104 * Whether two preferences describe the same layout. A widget with no
105 * meaningful overrides is treated as absent so that toggling a setting and
106 * back — or simply switching between scopes without editing — doesn't register
107 * as a change.
108 */
109 function isSamePreference(a: LayoutPreference, b: LayoutPreference): boolean {
110 const keys = new Set([...Object.keys(a.widgets), ...Object.keys(b.widgets)])
111 for (const key of keys) {
112 const aw = a.widgets[key]
113 const bw = b.widgets[key]
114 if (!!aw?.hidden !== !!bw?.hidden) {
115 return false
116 }
117 if (aw?.order !== bw?.order) {
118 return false
119 }
120 if (aw?.section !== bw?.section) {
121 return false
122 }
123 }
124 return true
125 }
126
127 const LayoutComposerRoot = <TLayoutId extends Layouts, TData>({
128 widgetsZonePrefix,
129 preferredLayoutId,
130 sections,
131 data,
132 hasOutlet = true,
133 customizeId = CUSTOMIZE_IDS.PAGE,
134 controlSize = "default",
135 disableWidgets = false,
136 layoutProps = {},
137 }: LayoutComposerProps<TLayoutId, TData>) => {
138 const { getWidgetsForSections, getLayout } = useExtension()
139 const {
140 personalPreference,
141 defaultPreference,
142 activeScope,
143 setPreference,
144 isSaving,
145 } = useLayoutPreference(widgetsZonePrefix)
146 const controlsHost = useLayoutCustomizerTriggerHost(LAYOUT_CONTROLS_LOCATION)
147 const { activeEditor, setActiveEditor } = useLayoutCustomizerActiveEditor()
148 const { editRequest, requestEdit } = useLayoutEditRequest()
149 const editorId = useId()
150 const { t } = useTranslation()
151 const prompt = usePrompt()
152
153 // Another composer is mid-edit; lock this one's trigger so the two don't both
154 // try to drive the shared top-bar controls slot at once.
155 const locked = activeEditor !== null && activeEditor !== editorId
156
157 const [editMode, setEditMode] = useState(false)
158 useEffect(() => {
159 return () => {
160 setActiveEditor(null)
161 }
162 }, [setActiveEditor])
163
164 // Consume an edit request aimed at this host. Clearing it first makes this a
165 // one-shot: it won't re-fire on later renders. `enterEdit` no-ops while
166 // another composer is editing (`locked`), so a stray request is safely
167 // dropped rather than queued.
168 useEffect(() => {
169 if (editRequest === customizeId && !editMode) {
170 requestEdit(null)
171 enterEdit()
172 }
173 // eslint-disable-next-line react-hooks/exhaustive-deps
174 }, [editRequest, customizeId, editMode])
175
176 const [draft, setDraft] = useState<LayoutPreference | null>(null)
177 // Which configuration the current edit session is targeting: the user's
178 // personal layout or the zone's shared default.
179 const [editScope, setEditScope] = useState<LayoutScope>("personal")
180
181 const preferenceForScope = useCallback(
182 (scope: LayoutScope): LayoutPreference => {
183 return scope === "default" ? defaultPreference : personalPreference
184 },
185 [defaultPreference, personalPreference]
186 )
187
188 const activePreference: LayoutPreference = useMemo(() => {
189 return editMode && draft ? draft : preferenceForScope(activeScope)
190 }, [editMode, draft, preferenceForScope, activeScope])
191
192 // Whether the current draft actually differs from the persisted preference
193 // for the scope being edited. Switching between scopes without making edits
194 // leaves this false, so saving is a no-op confirmation we can streamline.
195 const hasChanges = useMemo(() => {
196 return editMode && draft
197 ? !isSamePreference(draft, preferenceForScope(editScope))
198 : false
199 }, [editMode, draft, preferenceForScope, editScope])
200
201 // TODO: Implement switching between compatible layouts
202 const layoutId = preferredLayoutId
203
204 const layout = getLayout(layoutId)
205
206 // Derive the layout model: core + widget entries placed into their effective
207 // sections with the active preference applied. Memoized so it isn't rebuilt
208 // on unrelated re-renders (e.g. drag start) — only when the sections,
209 // registered widgets, or active preference actually change.
210 const { entriesBySection, widgetSectionMap, validSectionIds } =
211 useMemo(() => {
212 const coreElementsBySection = extractSectionElements(
213 sections as Record<string, ReactNode>
214 )
215 const naturalWidgets = disableWidgets
216 ? {}
217 : getWidgetsForSections(
218 widgetsZonePrefix,
219 layout?.sections?.map((s) => s.id) ?? []
220 )
221
222 // Build raw entries (core + widgets) at their natural sections. Relative
223 // placement before any user preference comes purely from the order they
224 // are pushed here, preserved by the stable sort in `buildDisplayEntries`.
225 // Widgets are pushed after core entries so they render after by default —
226 // If a configuration has been saved, newly added widget or core entry
227 // (which has no saved order) surfaces at the top, otherwise it will be
228 // placed at the bottom of the section.
229 const rawEntries: RawEntry[] = buildCoreEntries(coreElementsBySection)
230 for (const [naturalSection, widgets] of Object.entries(naturalWidgets)) {
231 for (const w of widgets) {
232 const WidgetComponent = w.Component as ComponentType<{
233 data?: unknown
234 }>
235 rawEntries.push({
236 widgetId: w.widgetId,
237 render: (data) => <WidgetComponent data={data} />,
238 naturalSection,
239 })
240 }
241 }
242
243 // Apply the active preference (draft when editing, persisted otherwise),
244 // keeping hidden entries with `hidden: true` so we can ghost them in edit
245 // mode.
246 const validSectionIds = new Set(layout?.sections.map((s) => s.id) ?? [])
247 const entriesBySection = buildDisplayEntries(
248 rawEntries,
249 activePreference,
250 validSectionIds
251 )
252
253 // Maps each entry's widgetId to the section it currently renders in.
254 // Shared by collision detection and the drag handlers to resolve the
255 // active/over sections of a move.
256 const widgetSectionMap: Record<string, string> = {}
257 for (const [sectionId, entries] of Object.entries(entriesBySection)) {
258 for (const e of entries) {
259 widgetSectionMap[e.widgetId] = sectionId
260 }
261 }
262
263 return {
264 entriesBySection,
265 widgetSectionMap,
266 validSectionIds,
267 }
268 }, [
269 sections,
270 widgetsZonePrefix,
271 layout,
272 activePreference,
273 getWidgetsForSections,
274 disableWidgets,
275 ])
276
277 const {
278 sensors,
279 collisionDetection,
280 activeEntry,
281 handleDragStart,
282 handleDragOver,
283 handleDragEnd,
284 } = useLayoutDnd({
285 entriesBySection,
286 widgetSectionMap,
287 validSectionIds,
288 setDraft,
289 })
290
291 const isHidden = useCallback(
292 (id: string): boolean => activePreference.widgets[id]?.hidden ?? false,
293 [activePreference]
294 )
295
296 const toggleHidden = useCallback((widgetId: string) => {
297 setDraft((prev) => {
298 if (!prev) {
299 return prev
300 }
301 const current = prev.widgets[widgetId] ?? {}
302 const nextWidget: WidgetPreference = {
303 ...current,
304 hidden: !current.hidden,
305 }
306 return {
307 ...prev,
308 widgets: { ...prev.widgets, [widgetId]: nextWidget },
309 }
310 })
311 }, [])
312
313 // Renders a single entry for the current mode: plain content at idle, a
314 // sortable wrapper with chrome in edit mode. An entry that currently renders
315 // nothing stays a sortable card showing a placeholder (see `SortableEntry`),
316 // so it remains visible and placeable rather than collapsing to a bare row.
317 const renderEntry = useCallback(
318 (entry: DisplayEntry): ReactNode => {
319 const content = entry.render(data)
320 if (!editMode) {
321 return <Fragment key={entry.widgetId}>{content}</Fragment>
322 }
323 return (
324 <SortableEntry
325 key={entry.widgetId}
326 widgetId={entry.widgetId}
327 order={entry.order}
328 hidden={entry.hidden}
329 onToggleHidden={() => toggleHidden(entry.widgetId)}
330 controlSize={controlSize}
331 >
332 {content}
333 </SortableEntry>
334 )
335 },
336 [data, editMode, controlSize, toggleHidden]
337 )
338
339 // Nested-children ordering shared with entries via `LayoutEditContext`. Reads
340 // order from the active preference (draft while editing, persisted otherwise)
341 // and writes into the draft so nested moves ride the same save/cancel flow.
342 const orderChildren = useCallback(
343 <T,>(children: T[], getId: (child: T) => string): T[] =>
344 [...children].sort(
345 (a, b) =>
346 (activePreference.widgets[getId(a)]?.order ?? 0) -
347 (activePreference.widgets[getId(b)]?.order ?? 0)
348 ),
349 [activePreference]
350 )
351
352 const setChildrenOrder = useCallback((orderedIds: string[]) => {
353 setDraft((prev) => {
354 if (!prev) {
355 return prev
356 }
357 const widgets = { ...prev.widgets }
358 orderedIds.forEach((id, index) => {
359 widgets[id] = { ...(widgets[id] ?? {}), order: index }
360 })
361 return { ...prev, widgets }
362 })
363 }, [])
364
365 const editContextValue = useMemo<LayoutEditContextValue>(
366 () => ({
367 editMode,
368 orderChildren,
369 setChildrenOrder,
370 isHidden,
371 toggleHidden,
372 }),
373 [editMode, orderChildren, setChildrenOrder, isHidden, toggleHidden]
374 )
375
376 function enterEdit() {
377 if (locked) {
378 return
379 }
380 setEditScope(activeScope)
381 setDraft(preferenceForScope(activeScope))
382 setEditMode(true)
383 setActiveEditor(editorId)
384 }
385
386 // When the user clicks a scope badge while editing:
387 // - If there are unsaved edits, keep the draft so the changes aren't lost
388 // and just retarget which scope they'll be saved to.
389 // - If the draft is clean (no edits vs. the current scope), load the saved
390 // preference for the new scope so the user sees its real state.
391 function switchScope(scope: LayoutScope) {
392 if (!hasChanges) {
393 setDraft(preferenceForScope(scope))
394 }
395 setEditScope(scope)
396 }
397
398 async function commitEdit() {
399 if (editScope === "default" && hasChanges) {
400 const confirmed = await prompt({
401 title: t("layout.saveForEveryoneTitle"),
402 description: t("layout.saveForEveryoneDescription"),
403 confirmText: t("layout.saveForEveryone"),
404 cancelText: t("actions.cancel"),
405 })
406 if (!confirmed) {
407 return
408 }
409 }
410
411 if (!draft) {
412 setEditMode(false)
413 setActiveEditor(null)
414 return
415 }
416
417 setPreference(
418 draft,
419 { asDefault: editScope === "default" },
420 {
421 onSuccess: () => {
422 setEditMode(false)
423 setDraft(null)
424 setActiveEditor(null)
425 },
426 }
427 )
428 }
429
430 function cancelEdit() {
431 setEditMode(false)
432 setDraft(null)
433 setActiveEditor(null)
434 }
435
436 const renderedSections: Record<string, ReactNode> = useMemo(() => {
437 const sections: Record<string, ReactNode> = {}
438 for (const section of layout?.sections ?? []) {
439 const entries = entriesBySection[section.id] ?? []
440 const visibleEntries = editMode
441 ? entries
442 : entries.filter((e) => !e.hidden)
443 const renderedItems = visibleEntries.map(renderEntry)
444
445 sections[section.id] = editMode ? (
446 <SectionDropzone
447 section={section}
448 items={visibleEntries.map((e) => e.widgetId)}
449 >
450 {renderedItems}
451 </SectionDropzone>
452 ) : (
453 renderedItems
454 )
455 }
456 return sections
457 }, [layout, entriesBySection, editMode, renderEntry])
458
459 const LayoutComponent = layout?.Component
460 if (!LayoutComponent) {
461 return null
462 }
463
464 // Edit-mode controls, portaled into the single top-bar slot while this
465 // composer is editing: Personal/Default badges to switch which configuration
466 // is being edited (active one highlighted), Cancel, and a Save button that
467 // targets the active scope ("Save for everyone" for the default). At idle the
468 // composer renders no controls — the central `CustomizerMenu` is the trigger.
469 const editControls = (
470 <div className="flex items-center gap-x-2">
471 <div className="flex items-center gap-x-1">
472 <Badge
473 size="xsmall"
474 color={editScope === "personal" ? "blue" : "grey"}
475 className="cursor-pointer"
476 onClick={() => switchScope("personal")}
477 >
478 {t("layout.personalView")}
479 </Badge>
480 <Badge
481 size="xsmall"
482 color={editScope === "default" ? "blue" : "grey"}
483 className="cursor-pointer"
484 onClick={() => switchScope("default")}
485 >
486 {t("layout.defaultView")}
487 </Badge>
488 </div>
489 <Button
490 size="small"
491 variant="secondary"
492 onClick={cancelEdit}
493 disabled={isSaving}
494 >
495 {t("actions.cancel")}
496 </Button>
497 <Button
498 size="small"
499 variant="primary"
500 onClick={commitEdit}
501 isLoading={isSaving}
502 >
503 {editScope === "default" && hasChanges
504 ? t("layout.saveForEveryone")
505 : t("actions.save")}
506 </Button>
507 </div>
508 )
509 const layoutNode = (
510 <LayoutComponent sections={renderedSections} data={data} {...layoutProps} />
511 )
512
513 return (
514 <LayoutEditProvider value={editContextValue}>
515 {/* While editing, portal the Cancel/Save controls into the shared top-bar
516 * slot — they take the place of the central trigger menu, which hides
517 * itself for the duration. */}
518 {editMode && controlsHost
519 ? createPortal(editControls, controlsHost)
520 : null}
521 {editMode ? (
522 <DndContext
523 sensors={sensors}
524 collisionDetection={collisionDetection}
525 onDragStart={handleDragStart}
526 onDragOver={handleDragOver}
527 onDragEnd={handleDragEnd}
528 >
529 {layoutNode}
530 <DragOverlay>
531 {activeEntry ? (
532 <div className="bg-ui-bg-base shadow-elevation-flyout ring-ui-border-base min-w-0 rounded-lg ring-1">
533 <EntryContent>{activeEntry.render(data)}</EntryContent>
534 </div>
535 ) : null}
536 </DragOverlay>
537 </DndContext>
538 ) : (
539 layoutNode
540 )}
541 {hasOutlet && <Outlet />}
542 </LayoutEditProvider>
543 )
544 }
545
546 export const LayoutComposer = Object.assign(LayoutComposerRoot, {
547 Entry: LayoutEntry,
548 })