Raw
1 import {
2 CustomFieldContainerZone,
3 CustomFieldFormTab,
4 CustomFieldFormZone,
5 CustomFieldModel,
6 deepMerge,
7 InjectionZone,
8 NESTED_ROUTE_POSITIONS,
9 } from "@medusajs/admin-shared"
10 import {
11 LayoutDefinition,
12 SectionWidgetMap,
13 } from "../components/layout-composer/types"
14 import * as React from "react"
15 import {
16 createBrowserRouter,
17 RouteObject,
18 RouterProvider,
19 } from "react-router-dom"
20 import { INavItem } from "../components/layout/nav-item"
21 import { Providers } from "../providers"
22 import coreTranslations from "../i18n/translations"
23 import { getRouteMap } from "./routes/get-route.map"
24 import { createRouteMap, getRouteExtensions } from "./routes/utils"
25 import { sortMenuItemsByRank } from "./utils/sort-menu-items-by-rank"
26 import { CORE_LAYOUTS } from "../components/layout-composer/core-layouts"
27 import {
28 ConfigExtension,
29 ConfigField,
30 ConfigFieldMap,
31 DashboardPlugin,
32 DisplayExtension,
33 DisplayMap,
34 ExtensionApi,
35 FormExtension,
36 FormField,
37 FormFieldExtension,
38 FormFieldMap,
39 FormZoneMap,
40 I18nExtension,
41 LayoutMap,
42 MenuItemExtension,
43 MenuItemKey,
44 MenuMap,
45 WidgetExtension,
46 WidgetMap,
47 ZoneStructure,
48 } from "./types"
49
50 type DashboardAppProps = {
51 plugins: DashboardPlugin[]
52 }
53
54 /**
55 * Matches segments that are optional and at the end of the path.
56 * Example: /path/to/:id?
57 * Such paths can be added to the menu items without the optional segment.
58 */
59 const OPTIONAL_LAST_SEGMENT_MATCH = /\/([^/])+\?$/
60
61 export class DashboardApp {
62 private widgets: WidgetMap
63 private layouts: LayoutMap
64 private menus: MenuMap
65 private fields: FormFieldMap
66 private configs: ConfigFieldMap
67 private displays: DisplayMap
68 private coreRoutes: RouteObject[]
69 private settingsRoutes: RouteObject[]
70 private i18nResources: I18nExtension
71
72 constructor({ plugins }: DashboardAppProps) {
73 this.widgets = this.populateWidgets(plugins)
74 this.layouts = this.populateLayouts(plugins)
75 this.menus = this.populateMenus(plugins)
76
77 const { coreRoutes, settingsRoutes } = this.populateRoutes(plugins)
78 this.coreRoutes = coreRoutes
79 this.settingsRoutes = settingsRoutes
80
81 const { fields, configs } = this.populateForm(plugins)
82 this.fields = fields
83 this.configs = configs
84 this.displays = this.populateDisplays(plugins)
85 this.i18nResources = this.populateI18n(plugins)
86 }
87
88 private populateRoutes(plugins: DashboardPlugin[]) {
89 const coreRoutes: RouteObject[] = []
90 const settingsRoutes: RouteObject[] = []
91
92 for (const plugin of plugins) {
93 const filteredCoreRoutes = getRouteExtensions(plugin.routeModule, "core")
94 const filteredSettingsRoutes = getRouteExtensions(
95 plugin.routeModule,
96 "settings"
97 )
98
99 const coreRoutesMap = createRouteMap(filteredCoreRoutes)
100 const settingsRoutesMap = createRouteMap(filteredSettingsRoutes)
101
102 coreRoutes.push(...coreRoutesMap)
103 settingsRoutes.push(...settingsRoutesMap)
104 }
105
106 return { coreRoutes, settingsRoutes }
107 }
108
109 private populateWidgets(plugins: DashboardPlugin[]) {
110 const registry = new Map<InjectionZone, WidgetExtension[]>()
111
112 plugins.forEach((plugin) => {
113 const widgets = plugin.widgetModule.widgets
114 if (!widgets) {
115 return
116 }
117
118 widgets.forEach((widget) => {
119 widget.zone.forEach((zone) => {
120 if (!registry.has(zone)) {
121 registry.set(zone, [])
122 }
123 registry.get(zone)!.push(widget)
124 })
125 })
126 })
127
128 return registry
129 }
130
131 private populateLayouts(plugins: DashboardPlugin[]) {
132 const registry = new Map<string, LayoutDefinition>()
133
134 CORE_LAYOUTS.forEach((layout) => registry.set(layout.id, layout))
135
136 plugins.forEach((plugin) => {
137 plugin.layoutModule?.layouts?.forEach((layout) => {
138 registry.set(layout.id, layout)
139 })
140 })
141
142 return registry
143 }
144
145 private populateMenus(plugins: DashboardPlugin[]) {
146 const registry = new Map<MenuItemKey, INavItem[]>()
147 const tempRegistry: Record<string, INavItem> = {}
148
149 // Collect all menu items from all plugins
150 const allMenuItems: MenuItemExtension[] = []
151 plugins.forEach((plugin) => {
152 if (plugin.menuItemModule.menuItems) {
153 allMenuItems.push(...plugin.menuItemModule.menuItems)
154 }
155 })
156
157 if (allMenuItems.length === 0) {
158 return registry
159 }
160
161 allMenuItems.sort((a, b) => a.path.length - b.path.length)
162
163 allMenuItems.forEach((item) => {
164 item.path = item.path.replace(OPTIONAL_LAST_SEGMENT_MATCH, "")
165 if (item.path.includes("/:") || item.path.endsWith("/*")) {
166 if (process.env.NODE_ENV === "development") {
167 console.warn(
168 `[@medusajs/dashboard] Menu item for path "${item.path}" can't be added to the sidebar as it contains a mandatory parameter.`
169 )
170 }
171 return
172 }
173
174 const isSettingsPath = item.path.startsWith("/settings")
175 const key = isSettingsPath ? "settingsExtensions" : "coreExtensions"
176
177 const pathParts = item.path.split("/").filter(Boolean)
178 const parentPath = "/" + pathParts.slice(0, -1).join("/")
179
180 // Check if this is a nested settings path
181 if (isSettingsPath && pathParts.length > 2) {
182 if (process.env.NODE_ENV === "development") {
183 console.warn(
184 `[@medusajs/dashboard] Nested settings menu item "${item.path}" can't be added to the sidebar. Only top-level settings items are allowed.`
185 )
186 }
187 return // Skip this item entirely
188 }
189
190 // Find the parent item if it exists
191 const parentItem = allMenuItems.find(
192 (menuItem) => menuItem.path === parentPath
193 )
194
195 // Check if parent item is a nested route under existing route
196 if (
197 parentItem?.nested &&
198 NESTED_ROUTE_POSITIONS.includes(parentItem?.nested) &&
199 pathParts.length > 1
200 ) {
201 if (process.env.NODE_ENV === "development") {
202 console.warn(
203 `[@medusajs/dashboard] Nested menu item "${item.path}" can't be added to the sidebar as it is nested under "${parentItem.nested}".`
204 )
205 }
206 return
207 }
208
209 const navItem: INavItem & { rank?: number } = {
210 label: item.label,
211 to: item.path,
212 icon: item.icon ? <item.icon /> : undefined,
213 items: [],
214 nested: item.nested,
215 rank: item.rank,
216 translationNs: item.translationNs,
217 }
218
219 if (parentPath !== "/" && tempRegistry[parentPath]) {
220 if (!tempRegistry[parentPath].items) {
221 tempRegistry[parentPath].items = []
222 }
223 tempRegistry[parentPath].items!.push(navItem)
224 } else {
225 if (!registry.has(key)) {
226 registry.set(key, [])
227 }
228 registry.get(key)!.push(navItem)
229 }
230
231 tempRegistry[item.path] = navItem
232 })
233
234 // Sort menu items by rank (ascending order, undefined ranks come last)
235 registry.forEach((items, key) => {
236 const sorted = sortMenuItemsByRank(items)
237 registry.set(key, sorted)
238 })
239
240 return registry
241 }
242
243 private populateForm(plugins: DashboardPlugin[]): {
244 fields: FormFieldMap
245 configs: ConfigFieldMap
246 } {
247 const fields: FormFieldMap = new Map()
248 const configs: ConfigFieldMap = new Map()
249
250 plugins.forEach((plugin) => {
251 Object.entries(plugin.formModule.customFields).forEach(
252 ([model, customization]) => {
253 // Initialize maps if they don't exist for this model
254 if (!fields.has(model as CustomFieldModel)) {
255 fields.set(model as CustomFieldModel, new Map())
256 }
257 if (!configs.has(model as CustomFieldModel)) {
258 configs.set(model as CustomFieldModel, new Map())
259 }
260
261 // Process forms
262 const modelFields = this.processFields(customization.forms)
263 const existingModelFields = fields.get(model as CustomFieldModel)!
264
265 // Merge the maps
266 modelFields.forEach((zoneStructure, zone) => {
267 if (!existingModelFields.has(zone)) {
268 existingModelFields.set(zone, { components: [], tabs: new Map() })
269 }
270
271 const existingZoneStructure = existingModelFields.get(zone)!
272
273 // Merge components
274 existingZoneStructure.components.push(...zoneStructure.components)
275
276 // Merge tabs
277 zoneStructure.tabs.forEach((fields, tab) => {
278 if (!existingZoneStructure.tabs.has(tab)) {
279 existingZoneStructure.tabs.set(tab, [])
280 }
281 existingZoneStructure.tabs.get(tab)!.push(...fields)
282 })
283 })
284
285 // Process configs
286 const modelConfigs = this.processConfigs(customization.configs)
287 const existingModelConfigs = configs.get(model as CustomFieldModel)!
288
289 // Merge the config maps
290 modelConfigs.forEach((configFields, zone) => {
291 if (!existingModelConfigs.has(zone)) {
292 existingModelConfigs.set(zone, [])
293 }
294 existingModelConfigs.get(zone)!.push(...configFields)
295 })
296 }
297 )
298 })
299
300 return { fields, configs }
301 }
302
303 private processFields(forms: FormExtension[]): FormZoneMap {
304 const formZoneMap: FormZoneMap = new Map()
305
306 forms.forEach((fieldDef) =>
307 this.processFieldDefinition(formZoneMap, fieldDef)
308 )
309
310 return formZoneMap
311 }
312
313 private processConfigs(
314 configs: ConfigExtension[]
315 ): Map<CustomFieldFormZone, ConfigField[]> {
316 const modelConfigMap = new Map<CustomFieldFormZone, ConfigField[]>()
317
318 configs.forEach((configDef) => {
319 const { zone, fields } = configDef
320 const zoneConfigs: ConfigField[] = []
321
322 Object.entries(fields).forEach(([name, config]) => {
323 zoneConfigs.push({
324 name,
325 defaultValue: config.defaultValue,
326 validation: config.validation,
327 })
328 })
329
330 modelConfigMap.set(zone, zoneConfigs)
331 })
332
333 return modelConfigMap
334 }
335
336 private processFieldDefinition(
337 formZoneMap: FormZoneMap,
338 fieldDef: FormExtension
339 ) {
340 const { zone, tab, fields: fieldsDefinition } = fieldDef
341 const zoneStructure = this.getOrCreateZoneStructure(formZoneMap, zone)
342
343 Object.entries(fieldsDefinition).forEach(([fieldKey, fieldDefinition]) => {
344 const formField = this.createFormField(fieldKey, fieldDefinition)
345 this.addFormFieldToZoneStructure(zoneStructure, formField, tab)
346 })
347 }
348
349 private getOrCreateZoneStructure(
350 formZoneMap: FormZoneMap,
351 zone: CustomFieldFormZone
352 ): ZoneStructure {
353 let zoneStructure = formZoneMap.get(zone)
354 if (!zoneStructure) {
355 zoneStructure = { components: [], tabs: new Map() }
356 formZoneMap.set(zone, zoneStructure)
357 }
358 return zoneStructure
359 }
360
361 private createFormField(
362 fieldKey: string,
363 fieldDefinition: FormFieldExtension
364 ): FormField {
365 return {
366 name: fieldKey,
367 validation: fieldDefinition.validation,
368 label: fieldDefinition.label,
369 description: fieldDefinition.description,
370 Component: fieldDefinition.Component,
371 }
372 }
373
374 private addFormFieldToZoneStructure(
375 zoneStructure: ZoneStructure,
376 formField: FormField,
377 tab?: CustomFieldFormTab
378 ) {
379 if (tab) {
380 let tabFields = zoneStructure.tabs.get(tab)
381 if (!tabFields) {
382 tabFields = []
383 zoneStructure.tabs.set(tab, tabFields)
384 }
385 tabFields.push(formField)
386 } else {
387 zoneStructure.components.push(formField)
388 }
389 }
390
391 private populateDisplays(plugins: DashboardPlugin[]): DisplayMap {
392 const displays = new Map<
393 CustomFieldModel,
394 Map<CustomFieldContainerZone, React.ComponentType<{ data: any }>[]>
395 >()
396
397 plugins.forEach((plugin) => {
398 Object.entries(plugin.displayModule.displays).forEach(
399 ([model, customization]) => {
400 if (!displays.has(model as CustomFieldModel)) {
401 displays.set(
402 model as CustomFieldModel,
403 new Map<
404 CustomFieldContainerZone,
405 React.ComponentType<{ data: any }>[]
406 >()
407 )
408 }
409
410 const modelDisplays = displays.get(model as CustomFieldModel)!
411 const processedDisplays = this.processDisplays(customization)
412
413 // Merge the displays
414 processedDisplays.forEach((components, zone) => {
415 if (!modelDisplays.has(zone)) {
416 modelDisplays.set(zone, [])
417 }
418 modelDisplays.get(zone)!.push(...components)
419 })
420 }
421 )
422 })
423
424 return displays
425 }
426
427 private populateI18n(plugins: DashboardPlugin[]): I18nExtension {
428 let resources: I18nExtension = { ...coreTranslations }
429
430 for (const plugin of plugins) {
431 resources = deepMerge(resources, plugin.i18nModule?.resources)
432 }
433
434 return resources
435 }
436
437 private processDisplays(
438 displays: DisplayExtension[]
439 ): Map<CustomFieldContainerZone, React.ComponentType<{ data: any }>[]> {
440 const modelDisplayMap = new Map<
441 CustomFieldContainerZone,
442 React.ComponentType<{ data: any }>[]
443 >()
444
445 displays.forEach((display) => {
446 const { zone, Component } = display
447 if (!modelDisplayMap.has(zone)) {
448 modelDisplayMap.set(zone, [])
449 }
450 modelDisplayMap.get(zone)!.push(Component)
451 })
452
453 return modelDisplayMap
454 }
455
456 private getMenu(path: MenuItemKey) {
457 return this.menus.get(path) || []
458 }
459
460 private getWidgets(zone: InjectionZone): React.ComponentType[] {
461 return (this.widgets.get(zone) || []).map((w) => w.Component)
462 }
463
464 private getLayout(layoutId: string): LayoutDefinition | undefined {
465 return this.layouts.get(layoutId)
466 }
467
468 /**
469 * Returns widgets for a given base zone grouped by layout section.
470 * The legacy `.before`/`.after` ordering suffixes are stripped and
471 * ignored. Widgets are returned inregistration order and will be
472 * assigned a default order of 0 in the LayoutComposer.
473 */
474 private getWidgetsForSections(
475 route: string,
476 sections: string[]
477 ): SectionWidgetMap {
478 const result: SectionWidgetMap = {}
479
480 for (const [zone, extensions] of this.widgets.entries()) {
481 if (!zone.startsWith(route)) {
482 continue
483 }
484
485 const suffix = zone
486 .slice(route.length + 1)
487 .replace(/\.?(before|after)$/, "")
488
489 const mainSection = sections.includes("main") ? "main" : sections[0]
490 const section = suffix || mainSection
491
492 if (!result[section]) {
493 result[section] = []
494 }
495
496 extensions.forEach((ext, i) => {
497 // `ext.widgetId` is the build-time stable id (author id or file hash).
498 // The positional `${zone}:${i}` is only a defensive fallback for
499 // widgets registered without one (e.g. legacy/unbuilt bundles).
500 const sourceId = ext.widgetId ?? `${zone}:${i}`
501 result[section].push({
502 Component: ext.Component,
503 // The id intentionally omits the section so a widget keeps its
504 // identity (and saved preference) when its zone moves to a different
505 // section of the same route.
506 widgetId: `widget:${sourceId}`,
507 })
508 })
509 }
510
511 // Two widgets resolving to the same id (e.g. one source file injected into
512 // two zones) would collide as React keys, sortable ids, and preference
513 // keys. Suffix later occurrences deterministically so each entry stays
514 // addressable. Deduped across all sections — not per-section — since ids no
515 // longer carry their section, so the same source injected into two
516 // different sections would otherwise produce identical ids.
517 const seen = new Map<string, number>()
518 for (const section of Object.keys(result)) {
519 for (const entry of result[section]) {
520 const count = seen.get(entry.widgetId) ?? 0
521 seen.set(entry.widgetId, count + 1)
522 if (count > 0) {
523 entry.widgetId = `${entry.widgetId}#${count + 1}`
524 }
525 }
526 }
527
528 return result
529 }
530
531 private getFormFields(
532 model: CustomFieldModel,
533 zone: CustomFieldFormZone,
534 tab?: CustomFieldFormTab
535 ) {
536 const zoneMap = this.fields.get(model)?.get(zone)
537
538 if (!zoneMap) {
539 return []
540 }
541
542 if (tab) {
543 return zoneMap.tabs.get(tab) || []
544 }
545
546 return zoneMap.components
547 }
548
549 private getFormConfigs(model: CustomFieldModel, zone: CustomFieldFormZone) {
550 return this.configs.get(model)?.get(zone) || []
551 }
552
553 private getDisplays(model: CustomFieldModel, zone: CustomFieldContainerZone) {
554 return this.displays.get(model)?.get(zone) || []
555 }
556
557 private getI18nResources() {
558 return this.i18nResources
559 }
560
561 get api(): ExtensionApi {
562 return {
563 getMenu: this.getMenu.bind(this),
564 getWidgets: this.getWidgets.bind(this),
565 getLayout: this.getLayout.bind(this),
566 getWidgetsForSections: this.getWidgetsForSections.bind(this),
567 getFormFields: this.getFormFields.bind(this),
568 getFormConfigs: this.getFormConfigs.bind(this),
569 getDisplays: this.getDisplays.bind(this),
570 getI18nResources: this.getI18nResources.bind(this),
571 }
572 }
573
574 render() {
575 const routes = getRouteMap({
576 settingsRoutes: this.settingsRoutes,
577 coreRoutes: this.coreRoutes,
578 })
579
580 const router = createBrowserRouter(routes, {
581 basename: __BASE__ || "/",
582 })
583
584 return (
585 <Providers api={this.api}>
586 <RouterProvider router={router} />
587 </Providers>
588 )
589 }
590 }