1 import {
2 Children,
3 ComponentType,
4 Fragment,
5 ReactElement,
6 ReactNode,
7 isValidElement,
8 } from "react"
9 import { LayoutEntry } from "./entry"
10 import type { LayoutEntryProps } from "./entry"
11 import { LayoutPreference } from "./types"
12
13 // Both core entries and widgets carry a `render` thunk so the rest of the
14 // composer treats them uniformly: core entries return their prebuilt element
15 // (ignoring `data`), widgets render their component with the page `data`. The
16 // thunk is what keeps `data` out of the layout-model memo — rendering is
17 // deferred to call time rather than baked into the entry.
18 export type EntryRenderer = (data: unknown) => ReactNode
19
20 export type DisplayEntry = {
21 widgetId: string
22 render: EntryRenderer
23 order: number
24 hidden: boolean
25 }
26
27 export type RawEntry = {
28 widgetId: string
29 render: EntryRenderer
30 naturalSection: string
31 }
32
33 /** Derives a stable string identifier from a React element's component type. */
34 function getElementName(element: ReactElement): string {
35 const { type } = element
36 if (typeof type === "string") {
37 return type
38 }
39 return (
40 (type as ComponentType).displayName ??
41 (type as ComponentType).name ??
42 "unknown"
43 )
44 }
45
46 function isLayoutEntry(
47 element: ReactElement
48 ): element is ReactElement<LayoutEntryProps> {
49 return element.type === LayoutEntry
50 }
51
52 /**
53 * Resolves the identity segment for a core element. Prefers an explicit
54 * `LayoutComposer.Entry` wrapper id (stable across renames and minification);
55 * otherwise falls back to the component's display/function name.
56 */
57 function getCoreEntryKey(element: ReactElement): string {
58 if (isLayoutEntry(element)) {
59 return element.props.id
60 }
61 return getElementName(element)
62 }
63
64 /**
65 * Builds a core entry for every element across all sections, in source order.
66 * Each entry renders its own prebuilt element.
67 *
68 * Duplicate ids (same component/name, or two anonymous elements) are
69 * disambiguated with a `#n` suffix via a single `seen` map shared across all
70 * sections — so two same-named entries in different sections still get distinct,
71 * deterministic ids and don't collide on keys, drag ids, or preference lookups.
72 * The id intentionally omits the section, so an entry keeps its identity (and
73 * saved preference) when its natural section changes in code.
74 */
75 export function buildCoreEntries(
76 elementsBySection: Record<string, ReactElement[]>
77 ): RawEntry[] {
78 const entries: RawEntry[] = []
79 const seen = new Map<string, number>()
80
81 for (const [sectionName, elements] of Object.entries(elementsBySection)) {
82 for (const el of elements) {
83 const name = getCoreEntryKey(el)
84 const base = `core:${name}`
85 const count = seen.get(base) ?? 0
86 seen.set(base, count + 1)
87 const widgetId = count === 0 ? base : `${base}#${count + 1}`
88
89 entries.push({
90 widgetId,
91 render: () => el,
92 naturalSection: sectionName,
93 })
94 }
95 }
96
97 return entries
98 }
99
100 export function extractSectionElements(
101 sections: Record<string, ReactNode>
102 ): Record<string, ReactElement[]> {
103 const result: Record<string, ReactElement[]> = {}
104 for (const [sectionName, node] of Object.entries(sections)) {
105 result[sectionName] = collectElements(node)
106 }
107 return result
108 }
109
110 /**
111 * Flattens a section's children into individual ReactElements, unwrapping
112 * fragments so each direct child component becomes its own customizer entry.
113 */
114 function collectElements(node: ReactNode): ReactElement[] {
115 const elements: ReactElement[] = []
116 Children.forEach(node, (child) => {
117 if (!isValidElement(child)) {
118 return
119 }
120 if (child.type === Fragment) {
121 const fragmentChildren = (child.props as { children?: ReactNode })
122 .children
123 elements.push(...collectElements(fragmentChildren))
124 return
125 }
126 elements.push(child)
127 })
128 return elements
129 }
130
131 /**
132 * Merges all entries (core + widgets) and applies a preference, returning a
133 * map of effective-section → DisplayEntry[] sorted by order. Includes hidden
134 * entries (with `hidden: true`) so the renderer can ghost them in edit mode.
135 *
136 * `validSections` is the set of section ids the active layout actually renders.
137 * A stored `section` override that points at a section which no longer exists
138 * (layout switched, section renamed/removed) is ignored so the entry falls back
139 * to its natural section instead of vanishing into an unrendered bucket.
140 */
141 export function buildDisplayEntries(
142 raw: RawEntry[],
143 preference: LayoutPreference,
144 validSections: Set<string>
145 ): Record<string, DisplayEntry[]> {
146 const result: Record<string, DisplayEntry[]> = {}
147 for (const entry of raw) {
148 const pref = preference.widgets[entry.widgetId]
149 const overrideSection =
150 pref?.section && validSections.has(pref.section)
151 ? pref.section
152 : undefined
153 const effectiveSection = overrideSection ?? entry.naturalSection
154 // Entries with no saved order share order 0; their relative placement
155 // (widgets before core, each group in source order) comes from insertion
156 // order preserved by the stable sort below.
157 const effectiveOrder = pref?.order ?? 0
158 const hidden = pref?.hidden ?? false
159 if (!result[effectiveSection]) {
160 result[effectiveSection] = []
161 }
162 result[effectiveSection].push({
163 widgetId: entry.widgetId,
164 render: entry.render,
165 order: effectiveOrder,
166 hidden,
167 })
168 }
169 for (const k of Object.keys(result)) {
170 result[k].sort((a, b) => a.order - b.order)
171 }
172 return result
173 }
174
175 export const SECTION_TAIL_SUFFIX = "::tail"
176
177 export const isSectionTailId = (id: string) => id.endsWith(SECTION_TAIL_SUFFIX)
178
179 export const getSectionIdFromTailId = (id: string) =>
180 id.slice(0, -SECTION_TAIL_SUFFIX.length)
181
182 // A section's trailing drop zone gets its own droppable id, derived from the
183 // section id, so the drag handlers can tell "dropped at the end of a section"
184 // apart from "dropped onto a specific entry". Kept here next to the component
185 // that renders it.
186 export const getSectionTailId = (sectionId: string) =>
187 `${sectionId}${SECTION_TAIL_SUFFIX}`