Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

feat(dashboard): layout composer, ordered extension layers, gates and layout preferences (#1674)

Viktor Holikd491bddff22b
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index 0fb1c0b9e..1005c5bda 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -445,6 +445,7 @@
"references/panel-extensions/overview",
"references/panel-extensions/custom-fields",
"references/panel-extensions/widgets",
+ "references/panel-extensions/layouts",
"references/panel-extensions/create-page"
]
},
diff --git a/apps/docs/references/panel-extensions/layouts.mdx b/apps/docs/references/panel-extensions/layouts.mdx
new file mode 100644
index 000000000..40c55ada3
--- /dev/null
+++ b/apps/docs/references/panel-extensions/layouts.mdx
@@ -0,0 +1,169 @@
+---
+title: "Layouts and layers"
+sidebarTitle: "Layouts and layers"
+description: "How extensions from plugins and your project stack, how a page exposes its sections, and how to hide, reorder, replace or wrap what a page renders."
+---
+
+Every panel extension comes from an ordered list of **layers**:
+
+1. `@mercurjs/admin` or `@mercurjs/vendor` itself,
+2. each plugin in `medusa-config` `plugins` order, from its built `.medusa/server/src/<admin|vendor>/index.mjs`,
+3. your Medusa project's `src/admin` or `src/vendor` folder (next to `medusa-config.ts`),
+4. the panel app's own `src` folder.
+
+A later layer wins. A route at a path an earlier layer declared replaces it, a widget with the same `id`
+replaces it, a translation key overrides it, and a layout preference overrides it field by field. Every
+layer uses the same folders: `routes/`, `widgets/`, `custom-fields/`, `layouts/`, `i18n/` and a
+`_layouts.ts` file.
+
+## Pages expose named entries
+
+A detail or list page renders a `LayoutComposer`. It names the zone widgets target, the layout it uses,
+and gives each section a stable entry id:
+
+```tsx
+import { CORE_LAYOUT_IDS } from "@mercurjs/dashboard-sdk"
+import { LayoutComposer, detailPageDefaultEntries } from "@mercurjs/dashboard-shared"
+
+<LayoutComposer
+ widgetsZonePrefix="product.detail"
+ preferredLayoutId={CORE_LAYOUT_IDS.TWO_COLUMN}
+ data={product}
+ sections={{
+ main: (
+ <>
+ <LayoutComposer.Entry id="ProductGeneralSection">
+ <ProductGeneralSection product={product} />
+ </LayoutComposer.Entry>
+ {detailPageDefaultEntries(product)}
+ </>
+ ),
+ side: (
+ <LayoutComposer.Entry id="ProductOrganizationSection">
+ <ProductOrganizationSection product={product} />
+ </LayoutComposer.Entry>
+ ),
+ }}
+/>
+```
+
+The page's own sections become entries `core:ProductGeneralSection`, `core:MetadataSection` and so on;
+widgets become `widget:<id>`. Use the same component on your own pages and the build emits their zones and
+entry ids into `extension-targets.d.ts`, so the next layer gets autocompletion for them.
+
+## Place a widget
+
+`zone` is the page prefix or one of its sections. `section` and `order` place the widget among the page's
+entries; core entries sit at order `0`, so a negative order renders before them and no order renders after.
+
+```tsx
+export const config = defineWidgetConfig({
+ zone: "product.detail",
+ id: "seller-offers",
+ section: "side",
+ order: -1,
+})
+```
+
+`replace` takes the slot of a page entry. The widget receives `renderDefault` to render what it replaced:
+
+```tsx
+export const config = defineWidgetConfig({
+ zone: "product.detail",
+ id: "general-with-seller",
+ replace: "core:ProductGeneralSection",
+})
+
+export default function GeneralWithSeller({ data, renderDefault }) {
+ return (
+ <>
+ {renderDefault?.()}
+ <SellerBadge product={data} />
+ </>
+ )
+}
+```
+
+The legacy `product.detail.side.before` and `.after` zones still work and map to the first and last
+position of that section.
+
+## Hide, reorder and move entries: `_layouts.ts`
+
+A layer's `_layouts.ts` holds per-zone preferences that apply to everyone. The sidebars are zones too
+(`nav.main`, `nav.settings`) with `nav:<path>` entries, which replaces `_navigation.ts`.
+
+```ts
+import { defineLayoutPreferences } from "@mercurjs/dashboard-sdk"
+import { Tag } from "@medusajs/icons"
+
+export default defineLayoutPreferences({
+ "product.detail": {
+ entries: {
+ "core:ProductMediaSection": { hidden: true },
+ "widget:seller-offers": { section: "main", order: 1 },
+ },
+ },
+ "nav.main": {
+ groups: [{ id: "finance", label: "Finance", rank: 5 }],
+ entries: {
+ "nav:/products": { label: "Catalog", icon: Tag, order: -1 },
+ "nav:/payouts": { section: "finance" },
+ "nav:/price-lists": { parent: null },
+ "nav:/settings/commissions": { hidden: true },
+ },
+ },
+})
+```
+
+## Override a page
+
+A `page.tsx` at a path an earlier layer already serves replaces it. The component receives `renderDefault`,
+which renders the page it replaced:
+
+```tsx
+export default function ProductDetail({ renderDefault }) {
+ return (
+ <>
+ <ApprovalBanner />
+ {renderDefault?.()}
+ </>
+ )
+}
+```
+
+## Block the panel behind a flow
+
+There is no app-wrapper seam, as in Medusa. A flow every member must complete before using the panel
+(terms acceptance, a verification step) is a page plus a redirect: a `routes/<flow>/page.tsx` with
+`config.public = true` so it renders in the bare public layout, and a widget on the `topbar` zone that
+checks the status with `useQuery` and `navigate`s to the page while the flow is outstanding. The API keeps
+enforcing the rule with a 403 for everything else.
+
+## Register a layout
+
+A file under `layouts/` registers a layout other pages can pick. Augment `LayoutSectionRegistry` so the
+`sections` prop is typed.
+
+```tsx
+import { defineLayoutConfig } from "@mercurjs/dashboard-sdk"
+
+export default defineLayoutConfig({
+ id: "erp:three-column",
+ sections: [{ id: "main" }, { id: "left" }, { id: "right" }],
+ Component: ({ sections }) => (
+ <div className="grid grid-cols-3 gap-3">
+ {sections.left}
+ {sections.main}
+ {sections.right}
+ </div>
+ ),
+})
+```
+
+```ts
+declare module "@mercurjs/dashboard-sdk" {
+ interface LayoutSectionRegistry {
+ "erp:three-column": "main" | "left" | "right"
+ }
+}
+```
diff --git a/claude-progress.md b/claude-progress.md
index a02226d42..be3f73c9b 100644
--- a/claude-progress.md
+++ b/claude-progress.md
@@ -14,6 +14,18 @@ session detail aggressively. The per-spec source of truth lives in
`bun run test:integration:http -- <pattern>`
- **Current blocker**: none
+## Session — Dashboard extensions, OS deltas D-001…D-005 (2026-10-20), branch `feat/dashboard-layout-composer`
+
+Spec: `docs/specs/spec-dashboard-extensions/` (local; `docs/specs` is gitignored), `in_progress`. PR #1674.
+- `LayoutComposer` (Medusa port, no edit mode) in `@mercurjs/dashboard-shared`; registry gained layouts,
+ gates, layered preferences, `getWidgetsForSections`; `resolveRouteOverrides` gives overriding routes
+ `renderDefault`. SDK: every virtual module merges ordered layers (`layers.ts`), new `layouts`/`preferences` modules, `defineRouteConfig`/`defineLayoutConfig`/`defineLayoutPreferences`.
+- Pilots on the composer: admin product detail, vendor offer detail (existing zone ids kept).
+- Verified: SDK vitest 16/16, shared vitest 33/33, panel tsc no new errors vs baseline, admin/vendor/cli
+ packages build, both host apps `vite build`. Docs page `references/panel-extensions/layouts.mdx`.
+- Next: D-006 (rewrite the remaining 116 compound pages, public `/hooks` + `/components`, peer deps),
+ D-007 (CLI emits extension-targets for plugins, typed plugin routes), sidebars as composers.
+
## Session — Seller ↔ Region assignment (SPEC-001), branch `feat/seller-regions`
Spec: `docs/specs/SPEC-001-seller-regions.md`. New `region_seller` link; `linkSellerRegionsWorkflow`;
diff --git a/packages/admin/scripts/generate-extension-targets.ts b/packages/admin/scripts/generate-extension-targets.ts
index 15b0f9fef..46b23e1b4 100644
--- a/packages/admin/scripts/generate-extension-targets.ts
+++ b/packages/admin/scripts/generate-extension-targets.ts
@@ -5,6 +5,8 @@
*
* - `<WidgetZone id="…">` usages, → WidgetZoneRegistry (+ placement suffixes)
* `useWidgetTabs("…")` calls
+ * - `<LayoutComposer widgetsZonePrefix>` → WidgetZoneRegistry (prefix + its layout sections)
+ * `<LayoutComposer.Entry id>` → LayoutEntryRegistry (`core:<id>`)
* - `useCoreRoutes()` `to:` literals → NavItemRegistry / NavParentRegistry
* - settings sidebar `to:` / group `id:` → NavItemRegistry / NavGroupRegistry
* - `<FormExtensionZone model zone>` / → CustomFieldsRegistry (form/display zones)
@@ -33,6 +35,39 @@ function walk(dir: string, out: string[] = []): string[] {
return out
}
+const LAYOUT_SECTIONS: Record<string, string[]> = {
+ "CORE_LAYOUT_IDS.SINGLE_COLUMN": ["main"],
+ "CORE_LAYOUT_IDS.TWO_COLUMN": ["main", "side"],
+}
+
+/**
+ * Composer pages: the zone prefix itself, one zone per section of the layout
+ * the page picked, and the `core:<id>` entry ids a widget may `replace`.
+ */
+function collectComposers(files: string[]): { zones: Set<string>; entries: Set<string> } {
+ const zones = new Set<string>()
+ const entries = new Set<string>()
+ const composerRe = /<LayoutComposer\b[^>]*?widgetsZonePrefix=["'`]([^"'`]+)["'`][^>]*?preferredLayoutId=\{([^}]+)\}/gs
+ const entryRe = /<LayoutComposer\.Entry\b[^>]*?\bid=["'`]([^"'`]+)["'`]/g
+ const defaultsRe = /detailPageDefaultEntries\(/
+ for (const file of files) {
+ const code = fs.readFileSync(file, "utf-8")
+ let m: RegExpExecArray | null
+ while ((m = composerRe.exec(code))) {
+ zones.add(m[1])
+ for (const section of LAYOUT_SECTIONS[m[2].trim()] ?? ["main"]) {
+ zones.add(`${m[1]}.${section}`)
+ }
+ }
+ while ((m = entryRe.exec(code))) entries.add(`core:${m[1]}`)
+ if (defaultsRe.test(code)) {
+ entries.add("core:MetadataSection")
+ entries.add("core:JsonViewSection")
+ }
+ }
+ return { zones, entries }
+}
+
function collectWidgetSlots(files: string[]): Set<string> {
const slots = new Set<string>()
const re = /<WidgetZone[^>]*\bid=["'`]([^"'`]+)["'`]/g
@@ -273,10 +308,17 @@ function keys(values: Iterable<string>): string {
function main() {
const files = walk(SRC)
const slots = collectWidgetSlots(files)
+ const composers = collectComposers(files)
const zoneIds = new Set<string>()
for (const slot of slots) {
for (const p of PLACEMENTS) zoneIds.add(`${slot}.${p}`)
}
+ for (const zone of composers.zones) {
+ zoneIds.add(zone)
+ if (zone.includes(".main") || zone.includes(".side")) {
+ for (const p of PLACEMENTS) zoneIds.add(`${zone}.${p}`)
+ }
+ }
const mainLayout = path.join(
SRC,
@@ -312,6 +354,10 @@ declare module "@mercurjs/dashboard-sdk" {
${keys(zoneIds)}
}
+ interface LayoutEntryRegistry {
+${keys(composers.entries)}
+ }
+
interface NavItemRegistry {
${keys(nav.items)}
}
diff --git a/packages/admin/src/app.tsx b/packages/admin/src/app.tsx
index 60ccef9c8..f632834db 100644
--- a/packages/admin/src/app.tsx
+++ b/packages/admin/src/app.tsx
@@ -2,9 +2,11 @@ import { customRoutes } from "virtual:mercur/routes";
import widgets from "virtual:mercur/widgets";
import navigation from "virtual:mercur/navigation";
import customFields from "virtual:mercur/custom-fields";
+import layouts from "virtual:mercur/layouts";
+import preferences from "virtual:mercur/preferences";
import { HelmetProvider } from "react-helmet-async";
import { QueryClientProvider } from "@tanstack/react-query";
-import { ExtensionProvider } from "@mercurjs/dashboard-shared";
+import { ExtensionProvider, resolveRouteOverrides } from "@mercurjs/dashboard-shared";
import { FeatureFlagProvider, ThemeProvider } from "./providers";
import { I18nProvider, Toaster, TooltipProvider } from "@medusajs/ui";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
@@ -16,10 +18,11 @@ import { queryClient } from "./lib/query-client";
export default function App() {
const routes = useMemo(() => {
+ const resolved = resolveRouteOverrides(customRoutes);
return {
- settingsRoutes: createRouteMap(getRoutesByType(customRoutes, "settings")),
- mainRoutes: createRouteMap(getRoutesByType(customRoutes, "main")),
- publicRoutes: createRouteMap(getRoutesByType(customRoutes, "public")),
+ settingsRoutes: createRouteMap(getRoutesByType(resolved, "settings")),
+ mainRoutes: createRouteMap(getRoutesByType(resolved, "main")),
+ publicRoutes: createRouteMap(getRoutesByType(resolved, "public")),
};
}, []);
@@ -33,6 +36,8 @@ export default function App() {
widgets={widgets}
navigation={navigation}
customFields={customFields}
+ layouts={layouts}
+ preferences={preferences}
>
<I18n />
<I18nProvider>
diff --git a/packages/admin/src/extension-targets.d.ts b/packages/admin/src/extension-targets.d.ts
index 047acb2fa..384dca830 100644
--- a/packages/admin/src/extension-targets.d.ts
+++ b/packages/admin/src/extension-targets.d.ts
@@ -100,8 +100,11 @@ declare module "@mercurjs/dashboard-sdk" {
"product-variants.detail.main.before": true
"product-variants.detail.side.after": true
"product-variants.detail.side.before": true
+ "product.detail": true
+ "product.detail.main": true
"product.detail.main.after": true
"product.detail.main.before": true
+ "product.detail.side": true
"product.detail.side.after": true
"product.detail.side.before": true
"products.list.after": true
@@ -162,6 +165,18 @@ declare module "@mercurjs/dashboard-sdk" {
"users.list.before": true
}
+ interface LayoutEntryRegistry {
+ "core:JsonViewSection": true
+ "core:MetadataSection": true
+ "core:ProductActiveEditSection": true
+ "core:ProductActiveRequestSection": true
+ "core:ProductAttributeSection": true
+ "core:ProductGeneralSection": true
+ "core:ProductMediaSection": true
+ "core:ProductOrganizationSection": true
+ "core:ProductVariantSection": true
+ }
+
interface NavItemRegistry {
"campaigns": true
"categories": true
diff --git a/packages/admin/src/module.d.ts b/packages/admin/src/module.d.ts
index 49b7e7065..0a71a4609 100644
--- a/packages/admin/src/module.d.ts
+++ b/packages/admin/src/module.d.ts
@@ -40,3 +40,15 @@ declare module "virtual:mercur/custom-fields" {
const customFields: CustomFieldsModule
export default customFields
}
+
+declare module "virtual:mercur/layouts" {
+ import { LayoutModule } from '@mercurjs/dashboard-shared'
+ const layouts: LayoutModule
+ export default layouts
+}
+
+declare module "virtual:mercur/preferences" {
+ import { PreferenceModule } from '@mercurjs/dashboard-shared'
+ const preferences: PreferenceModule
+ export default preferences
+}
diff --git a/packages/admin/src/pages/products/product-detail/product-detail.tsx b/packages/admin/src/pages/products/product-detail/product-detail.tsx
index 27be3bc18..22b1bc7f8 100644
--- a/packages/admin/src/pages/products/product-detail/product-detail.tsx
+++ b/packages/admin/src/pages/products/product-detail/product-detail.tsx
@@ -1,11 +1,14 @@
-import { ReactNode, Children } from "react";
import { useLoaderData, useParams } from "react-router-dom";
import { HttpTypes } from "@medusajs/types";
import { HttpTypes as MercurHttpTypes, SellerDTO } from "@mercurjs/types";
-import { WidgetZone, useLinkQuery } from "@mercurjs/dashboard-shared";
+import { CORE_LAYOUT_IDS } from "@mercurjs/dashboard-sdk";
+import {
+ LayoutComposer,
+ detailPageDefaultEntries,
+ useLinkQuery,
+} from "@mercurjs/dashboard-shared";
import { TwoColumnPageSkeleton } from "../../../components/common/skeleton";
-import { TwoColumnPage } from "../../../components/layout/pages";
import { useProduct } from "../../../hooks/api/products";
import { ProductActiveEditSection } from "./components/product-active-edit-section";
import { ProductActiveRequestSection } from "./components/product-active-request-section";
@@ -21,7 +24,7 @@ type AdminProductWithSeller = HttpTypes.AdminProduct & {
sellers?: SellerDTO[];
};
-const Root = ({ children }: { children?: ReactNode }) => {
+export const ProductDetailPage = () => {
const initialData = useLoaderData() as Awaited<
ReturnType<typeof productLoader>
>;
@@ -53,49 +56,44 @@ const Root = ({ children }: { children?: ReactNode }) => {
throw error;
}
- return Children.count(children) > 0 ? (
- <TwoColumnPage
+ return (
+ <LayoutComposer
+ widgetsZonePrefix="product.detail"
+ preferredLayoutId={CORE_LAYOUT_IDS.TWO_COLUMN}
data={product}
- showJSON
- showMetadata
data-testid="product-detail-page"
- >
- {children}
- </TwoColumnPage>
- ) : (
- <TwoColumnPage
- data={product}
- showJSON
- showMetadata
- data-testid="product-detail-page"
- >
- <TwoColumnPage.Main data-testid="product-detail-main">
- <WidgetZone id="product.detail.main" data={product}>
- <ProductActiveRequestSection product={product} />
- <ProductActiveEditSection product={product} />
- <ProductGeneralSection product={product} />
- <ProductMediaSection product={product} />
- <ProductVariantSection product={product} />
- </WidgetZone>
- </TwoColumnPage.Main>
- <TwoColumnPage.Sidebar data-testid="product-detail-sidebar">
- <WidgetZone id="product.detail.side" data={product}>
- <ProductOrganizationSection product={product} />
- <ProductAttributeSection product={product} />
- </WidgetZone>
- </TwoColumnPage.Sidebar>
- </TwoColumnPage>
+ sections={{
+ main: (
+ <>
+ <LayoutComposer.Entry id="ProductActiveRequestSection">
+ <ProductActiveRequestSection product={product} />
+ </LayoutComposer.Entry>
+ <LayoutComposer.Entry id="ProductActiveEditSection">
+ <ProductActiveEditSection product={product} />
+ </LayoutComposer.Entry>
+ <LayoutComposer.Entry id="ProductGeneralSection">
+ <ProductGeneralSection product={product} />
+ </LayoutComposer.Entry>
+ <LayoutComposer.Entry id="ProductMediaSection">
+ <ProductMediaSection product={product} />
+ </LayoutComposer.Entry>
+ <LayoutComposer.Entry id="ProductVariantSection">
+ <ProductVariantSection product={product} />
+ </LayoutComposer.Entry>
+ {detailPageDefaultEntries(product)}
+ </>
+ ),
+ side: (
+ <>
+ <LayoutComposer.Entry id="ProductOrganizationSection">
+ <ProductOrganizationSection product={product} />
+ </LayoutComposer.Entry>
+ <LayoutComposer.Entry id="ProductAttributeSection">
+ <ProductAttributeSection product={product} />
+ </LayoutComposer.Entry>
+ </>
+ ),
+ }}
+ />
);
};
-
-export const ProductDetailPage = Object.assign(Root, {
- Main: TwoColumnPage.Main,
- Sidebar: TwoColumnPage.Sidebar,
- MainActiveRequestSection: ProductActiveRequestSection,
- MainActiveEditSection: ProductActiveEditSection,
- MainGeneralSection: ProductGeneralSection,
- MainMediaSection: ProductMediaSection,
- MainAttributeSection: ProductAttributeSection,
- MainVariantSection: ProductVariantSection,
- SidebarOrganizationSection: ProductOrganizationSection,
-});
diff --git a/packages/admin/src/utils/routes.ts b/packages/admin/src/utils/routes.ts
index ee1657470..a083be8cf 100644
--- a/packages/admin/src/utils/routes.ts
+++ b/packages/admin/src/utils/routes.ts
@@ -1,10 +1,11 @@
import { ComponentType } from "react"
import { LoaderFunction, RouteObject } from "react-router-dom"
import type { Permission, RouteHandle } from "@mercurjs/dashboard-sdk"
+import type { RenderDefaultProps } from "@mercurjs/dashboard-shared"
import { ErrorBoundary } from "../components/utilities/error-boundary"
export type Route = {
- Component: ComponentType
+ Component: ComponentType<RenderDefaultProps>
path: string
loader?: LoaderFunction
handle?: RouteHandle
diff --git a/packages/admin/tsup.config.ts b/packages/admin/tsup.config.ts
index dd32b89ca..a503b30dd 100644
--- a/packages/admin/tsup.config.ts
+++ b/packages/admin/tsup.config.ts
@@ -5,5 +5,5 @@ export default defineConfig({
dts: true,
entry: ["src/index.ts", "src/index.css", 'src/pages/index.ts'],
format: ["esm"],
- external: ["react", "react-dom", "react-router-dom", "virtual:mercur/config", "virtual:mercur/routes", "virtual:mercur/menu-items", "virtual:mercur/i18n", "virtual:mercur/widgets", "virtual:mercur/navigation", "virtual:mercur/custom-fields"],
+ external: ["react", "react-dom", "react-router-dom", "virtual:mercur/config", "virtual:mercur/routes", "virtual:mercur/menu-items", "virtual:mercur/i18n", "virtual:mercur/widgets", "virtual:mercur/navigation", "virtual:mercur/custom-fields", "virtual:mercur/layouts", "virtual:mercur/preferences"],
});
diff --git a/packages/cli/src/commands/dashboard-build.ts b/packages/cli/src/commands/dashboard-build.ts
index fb86c27ae..f2539ae22 100644
--- a/packages/cli/src/commands/dashboard-build.ts
+++ b/packages/cli/src/commands/dashboard-build.ts
@@ -1,3 +1,4 @@
+import fs from "fs";
import path from "path";
import { handleError } from "@/src/utils/handle-error";
import {
@@ -13,7 +14,7 @@ const APPS: DashboardApp[] = ["admin", "vendor"];
export const dashboardBuild = new Command()
.name("dashboard:build")
.description(
- "build a dashboard extensions entry (routes, widgets, custom fields, i18n) from a source directory"
+ "build a dashboard extensions entry (routes, widgets, custom fields, layouts, i18n) from a source directory"
)
.option(
"-c, --cwd <cwd>",
@@ -21,8 +22,11 @@ export const dashboardBuild = new Command()
process.cwd()
)
.option("-a, --app <app>", "which panel the entry targets (admin|vendor)", "admin")
- .option("-s, --src <src>", "source directory to crawl", "src")
- .option("-o, --out <out>", "output file", "dist/admin-extensions.mjs")
+ .option(
+ "-s, --src <src>",
+ "source directory to crawl. defaults to src/<app> when it exists, else src."
+ )
+ .option("-o, --out <out>", "output file. defaults to dist/<app>-extensions.mjs.")
.option("-w, --watch", "rebuild on change", false)
.action(async (opts) => {
try {
@@ -33,12 +37,17 @@ export const dashboardBuild = new Command()
process.exit(1);
}
+ const srcDir =
+ opts.src ??
+ (fs.existsSync(path.join(cwd, "src", opts.app)) ? path.join("src", opts.app) : "src");
+ const outFile = opts.out ?? `dist/${opts.app}-extensions.mjs`;
+
const buildSpinner = spinner(`Building ${opts.app} extensions...`);
const ok = await buildDashboardExtensions({
root: cwd,
- srcDir: opts.src,
- outFile: opts.out,
+ srcDir,
+ outFile,
watch: opts.watch,
});
diff --git a/packages/dashboard-sdk/src/__tests__/layers.spec.ts b/packages/dashboard-sdk/src/__tests__/layers.spec.ts
new file mode 100644
index 000000000..d9457f3fc
--- /dev/null
+++ b/packages/dashboard-sdk/src/__tests__/layers.spec.ts
@@ -0,0 +1,124 @@
+import fs from "fs"
+import os from "os"
+import path from "path"
+import { afterEach, describe, expect, test } from "vitest"
+import { generateRoutes } from "../routes"
+import { generateWidgets } from "../widgets"
+import { generateNavigation } from "../navigation"
+import { generatePreferences } from "../preferences-module"
+import { generatePluginEntryModule } from "../generate-plugin-entry"
+import type { BuiltMercurConfig } from "../types"
+
+const tmpDirs: string[] = []
+
+const makeDir = () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mercur-layers-"))
+ tmpDirs.push(dir)
+ return dir
+}
+
+const write = (file: string, source: string) => {
+ fs.mkdirSync(path.dirname(file), { recursive: true })
+ fs.writeFileSync(file, source)
+}
+
+const evaluate = async (code: string, root: string, name: string) => {
+ const out = path.join(root, `${name}.ts`)
+ fs.writeFileSync(out, code)
+ return import(out)
+}
+
+const page = (label: string) => `
+export const config = { label: "${label}" }
+export default function Page() { return null }
+`
+
+afterEach(() => {
+ for (const dir of tmpDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true })
+})
+
+describe("layers", () => {
+ test("routes are emitted plugin, project, host; later layers last", async () => {
+ const root = makeDir()
+ const pluginSrc = path.join(root, "plugin", "src", "admin")
+ write(path.join(pluginSrc, "routes", "disputes", "page.tsx"), page("Disputes"))
+ const plugin = path.join(root, "plugin-entry.ts")
+ fs.writeFileSync(plugin, generatePluginEntryModule(pluginSrc))
+
+ const projectDir = path.join(root, "api", "src", "admin")
+ write(path.join(projectDir, "routes", "disputes", "page.tsx"), page("Project disputes"))
+ const srcDir = path.join(root, "host", "src")
+ write(path.join(srcDir, "routes", "reports", "page.tsx"), page("Reports"))
+
+ const config = { srcDir, projectDir, pluginExtensions: [plugin] } as BuiltMercurConfig
+ const { customRoutes } = await evaluate(generateRoutes(config), root, "routes")
+
+ expect(customRoutes.map((r: { path: string }) => r.path)).toEqual([
+ "/disputes",
+ "/disputes",
+ "/reports",
+ ])
+ })
+
+ test("a later widget with the same id replaces the earlier one", async () => {
+ const root = makeDir()
+ const pluginSrc = path.join(root, "plugin", "src", "admin")
+ write(
+ path.join(pluginSrc, "widgets", "a.tsx"),
+ `export const config = { zone: "product.detail", id: "seller", order: -1 }
+export default function PluginWidget() { return null }`
+ )
+ const plugin = path.join(root, "plugin-entry.ts")
+ fs.writeFileSync(plugin, generatePluginEntryModule(pluginSrc))
+
+ const srcDir = path.join(root, "host", "src")
+ write(
+ path.join(srcDir, "widgets", "b.tsx"),
+ `export const config = { zone: "product.detail.side", id: "seller", replace: "core:ProductGeneralSection" }
+export default function HostWidget() { return null }`
+ )
+
+ const config = { srcDir, pluginExtensions: [plugin] } as BuiltMercurConfig
+ const { widgets } = (await evaluate(generateWidgets(config), root, "widgets")).default
+
+ expect(widgets).toHaveLength(1)
+ expect(widgets[0]).toMatchObject({
+ widgetId: "seller",
+ zone: ["product.detail.side"],
+ replace: "core:ProductGeneralSection",
+ })
+ expect(widgets[0].Component.name).toBe("HostWidget")
+ })
+
+ test("navigation merges per id across layers and preferences stack in order", async () => {
+ const root = makeDir()
+ const pluginSrc = path.join(root, "plugin", "src", "admin")
+ write(
+ path.join(pluginSrc, "_navigation.ts"),
+ `export default { groups: [{ id: "finance", label: "Finance" }], items: [{ id: "payouts", group: "finance", rank: 2 }] }`
+ )
+ write(
+ path.join(pluginSrc, "_layouts.ts"),
+ `export default { "product.detail": { entries: { "core:ProductMediaSection": { hidden: true } } } }`
+ )
+ const plugin = path.join(root, "plugin-entry.ts")
+ fs.writeFileSync(plugin, generatePluginEntryModule(pluginSrc))
+
+ const srcDir = path.join(root, "host", "src")
+ write(path.join(srcDir, "_navigation.ts"), `export default { items: [{ id: "payouts", hidden: true }] }`)
+ write(path.join(srcDir, "_layouts.ts"), `export default { "nav.main": { entries: { "nav:/orders": { order: 0 } } } }`)
+
+ const config = { srcDir, pluginExtensions: [plugin] } as BuiltMercurConfig
+ const navigation = (await evaluate(generateNavigation(config), root, "navigation")).default
+ expect(navigation).toEqual({
+ groups: [{ id: "finance", label: "Finance" }],
+ items: [{ id: "payouts", group: "finance", rank: 2, hidden: true }],
+ })
+
+ const { layers } = (await evaluate(generatePreferences(config), root, "preferences")).default
+ expect(layers).toEqual([
+ { "product.detail": { entries: { "core:ProductMediaSection": { hidden: true } } } },
+ { "nav.main": { entries: { "nav:/orders": { order: 0 } } } },
+ ])
+ })
+})
diff --git a/packages/dashboard-sdk/src/babel.ts b/packages/dashboard-sdk/src/babel.ts
index d6977d020..40b5e1172 100644
--- a/packages/dashboard-sdk/src/babel.ts
+++ b/packages/dashboard-sdk/src/babel.ts
@@ -13,6 +13,7 @@ import {
isVariableDeclaration,
isVariableDeclarator,
isArrayExpression,
+ isUnaryExpression,
} from "@babel/types"
let traverse: typeof _traverse
@@ -37,4 +38,5 @@ export {
isVariableDeclaration,
isVariableDeclarator,
isArrayExpression,
+ isUnaryExpression,
}
diff --git a/packages/dashboard-sdk/src/config/index.ts b/packages/dashboard-sdk/src/config/index.ts
index 6820f94cf..d47fc66d5 100644
--- a/packages/dashboard-sdk/src/config/index.ts
+++ b/packages/dashboard-sdk/src/config/index.ts
@@ -1,7 +1,11 @@
export * from "./types"
export * from "./custom-fields"
+export * from "./layouts"
export {
defineWidgetConfig,
defineNavigationConfig,
defineCustomFieldsConfig,
+ defineRouteConfig,
+ defineLayoutConfig,
+ defineLayoutPreferences,
} from "./utils"
diff --git a/packages/dashboard-sdk/src/config/layouts.ts b/packages/dashboard-sdk/src/config/layouts.ts
new file mode 100644
index 000000000..3eb1bcd5e
--- /dev/null
+++ b/packages/dashboard-sdk/src/config/layouts.ts
@@ -0,0 +1,95 @@
+import type { ComponentType, ReactNode } from "react"
+
+export const CORE_LAYOUT_IDS = {
+ SINGLE_COLUMN: "core:single-column",
+ TWO_COLUMN: "core:two-column",
+} as const
+
+export type LayoutSection = {
+ id: string
+}
+
+/**
+ * Maps each layout id to the union of section names it renders, so a page's
+ * `sections` prop is checked against the layout it picked. A plugin layout
+ * registers its sections by augmenting this interface:
+ *
+ * @example
+ * declare module "@mercurjs/dashboard-sdk" {
+ * interface LayoutSectionRegistry {
+ * "erp:three-column": "main" | "left" | "right"
+ * }
+ * }
+ */
+export interface LayoutSectionRegistry {
+ [CORE_LAYOUT_IDS.SINGLE_COLUMN]: "main"
+ [CORE_LAYOUT_IDS.TWO_COLUMN]: "main" | "side"
+}
+
+export type Layouts = keyof LayoutSectionRegistry
+
+export type SectionNameFor<TLayoutId extends Layouts> =
+ LayoutSectionRegistry[TLayoutId]
+
+export type LayoutComponentProps = {
+ sections: Record<string, ReactNode>
+ data?: unknown
+ className?: string
+}
+
+export type LayoutConfig = {
+ /** Namespaced id, e.g. `erp:three-column`. `core:` is reserved. */
+ id: string
+ sections: LayoutSection[]
+ Component: ComponentType<LayoutComponentProps>
+}
+
+/**
+ * Entry ids a page exposes: `core:<Entry id>` for its own sections,
+ * `widget:<widget id>` for injected widgets, `nav:<path>` for sidebar items.
+ * Panels seed the built-in ids through `extension-targets`.
+ */
+export interface LayoutEntryRegistry {}
+
+export type LayoutEntryId = keyof LayoutEntryRegistry extends never
+ ? string
+ : keyof LayoutEntryRegistry
+
+export type EntryPreference = {
+ hidden?: boolean
+ /** Move the entry to another section of the page's layout. */
+ section?: string
+ /** Sort order within the section; entries without one keep source order at 0. */
+ order?: number
+ /** Sidebar entries only: i18n key or literal replacing the label. */
+ label?: string
+ /** Sidebar entries only: icon component replacing the icon. */
+ icon?: ComponentType
+ /** Sidebar entries only: re-parent under another item, `null` promotes to top level. */
+ parent?: string | null
+}
+
+export type NavGroupPreference = {
+ id: string
+ label?: string
+ translationNs?: string
+ rank?: number
+ hidden?: boolean
+}
+
+export type ZonePreference = {
+ entries?: Record<string, EntryPreference>
+ /** Sidebar zones (`nav.main`, `nav.settings`) only. */
+ groups?: NavGroupPreference[]
+}
+
+/**
+ * Code-level layout preferences, one object per zone prefix. Declared in a
+ * layer's `_layouts.ts`; later layers override earlier ones field by field.
+ */
+export type LayoutPreferences = Record<string, ZonePreference>
+
+export const NAV_ZONES = {
+ MAIN: "nav.main",
+ SETTINGS: "nav.settings",
+} as const
diff --git a/packages/dashboard-sdk/src/config/types.ts b/packages/dashboard-sdk/src/config/types.ts
index 3a9fb8118..ceb8d0c22 100644
--- a/packages/dashboard-sdk/src/config/types.ts
+++ b/packages/dashboard-sdk/src/config/types.ts
@@ -1,5 +1,6 @@
import type { ComponentType } from "react"
import type { Permission } from "../permissions"
+import type { LayoutEntryId } from "./layouts"
/**
* Open registry interfaces. Each panel package ships a generated
@@ -36,15 +37,28 @@ export type NavGroupId = keyof NavGroupRegistry extends never
: keyof NavGroupRegistry
/**
- * A widget is a React component attached to a named zone on a page. The
- * placement (`before | after`) is encoded as the zone-id suffix, so there is no
- * separate rank field — multiple `before`/`after` widgets stack in registration
- * order.
+ * A widget is a React component attached to a named zone on a page. On a
+ * composer page the zone is the page prefix (`product.details`) or one of its
+ * sections (`product.details.side`); `section`, `order` and `replace` place it
+ * among the page's entries. The legacy `before` / `after` zone suffixes still
+ * resolve to the first and last position of the section.
*/
export interface WidgetConfig {
zone: WidgetZoneId | WidgetZoneId[]
/** Stable id; derived from the file path at build time when omitted. */
id?: string
+ /** Section of the page layout to render in; defaults to the zone's section. */
+ section?: string
+ /**
+ * Sort order among the section's entries. Core entries sit at 0, so a
+ * negative order renders before them; unset renders after them.
+ */
+ order?: number
+ /**
+ * Take the place of a page entry (`core:ProductGeneralSection`). The widget
+ * receives `renderDefault` to render what it replaced.
+ */
+ replace?: LayoutEntryId
/**
* Permission(s) the actor needs for the widget to render. With several, any
* one is enough.
diff --git a/packages/dashboard-sdk/src/config/utils.ts b/packages/dashboard-sdk/src/config/utils.ts
index 3fbf1a57c..950696332 100644
--- a/packages/dashboard-sdk/src/config/utils.ts
+++ b/packages/dashboard-sdk/src/config/utils.ts
@@ -3,6 +3,8 @@ import type {
WidgetConfig,
} from "./types"
import type { CustomFieldModel, CustomFieldsConfig } from "./custom-fields"
+import type { LayoutConfig, LayoutPreferences } from "./layouts"
+import type { RouteConfig } from "../types"
/**
* Wraps a declarative config so Vite's Fast Refresh treats the module as a
@@ -32,3 +34,17 @@ export function defineCustomFieldsConfig<TModel extends CustomFieldModel>(
): CustomFieldsConfig<TModel> {
return createConfigHelper(config)
}
+
+export function defineRouteConfig(config: RouteConfig): RouteConfig {
+ return createConfigHelper(config)
+}
+
+export function defineLayoutConfig(config: LayoutConfig): LayoutConfig {
+ return createConfigHelper(config)
+}
+
+export function defineLayoutPreferences(
+ config: LayoutPreferences
+): LayoutPreferences {
+ return config
+}
diff --git a/packages/dashboard-sdk/src/constants.ts b/packages/dashboard-sdk/src/constants.ts
index 66a4cce6d..a29e1d8e8 100644
--- a/packages/dashboard-sdk/src/constants.ts
+++ b/packages/dashboard-sdk/src/constants.ts
@@ -7,6 +7,8 @@ export const I18N_VIRTUAL_MODULE = "virtual:mercur/i18n"
export const WIDGETS_VIRTUAL_MODULE = "virtual:mercur/widgets"
export const NAVIGATION_VIRTUAL_MODULE = "virtual:mercur/navigation"
export const CUSTOM_FIELDS_VIRTUAL_MODULE = "virtual:mercur/custom-fields"
+export const LAYOUTS_VIRTUAL_MODULE = "virtual:mercur/layouts"
+export const PREFERENCES_VIRTUAL_MODULE = "virtual:mercur/preferences"
export const RESOLVED_CONFIG_MODULE = "\0" + CONFIG_VIRTUAL_MODULE
export const RESOLVED_ROUTES_MODULE = "\0" + ROUTES_VIRTUAL_MODULE
@@ -15,6 +17,8 @@ export const RESOLVED_I18N_MODULE = "\0" + I18N_VIRTUAL_MODULE
export const RESOLVED_WIDGETS_MODULE = "\0" + WIDGETS_VIRTUAL_MODULE
export const RESOLVED_NAVIGATION_MODULE = "\0" + NAVIGATION_VIRTUAL_MODULE
export const RESOLVED_CUSTOM_FIELDS_MODULE = "\0" + CUSTOM_FIELDS_VIRTUAL_MODULE
+export const RESOLVED_LAYOUTS_MODULE = "\0" + LAYOUTS_VIRTUAL_MODULE
+export const RESOLVED_PREFERENCES_MODULE = "\0" + PREFERENCES_VIRTUAL_MODULE
export const VIRTUAL_MODULES = [
CONFIG_VIRTUAL_MODULE,
@@ -24,4 +28,11 @@ export const VIRTUAL_MODULES = [
WIDGETS_VIRTUAL_MODULE,
NAVIGATION_VIRTUAL_MODULE,
CUSTOM_FIELDS_VIRTUAL_MODULE,
+ LAYOUTS_VIRTUAL_MODULE,
+ PREFERENCES_VIRTUAL_MODULE,
]
+
+/** The file-name stem of a layer's code-level layout preferences. */
+export const LAYOUT_PREFERENCES_FILE = "_layouts"
+/** The file-name stem of the legacy host-only navigation overrides. */
+export const NAVIGATION_FILE = "_navigation"
diff --git a/packages/dashboard-sdk/src/custom-fields.ts b/packages/dashboard-sdk/src/custom-fields.ts
index caa8b4316..0cf3fd519 100644
--- a/packages/dashboard-sdk/src/custom-fields.ts
+++ b/packages/dashboard-sdk/src/custom-fields.ts
@@ -1,52 +1,20 @@
-import path from "path"
-import { normalizePath, crawlModuleFiles } from "./utils"
+import { emitLayers, spreadLayers } from "./layers"
import type { BuiltMercurConfig } from "./types"
/**
* Custom-field configs carry runtime values (zod validation, render
- * components, default-value resolvers), so — unlike widgets — the emitted
- * module re-exports the actual default-exported config objects rather than a
- * build-time-extracted literal. The runtime `ExtensionRegistry` reads
- * `model` / `link` / `forms` / `displays` / `list` off each object, applying
- * them in array order.
+ * components, default-value resolvers), so the emitted module re-exports the
+ * default-exported config objects in layer order; the runtime
+ * `ExtensionRegistry` keys them so a later config replaces an earlier one.
*/
-export function generateCustomFields({
- srcDir,
- pluginExtensions,
-}: BuiltMercurConfig): string {
- const dir = path.join(srcDir, "custom-fields")
- const files = crawlModuleFiles(dir)
+export function generateCustomFields(config: BuiltMercurConfig): string {
+ const { header, names } = emitLayers(config)
- const imports = files.map(
- (file, i) => `import __cf${i} from "${normalizePath(file)}"`
- )
- const localRefs = files.map((_, i) => `__cf${i}`)
-
- const pluginDeclarations = pluginExtensions.map(
- (ext, i) =>
- `const __plugin${i} = (await import("${normalizePath(ext)}")).default`
- )
- const pluginSpreads = pluginExtensions.map(
- (_, i) => ` ...(__plugin${i}.customFieldsModule?.configs ?? [])`
- )
-
- // Host configs go last so they layer over (and win against) plugin configs.
- const configs = [
- ...pluginSpreads,
- ...localRefs.map((ref) => ` ${ref}`),
- ]
-
- if (configs.length === 0 && pluginDeclarations.length === 0) {
- return `export default { configs: [] }`
- }
-
- return `${imports.join("\n")}
-
-${pluginDeclarations.join("\n")}
+ return `${header}
export default {
configs: [
-${configs.join(",\n")}
+${spreadLayers(names, "customFieldsModule", "configs")}
]
}`
}
diff --git a/packages/dashboard-sdk/src/generate-plugin-entry.ts b/packages/dashboard-sdk/src/generate-plugin-entry.ts
index 917cf5dac..d46202f5a 100644
--- a/packages/dashboard-sdk/src/generate-plugin-entry.ts
+++ b/packages/dashboard-sdk/src/generate-plugin-entry.ts
@@ -1,124 +1,18 @@
-import path from "path"
-import { crawlRoutes, parseFile, buildRouteTree, formatRoute } from "./routes"
-import { parseMenuItemFile, formatMenuItem } from "./menu-items"
-import { collectWidgets } from "./widgets"
-import { normalizePath, crawlModuleFiles } from "./utils"
-import { VALID_FILE_EXTENSIONS } from "./constants"
-import fs from "fs"
-
-function findI18nIndex(srcDir: string): string | null {
- const i18nDir = path.join(srcDir, "i18n")
- if (!fs.existsSync(i18nDir)) return null
-
- for (const ext of VALID_FILE_EXTENSIONS) {
- const filePath = path.join(i18nDir, `index${ext}`)
- if (fs.existsSync(filePath)) return filePath
- }
-
- return null
-}
+import { collectLayer } from "./layers"
/**
- * Generates a plugin entry module for a given source directory (e.g. src/vendor).
- * Scans routes, menu items, and i18n — outputs a single module string
- * that exports default `{ routeModule, menuItemModule, i18nModule }`.
+ * Generates a plugin entry module for a given source directory (e.g.
+ * src/vendor): the same shape the Vite plugin crawls for the project and host
+ * layers, so a prebuilt plugin merges exactly like a source folder.
*/
export function generatePluginEntryModule(srcDir: string): string {
- const routesDir = path.join(srcDir, "routes")
- const files = crawlRoutes(routesDir)
-
- let index = 0
- const routeResults: ReturnType<typeof parseFile>[] = []
- const menuItemResults: ReturnType<typeof parseMenuItemFile>[] = []
-
- for (const file of files) {
- const route = parseFile(file, routesDir, index)
- if (route) {
- routeResults.push(route)
- }
-
- const menuItem = parseMenuItemFile(file, routesDir, index)
- if (menuItem) {
- menuItemResults.push(menuItem)
- }
-
- index++
- }
-
- const routeTree = buildRouteTree(routeResults.filter(Boolean) as any[])
- const routeImports = routeTree.flatMap((r) => r.imports)
- const routes = routeTree.map((r) => formatRoute(r.route))
-
- const menuItemImports = menuItemResults
- .filter(Boolean)
- .map((r) => r!.import)
- const menuItems = menuItemResults
- .filter(Boolean)
- .map((r) => formatMenuItem(r!.menuItem))
-
- // widgets (offset the index namespace so component names don't collide)
- const { imports: widgetImports, entries: widgetEntries } = collectWidgets(
- srcDir,
- index
- )
-
- // custom-fields (aggregate default exports)
- const cfFiles = crawlModuleFiles(path.join(srcDir, "custom-fields"))
- const cfImports = cfFiles.map(
- (file, i) => `import __cf${i} from "${normalizePath(file)}"`
- )
- const cfRefs = cfFiles.map((_, i) => ` __cf${i}`)
-
- // i18n
- const i18nFile = findI18nIndex(srcDir)
- const i18nImport = i18nFile
- ? `import i18nResources from "${normalizePath(i18nFile)}"`
- : ""
- const i18nValue = i18nFile ? "i18nResources" : "{}"
-
- const allImports = [
- ...routeImports,
- ...menuItemImports,
- ...widgetImports,
- ...cfImports,
- ]
- if (i18nImport) allImports.push(i18nImport)
+ const { imports, declaration, name } = collectLayer(srcDir, 0)
return `// Auto-generated plugin extensions entry
-${allImports.join("\n")}
-
-const routeModule = {
- routes: [
-${routes.join(",\n")}
- ]
-}
-
-const menuItemModule = {
- menuItems: [
-${menuItems.join(",\n")}
- ]
-}
+${imports.join("\n")}
-const widgetModule = {
- widgets: [
-${widgetEntries.join(",\n")}
- ]
-}
-
-const customFieldsModule = {
- configs: [
-${cfRefs.join(",\n")}
- ]
-}
-
-const plugin = {
- routeModule,
- menuItemModule,
- widgetModule,
- customFieldsModule,
- i18nModule: ${i18nValue},
-}
+${declaration}
-export default plugin
+export default ${name}
`
}
diff --git a/packages/dashboard-sdk/src/i18n.ts b/packages/dashboard-sdk/src/i18n.ts
index 596243e4c..5b6cc02bf 100644
--- a/packages/dashboard-sdk/src/i18n.ts
+++ b/packages/dashboard-sdk/src/i18n.ts
@@ -1,44 +1,12 @@
-import fs from "fs"
-import path from "path"
-import { VALID_FILE_EXTENSIONS } from "./constants"
-import { normalizePath } from "./utils"
+import { emitLayers } from "./layers"
import type { BuiltMercurConfig } from "./types"
-function findI18nIndex(srcDir: string): string | null {
- const i18nDir = path.join(srcDir, "i18n")
-
- if (!fs.existsSync(i18nDir)) {
- return null
- }
-
- for (const ext of VALID_FILE_EXTENSIONS) {
- const filePath = path.join(i18nDir, `index${ext}`)
- if (fs.existsSync(filePath)) {
- return filePath
- }
- }
-
- return null
-}
-
-export function generateI18n({ srcDir, pluginExtensions }: BuiltMercurConfig): string {
- const indexFile = findI18nIndex(srcDir)
-
- const imports = [
- ...(indexFile ? [`import appI18n from "${normalizePath(indexFile)}"`] : []),
- ...pluginExtensions.map(
- (ext, i) => `import __plugin${i} from "${normalizePath(ext)}"`
- ),
- ]
-
- // Plugins first, app last, so the host can override a plugin's copy.
- const sources = [
- ...pluginExtensions.map((_, i) => `(__plugin${i}.i18nModule ?? {})`),
- ...(indexFile ? ["appI18n"] : []),
- ]
+/** Deep-merged in layer order, so a later layer overrides a plugin's copy. */
+export function generateI18n(config: BuiltMercurConfig): string {
+ const { header, names } = emitLayers(config)
// deepMerge is inlined because the virtual module has no runtime dependency on @mercurjs/admin.
- return `${imports.join("\n")}
+ return `${header}
function deepMerge(target, source) {
const result = { ...target }
@@ -64,6 +32,6 @@ function mergeResources(target, source) {
return result
}
-export default [${sources.join(", ")}].reduce(mergeResources, {})
+export default [${names.map((name) => `(${name}.i18nModule ?? {})`).join(", ")}].reduce(mergeResources, {})
`
}
diff --git a/packages/dashboard-sdk/src/layers.ts b/packages/dashboard-sdk/src/layers.ts
new file mode 100644
index 000000000..4b7a49ab3
--- /dev/null
+++ b/packages/dashboard-sdk/src/layers.ts
@@ -0,0 +1,170 @@
+import fs from "fs"
+import path from "path"
+import { crawlRoutes, parseFile, buildRouteTree, formatRoute } from "./routes"
+import { parseMenuItemFile, formatMenuItem } from "./menu-items"
+import { collectWidgets } from "./widgets"
+import { normalizePath, crawlModuleFiles } from "./utils"
+import { LAYOUT_PREFERENCES_FILE, NAVIGATION_FILE, VALID_FILE_EXTENSIONS } from "./constants"
+import type { BuiltMercurConfig } from "./types"
+
+/**
+ * Where a layer's extensions come from: a prebuilt plugin entry module, or a
+ * source folder crawled at build time (the Medusa project's `src/<app>` and the
+ * host app's `src`).
+ */
+export type LayerSource = { entry: string } | { srcDir: string }
+
+export function layerSources({
+ pluginExtensions,
+ projectDir,
+ srcDir,
+}: Pick<BuiltMercurConfig, "pluginExtensions" | "projectDir" | "srcDir">): LayerSource[] {
+ return [
+ ...pluginExtensions.map((entry) => ({ entry })),
+ ...(projectDir ? [{ srcDir: projectDir }] : []),
+ { srcDir },
+ ]
+}
+
+function findFile(dir: string, stem: string): string | null {
+ for (const ext of VALID_FILE_EXTENSIONS) {
+ const file = path.join(dir, `${stem}${ext}`)
+ if (fs.existsSync(file)) return file
+ }
+ return null
+}
+
+export type CollectedLayer = {
+ imports: string[]
+ /** Declares `const <name> = { routeModule, menuItemModule, ... }`. */
+ declaration: string
+ name: string
+ nextIndex: number
+}
+
+/**
+ * Crawls one source folder into the same shape a prebuilt plugin entry exports,
+ * so every layer merges the same way. Identifiers carry the layer index so
+ * several crawled layers can share one module.
+ */
+export function collectLayer(srcDir: string, layer: number, startIndex = 0): CollectedLayer {
+ const name = `__layer${layer}`
+ const routesDir = path.join(srcDir, "routes")
+
+ let index = startIndex
+ const routeResults: NonNullable<ReturnType<typeof parseFile>>[] = []
+ const menuItemResults: NonNullable<ReturnType<typeof parseMenuItemFile>>[] = []
+
+ for (const file of crawlRoutes(routesDir)) {
+ const route = parseFile(file, routesDir, index)
+ if (route) routeResults.push(route)
+
+ const menuItem = parseMenuItemFile(file, routesDir, index)
+ if (menuItem) menuItemResults.push(menuItem)
+
+ index++
+ }
+
+ const routeTree = buildRouteTree(routeResults)
+ const routeImports = routeTree.flatMap((r) => r.imports)
+ const routes = routeTree.map((r) => formatRoute(r.route))
+
+ const menuItemImports = menuItemResults.map((r) => r.import)
+ const menuItems = menuItemResults.map((r) => formatMenuItem(r.menuItem))
+
+ const widgets = collectWidgets(srcDir, index)
+ index += widgets.entries.length
+
+ const cfFiles = crawlModuleFiles(path.join(srcDir, "custom-fields"))
+ const cfImports = cfFiles.map(
+ (file, i) => `import __cf${layer}_${i} from "${normalizePath(file)}"`
+ )
+ const cfRefs = cfFiles.map((_, i) => ` __cf${layer}_${i}`)
+
+ const layoutFiles = crawlModuleFiles(path.join(srcDir, "layouts"))
+ const layoutImports = layoutFiles.map(
+ (file, i) => `import __layout${layer}_${i} from "${normalizePath(file)}"`
+ )
+ const layoutRefs = layoutFiles.map((_, i) => ` __layout${layer}_${i}`)
+
+ const i18nFile = findFile(path.join(srcDir, "i18n"), "index")
+ const i18nName = `__i18n${layer}`
+ const navigationFile = findFile(srcDir, NAVIGATION_FILE)
+ const navigationName = `__navigation${layer}`
+ const preferencesFile = findFile(srcDir, LAYOUT_PREFERENCES_FILE)
+ const preferencesName = `__preferences${layer}`
+
+ const imports = [
+ ...routeImports,
+ ...menuItemImports,
+ ...widgets.imports,
+ ...cfImports,
+ ...layoutImports,
+ ...(i18nFile ? [`import ${i18nName} from "${normalizePath(i18nFile)}"`] : []),
+ ...(navigationFile
+ ? [`import ${navigationName} from "${normalizePath(navigationFile)}"`]
+ : []),
+ ...(preferencesFile
+ ? [`import ${preferencesName} from "${normalizePath(preferencesFile)}"`]
+ : []),
+ ]
+
+ const declaration = `const ${name} = {
+ routeModule: { routes: [
+${routes.join(",\n")}
+ ] },
+ menuItemModule: { menuItems: [
+${menuItems.join(",\n")}
+ ] },
+ widgetModule: { widgets: [
+${widgets.entries.join(",\n")}
+ ] },
+ customFieldsModule: { configs: [
+${cfRefs.join(",\n")}
+ ] },
+ layoutModule: { layouts: [
+${layoutRefs.join(",\n")}
+ ] },
+ i18nModule: ${i18nFile ? i18nName : "{}"},
+ navigationModule: ${navigationFile ? navigationName : "{}"},
+ preferenceModule: ${preferencesFile ? preferencesName : "{}"},
+}`
+
+ return { imports, declaration, name, nextIndex: index }
+}
+
+export type EmittedLayers = {
+ /** Import statements and crawled-layer declarations, in layer order. */
+ header: string
+ /** Identifiers that each evaluate to a layer's entry object, in layer order. */
+ names: string[]
+}
+
+export function emitLayers(config: Pick<BuiltMercurConfig, "pluginExtensions" | "projectDir" | "srcDir">): EmittedLayers {
+ const lines: string[] = []
+ const declarations: string[] = []
+ const names: string[] = []
+ let index = 0
+
+ layerSources(config).forEach((source, layer) => {
+ if ("entry" in source) {
+ const name = `__layer${layer}`
+ lines.push(`import ${name} from "${normalizePath(source.entry)}"`)
+ names.push(name)
+ return
+ }
+
+ const collected = collectLayer(source.srcDir, layer, index)
+ index = collected.nextIndex
+ lines.push(...collected.imports)
+ declarations.push(collected.declaration)
+ names.push(collected.name)
+ })
+
+ return { header: [...lines, ...declarations].join("\n"), names }
+}
+
+/** `[...(a.key?.list ?? []), ...]` across layers, in order. */
+export function spreadLayers(names: string[], key: string, list: string): string {
+ return names.map((name) => ` ...(${name}.${key}?.${list} ?? [])`).join(",\n")
+}
diff --git a/packages/dashboard-sdk/src/layouts-module.ts b/packages/dashboard-sdk/src/layouts-module.ts
new file mode 100644
index 000000000..45c6ca643
--- /dev/null
+++ b/packages/dashboard-sdk/src/layouts-module.ts
@@ -0,0 +1,18 @@
+import { emitLayers, spreadLayers } from "./layers"
+import type { BuiltMercurConfig } from "./types"
+
+/** A later layout with the same id replaces the earlier one; `core:` ids are reserved. */
+export function generateLayouts(config: BuiltMercurConfig): string {
+ const { header, names } = emitLayers(config)
+
+ return `${header}
+
+const byId = new Map()
+for (const layout of [
+${spreadLayers(names, "layoutModule", "layouts")}
+]) {
+ if (layout?.id) byId.set(layout.id, layout)
+}
+
+export default { layouts: [...byId.values()] }`
+}
diff --git a/packages/dashboard-sdk/src/menu-items.ts b/packages/dashboard-sdk/src/menu-items.ts
index 214a7d6c2..e22a494d0 100644
--- a/packages/dashboard-sdk/src/menu-items.ts
+++ b/packages/dashboard-sdk/src/menu-items.ts
@@ -1,5 +1,4 @@
import fs from "fs"
-import path from "path"
import { VALID_FILE_EXTENSIONS } from "./constants"
import { normalizePath, getParserOptions } from "./utils"
import {
@@ -15,6 +14,7 @@ import {
isObjectExpression,
isBooleanLiteral,
} from "./babel"
+import { emitLayers, spreadLayers } from "./layers"
import type { BuiltMercurConfig } from "./types"
type MenuItemConfig = {
@@ -45,33 +45,6 @@ type MenuItemResult = {
menuItem: MenuItem
}
-function crawlRoutes(dir: string, pattern = "page"): string[] {
- const files: string[] = []
-
- if (!fs.existsSync(dir)) {
- return files
- }
-
- const entries = fs.readdirSync(dir, { withFileTypes: true })
-
- for (const entry of entries) {
- const fullPath = path.join(dir, entry.name)
-
- if (entry.isDirectory()) {
- files.push(...crawlRoutes(fullPath, pattern))
- } else if (entry.isFile()) {
- const ext = path.extname(entry.name)
- const baseName = path.basename(entry.name, ext)
-
- if (baseName === pattern && VALID_FILE_EXTENSIONS.includes(ext)) {
- files.push(fullPath)
- }
- }
- }
-
- return files
-}
-
function getRoute(file: string, routesDir: string): string {
const importPath = normalizePath(file)
const normalizedRoutesDir = normalizePath(routesDir)
@@ -301,47 +274,18 @@ export function parseMenuItemFile(
}
}
-export function generateMenuItems({ srcDir, pluginExtensions }: BuiltMercurConfig): string {
- const routesDir = path.join(srcDir, "routes")
-
- let index = 0
- const results: MenuItemResult[] = []
+/** Later layers win: a menu item at a path already declared replaces it. */
+export function generateMenuItems(config: BuiltMercurConfig): string {
+ const { header, names } = emitLayers(config)
- // App's own routes
- for (const file of crawlRoutes(routesDir)) {
- const result = parseMenuItemFile(file, routesDir, index)
- if (result) {
- results.push(result)
- index++
- }
- }
-
- // Plugin extensions. Static rather than `await import(...)`: a top-level
- // await here would force every consuming app to raise its build target.
- const pluginDeclarations = pluginExtensions.map((ext, i) =>
- `import __plugin${i} from "${normalizePath(ext)}"`
- )
- const pluginSpreads = pluginExtensions.map((_, i) =>
- ` ...(__plugin${i}.menuItemModule?.menuItems ?? [])`
- )
-
- const appImports = results.map((r) => r.import)
- const appMenuItems = results.map((r) => formatMenuItem(r.menuItem))
+ return `${header}
- const allImports = [...appImports]
- const allMenuItems = [...appMenuItems, ...pluginSpreads]
-
- if (allImports.length === 0 && pluginDeclarations.length === 0 && allMenuItems.length === 0) {
- return `export default { menuItems: [] }`
- }
-
- return `${allImports.join("\n")}
-
-${pluginDeclarations.join("\n")}
+const byPath = new Map()
+for (const item of [
+${spreadLayers(names, "menuItemModule", "menuItems")}
+]) {
+ byPath.set(item.path, item)
+}
-export default {
- menuItems: [
-${allMenuItems.join(",\n")}
- ]
-}`
+export default { menuItems: [...byPath.values()] }`
}
diff --git a/packages/dashboard-sdk/src/navigation.ts b/packages/dashboard-sdk/src/navigation.ts
index f7427fb10..15ef4d6ab 100644
--- a/packages/dashboard-sdk/src/navigation.ts
+++ b/packages/dashboard-sdk/src/navigation.ts
@@ -1,30 +1,25 @@
-import fs from "fs"
-import path from "path"
-import { VALID_FILE_EXTENSIONS } from "./constants"
-import { normalizePath } from "./utils"
+import { emitLayers } from "./layers"
import type { BuiltMercurConfig } from "./types"
/**
- * Navigation overrides are a single host-owned file `src/_navigation.ts`,
- * discovered like `src/i18n/index.*` (one file, not a folder crawl). Installed
- * blocks cannot contribute nav overrides — the sidebar order/visibility is a
- * deliberate host-only single source of truth, so there is no plugin-entry slot.
+ * `_navigation.ts` overrides from every layer, merged in order: groups and
+ * items with the same id are combined field by field, later layers winning.
*/
-function findNavigationFile(srcDir: string): string | null {
- for (const ext of VALID_FILE_EXTENSIONS) {
- const filePath = path.join(srcDir, `_navigation${ext}`)
- if (fs.existsSync(filePath)) return filePath
- }
- return null
-}
+export function generateNavigation(config: BuiltMercurConfig): string {
+ const { header, names } = emitLayers(config)
-export function generateNavigation({ srcDir }: BuiltMercurConfig): string {
- const file = findNavigationFile(srcDir)
+ return `${header}
- if (!file) {
- return `export default { items: [] }`
+const groups = new Map()
+const items = new Map()
+for (const navigation of [${names.map((name) => `${name}.navigationModule ?? {}`).join(", ")}]) {
+ for (const group of navigation.groups ?? []) {
+ if (group?.id) groups.set(group.id, { ...(groups.get(group.id) ?? {}), ...group })
}
+ for (const item of navigation.items ?? []) {
+ if (item?.id) items.set(item.id, { ...(items.get(item.id) ?? {}), ...item })
+ }
+}
- return `import navigationConfig from "${normalizePath(file)}"
-export default navigationConfig`
+export default { groups: [...groups.values()], items: [...items.values()] }`
}
diff --git a/packages/dashboard-sdk/src/plugin.ts b/packages/dashboard-sdk/src/plugin.ts
index 6a473e0a0..717024daa 100644
--- a/packages/dashboard-sdk/src/plugin.ts
+++ b/packages/dashboard-sdk/src/plugin.ts
@@ -4,10 +4,17 @@ import fs from "fs";
import { createRequire } from "module";
import { getFileExports } from "./utils";
import {
+ LAYOUT_PREFERENCES_FILE,
+ NAVIGATION_FILE,
RESOLVED_ROUTES_MODULE,
+ RESOLVED_MENU_ITEMS_MODULE,
RESOLVED_WIDGETS_MODULE,
RESOLVED_NAVIGATION_MODULE,
RESOLVED_CUSTOM_FIELDS_MODULE,
+ RESOLVED_LAYOUTS_MODULE,
+ RESOLVED_PREFERENCES_MODULE,
+ RESOLVED_I18N_MODULE,
+ VIRTUAL_MODULES,
} from "./constants";
import {
isVirtualModule,
@@ -27,13 +34,51 @@ function isWidgetFile(file: string): boolean {
function isNavigationFile(file: string): boolean {
const basename = path.basename(file, path.extname(file));
- return basename === "_navigation";
+ return basename === NAVIGATION_FILE;
+}
+
+function isPreferencesFile(file: string): boolean {
+ const basename = path.basename(file, path.extname(file));
+ return basename === LAYOUT_PREFERENCES_FILE;
}
function isCustomFieldFile(file: string): boolean {
return normalizeSep(file).includes("/src/custom-fields/");
}
+function isLayoutFile(file: string): boolean {
+ return normalizeSep(file).includes("/layouts/");
+}
+
+function isI18nFile(file: string): boolean {
+ return normalizeSep(file).includes("/i18n/");
+}
+
+// Every virtual module reads every layer, so a change in one kind of file
+// invalidates them all; the cost is one re-crawl per edit.
+const LAYERED_MODULES = [
+ RESOLVED_ROUTES_MODULE,
+ RESOLVED_MENU_ITEMS_MODULE,
+ RESOLVED_WIDGETS_MODULE,
+ RESOLVED_NAVIGATION_MODULE,
+ RESOLVED_CUSTOM_FIELDS_MODULE,
+ RESOLVED_LAYOUTS_MODULE,
+ RESOLVED_PREFERENCES_MODULE,
+ RESOLVED_I18N_MODULE,
+];
+
+function isExtensionFile(file: string): boolean {
+ return (
+ isRouteFile(file) ||
+ isWidgetFile(file) ||
+ isNavigationFile(file) ||
+ isPreferencesFile(file) ||
+ isCustomFieldFile(file) ||
+ isLayoutFile(file) ||
+ isI18nFile(file)
+ );
+}
+
function normalizeSep(file: string): string {
return file.replace(/\\/g, "/");
}
@@ -202,6 +247,7 @@ async function loadMedusaConfig(
): Promise<{
base?: string;
pluginExtensions: string[];
+ projectDir?: string;
vendorAppUrl?: string;
}> {
const configDir = path.dirname(medusaConfigPath);
@@ -264,7 +310,15 @@ async function loadMedusaConfig(
) ?? [];
const pluginExtensions = resolvePluginExtensions(plugins, configDir, appType);
- return { base, pluginExtensions, vendorAppUrl };
+ // The Medusa project's own panel extensions live beside its backend code,
+ // as `src/admin` does for Medusa's admin.
+ const projectCandidate = path.join(configDir, "src", appType);
+ const projectDir =
+ fs.existsSync(projectCandidate) && fs.realpathSync(projectCandidate) !== root
+ ? projectCandidate
+ : undefined;
+
+ return { base, pluginExtensions, projectDir, vendorAppUrl };
} catch (error) {
// Don't fail the build — but never fail silently either: without the Medusa config
// the panel is built with base "/" and no plugin extensions, and a panel served
@@ -295,7 +349,7 @@ export function mercurDashboardPlugin(pluginConfig: MercurConfig): Vite.Plugin {
root,
pluginConfig.medusaConfigPath,
);
- const { base, pluginExtensions, vendorAppUrl } = await loadMedusaConfig(
+ const { base, pluginExtensions, projectDir, vendorAppUrl } = await loadMedusaConfig(
medusaConfigPath,
root,
{
@@ -314,6 +368,7 @@ export function mercurDashboardPlugin(pluginConfig: MercurConfig): Vite.Plugin {
base,
root,
srcDir,
+ projectDir,
pluginExtensions,
imageLimit,
};
@@ -329,16 +384,7 @@ export function mercurDashboardPlugin(pluginConfig: MercurConfig): Vite.Plugin {
dedupe: ["i18next", "react-i18next", "react", "react-dom"],
},
optimizeDeps: {
- exclude: [
- "virtual:mercur/config",
- "virtual:mercur/routes",
- "virtual:mercur/menu-items",
- "virtual:mercur/i18n",
- "virtual:mercur/widgets",
- "virtual:mercur/navigation",
- "virtual:mercur/custom-fields",
- ...MEDUSA_VIRTUAL_MODULES,
- ],
+ exclude: [...VIRTUAL_MODULES, ...MEDUSA_VIRTUAL_MODULES],
include: filterResolvableDeps(
[
"react",
@@ -385,10 +431,9 @@ export function mercurDashboardPlugin(pluginConfig: MercurConfig): Vite.Plugin {
};
const handleChange = (file: string) => {
- if (isRouteFile(file)) invalidate(RESOLVED_ROUTES_MODULE, true);
- if (isWidgetFile(file)) invalidate(RESOLVED_WIDGETS_MODULE, true);
- if (isNavigationFile(file)) invalidate(RESOLVED_NAVIGATION_MODULE, true);
- if (isCustomFieldFile(file)) invalidate(RESOLVED_CUSTOM_FIELDS_MODULE, true);
+ if (!isExtensionFile(file)) return;
+ for (const moduleId of LAYERED_MODULES) invalidate(moduleId, false);
+ server.ws.send({ type: "full-reload" });
};
server.watcher.on("add", handleChange);
@@ -400,10 +445,8 @@ export function mercurDashboardPlugin(pluginConfig: MercurConfig): Vite.Plugin {
if (mod) server.moduleGraph.invalidateModule(mod);
};
- if (isRouteFile(file)) invalidate(RESOLVED_ROUTES_MODULE);
- if (isWidgetFile(file)) invalidate(RESOLVED_WIDGETS_MODULE);
- if (isNavigationFile(file)) invalidate(RESOLVED_NAVIGATION_MODULE);
- if (isCustomFieldFile(file)) invalidate(RESOLVED_CUSTOM_FIELDS_MODULE);
+ if (!isExtensionFile(file)) return;
+ for (const moduleId of LAYERED_MODULES) invalidate(moduleId);
},
};
}
diff --git a/packages/dashboard-sdk/src/preferences-module.ts b/packages/dashboard-sdk/src/preferences-module.ts
new file mode 100644
index 000000000..0ec2be589
--- /dev/null
+++ b/packages/dashboard-sdk/src/preferences-module.ts
@@ -0,0 +1,14 @@
+import { emitLayers } from "./layers"
+import type { BuiltMercurConfig } from "./types"
+
+/**
+ * One `_layouts.ts` preference object per layer, in order. Merging happens in
+ * the runtime registry, field by field per zone entry, later layers winning.
+ */
+export function generatePreferences(config: BuiltMercurConfig): string {
+ const { header, names } = emitLayers(config)
+
+ return `${header}
+
+export default { layers: [${names.map((name) => `${name}.preferenceModule ?? {}`).join(", ")}] }`
+}
diff --git a/packages/dashboard-sdk/src/routes.ts b/packages/dashboard-sdk/src/routes.ts
index 70a1de079..c778bcb1d 100644
--- a/packages/dashboard-sdk/src/routes.ts
+++ b/packages/dashboard-sdk/src/routes.ts
@@ -11,6 +11,7 @@ import {
isVariableDeclaration,
isVariableDeclarator,
} from "./babel"
+import { emitLayers, spreadLayers } from "./layers"
import type { BuiltMercurConfig } from "./types"
type Route = {
@@ -277,46 +278,17 @@ export function buildRouteTree(results: RouteResult[]): RouteResult[] {
return Array.from(routeMap.values())
}
-export function generateRoutes({ srcDir, pluginExtensions }: BuiltMercurConfig): string {
- const routesDir = path.join(srcDir, "routes")
+/**
+ * Routes are emitted in layer order, plugins first and the host app last. A
+ * later route at the same path overrides the earlier one; the panel resolves
+ * the override and hands the overridden page to the new one as `renderDefault`.
+ */
+export function generateRoutes(config: BuiltMercurConfig): string {
+ const { header, names } = emitLayers(config)
- let index = 0
- const results: RouteResult[] = []
-
- // App's own routes
- for (const file of crawlRoutes(routesDir)) {
- const result = parseFile(file, routesDir, index)
- if (result) {
- results.push(result)
- index++
- }
- }
-
- // Plugin extensions. Static rather than `await import(...)`: a top-level
- // await here would force every consuming app to raise its build target.
- const pluginDeclarations = pluginExtensions.map((ext, i) =>
- `import __plugin${i} from "${normalizePath(ext)}"`
- )
- const pluginSpreads = pluginExtensions.map((_, i) =>
- ` ...(__plugin${i}.routeModule?.routes ?? [])`
- )
-
- const routeTree = buildRouteTree(results)
- const appImports = routeTree.flatMap((r) => r.imports)
- const appRoutes = routeTree.map((r) => formatRoute(r.route))
-
- const allImports = [...appImports]
- const allRoutes = [...appRoutes, ...pluginSpreads]
-
- if (allImports.length === 0 && pluginDeclarations.length === 0 && allRoutes.length === 0) {
- return `export const customRoutes = []`
- }
-
- return `${allImports.join("\n")}
-
-${pluginDeclarations.join("\n")}
+ return `${header}
export const customRoutes = [
-${allRoutes.join(",\n")}
+${spreadLayers(names, "routeModule", "routes")}
]`
}
diff --git a/packages/dashboard-sdk/src/types.ts b/packages/dashboard-sdk/src/types.ts
index 1e61376c8..ba66b8696 100644
--- a/packages/dashboard-sdk/src/types.ts
+++ b/packages/dashboard-sdk/src/types.ts
@@ -61,7 +61,14 @@ export interface BuiltMercurConfig extends MercurConfig {
backendUrl: string;
base?: string;
root: string
+ /** The host app's own `src`, crawled as the last layer. */
srcDir: string
+ /**
+ * The Medusa project's `src/<admin|vendor>`, crawled as the layer between
+ * the plugins and the host app. Unset when the folder does not exist.
+ */
+ projectDir?: string
+ /** Prebuilt plugin entries, in `medusa-config` plugin order. */
pluginExtensions: string[]
imageLimit: number
}
diff --git a/packages/dashboard-sdk/src/virtual-modules.ts b/packages/dashboard-sdk/src/virtual-modules.ts
index da097aa57..0b6f6ed12 100644
--- a/packages/dashboard-sdk/src/virtual-modules.ts
+++ b/packages/dashboard-sdk/src/virtual-modules.ts
@@ -6,6 +6,8 @@ import {
RESOLVED_WIDGETS_MODULE,
RESOLVED_NAVIGATION_MODULE,
RESOLVED_CUSTOM_FIELDS_MODULE,
+ RESOLVED_LAYOUTS_MODULE,
+ RESOLVED_PREFERENCES_MODULE,
VIRTUAL_MODULES,
} from "./constants"
import { generateRoutes } from "./routes"
@@ -14,6 +16,8 @@ import { generateI18n } from "./i18n"
import { generateWidgets } from "./widgets"
import { generateNavigation } from "./navigation"
import { generateCustomFields } from "./custom-fields"
+import { generateLayouts } from "./layouts-module"
+import { generatePreferences } from "./preferences-module"
import type { BuiltMercurConfig } from "./types"
export function isVirtualModule(id: string): boolean {
@@ -61,6 +65,14 @@ export function loadVirtualModule({
return generateCustomFields(mercurConfig)
}
+ if (id === RESOLVED_LAYOUTS_MODULE) {
+ return generateLayouts(mercurConfig)
+ }
+
+ if (id === RESOLVED_PREFERENCES_MODULE) {
+ return generatePreferences(mercurConfig)
+ }
+
return null
}
diff --git a/packages/dashboard-sdk/src/widgets.ts b/packages/dashboard-sdk/src/widgets.ts
index 01a43db5d..6efa2dd18 100644
--- a/packages/dashboard-sdk/src/widgets.ts
+++ b/packages/dashboard-sdk/src/widgets.ts
@@ -14,10 +14,13 @@ import {
isIdentifier,
isObjectExpression,
isObjectProperty,
+ isNumericLiteral,
isStringLiteral,
+ isUnaryExpression,
isVariableDeclaration,
isVariableDeclarator,
} from "./babel"
+import { emitLayers, spreadLayers } from "./layers"
import type { BuiltMercurConfig } from "./types"
type WidgetInfo = {
@@ -25,6 +28,17 @@ type WidgetInfo = {
id?: string
label?: string
permissions: string[]
+ section?: string
+ order?: number
+ replace?: string
+}
+
+function readNumber(value: any): number | undefined {
+ if (isNumericLiteral(value)) return value.value
+ if (isUnaryExpression(value) && value.operator === "-" && isNumericLiteral(value.argument)) {
+ return -value.argument.value
+ }
+ return undefined
}
type WidgetResult = {
@@ -47,6 +61,9 @@ function readWidgetConfig(properties: any[]): WidgetInfo | null {
const permissions: string[] = []
let id: string | undefined
let label: string | undefined
+ let section: string | undefined
+ let order: number | undefined
+ let replace: string | undefined
for (const prop of properties) {
if (!isObjectProperty(prop)) continue
@@ -62,10 +79,19 @@ function readWidgetConfig(properties: any[]): WidgetInfo | null {
if (isIdentifier(prop.key, { name: "label" }) && isStringLiteral(prop.value)) {
label = prop.value.value
}
+ if (isIdentifier(prop.key, { name: "section" }) && isStringLiteral(prop.value)) {
+ section = prop.value.value
+ }
+ if (isIdentifier(prop.key, { name: "order" })) {
+ order = readNumber(prop.value)
+ }
+ if (isIdentifier(prop.key, { name: "replace" }) && isStringLiteral(prop.value)) {
+ replace = prop.value.value
+ }
}
if (zones.length === 0) return null
- return { zones, id, label, permissions }
+ return { zones, id, label, permissions, section, order, replace }
}
function getConfigProperties(node: any): any[] | null {
@@ -153,7 +179,9 @@ function parseWidgetFile(
info.permissions.length
? `, permission: ${JSON.stringify(info.permissions)}`
: ""
- } }`,
+ }${info.section ? `, section: ${JSON.stringify(info.section)}` : ""}${
+ info.order !== undefined ? `, order: ${info.order}` : ""
+ }${info.replace ? `, replace: ${JSON.stringify(info.replace)}` : ""} }`,
}
}
@@ -183,33 +211,21 @@ export function collectWidgets(
}
}
-export function generateWidgets({
- srcDir,
- pluginExtensions,
-}: BuiltMercurConfig): string {
- const { imports, entries: widgetEntries } = collectWidgets(srcDir)
-
- const pluginDeclarations = pluginExtensions.map(
- (ext, i) =>
- `import __plugin${i} from "${normalizePath(ext)}"`
- )
- const pluginSpreads = pluginExtensions.map(
- (_, i) => ` ...(__plugin${i}.widgetModule?.widgets ?? [])`
- )
-
- const entries = [...widgetEntries, ...pluginSpreads]
-
- if (imports.length === 0 && pluginDeclarations.length === 0 && entries.length === 0) {
- return `export default { widgets: [] }`
- }
+/**
+ * Widgets stack across layers; a later layer's widget with the same id replaces
+ * the earlier one so a project can swap a plugin's widget without a new id.
+ */
+export function generateWidgets(config: BuiltMercurConfig): string {
+ const { header, names } = emitLayers(config)
- return `${imports.join("\n")}
+ return `${header}
-${pluginDeclarations.join("\n")}
+const byId = new Map()
+for (const widget of [
+${spreadLayers(names, "widgetModule", "widgets")}
+]) {
+ byId.set(widget.widgetId, widget)
+}
-export default {
- widgets: [
-${entries.join(",\n")}
- ]
-}`
+export default { widgets: [...byId.values()] }`
}
diff --git a/packages/dashboard-shared/src/extensions/context.tsx b/packages/dashboard-shared/src/extensions/context.tsx
index edee17a85..c65894e3d 100644
--- a/packages/dashboard-shared/src/extensions/context.tsx
+++ b/packages/dashboard-shared/src/extensions/context.tsx
@@ -2,9 +2,12 @@ import { createContext, useContext, useMemo, type ReactNode } from "react"
import {
ExtensionRegistry,
type CustomFieldsModule,
+ type LayoutModule,
type NavigationModule,
+ type PreferenceModule,
type WidgetModule,
} from "./registry"
+import { CORE_LAYOUTS } from "../layout-composer/core-layouts"
const ExtensionContext = createContext<ExtensionRegistry | null>(null)
@@ -12,6 +15,8 @@ export type ExtensionProviderProps = {
widgets?: WidgetModule
navigation?: NavigationModule
customFields?: CustomFieldsModule
+ layouts?: LayoutModule
+ preferences?: PreferenceModule
children: ReactNode
}
@@ -29,13 +34,22 @@ export const ExtensionProvider = ({
widgets,
navigation,
customFields,
+ layouts,
+ preferences,
children,
}: ExtensionProviderProps) => {
const registry = useMemo(() => {
- const next = new ExtensionRegistry({ widgets, navigation, customFields })
+ const next = new ExtensionRegistry({
+ widgets,
+ navigation,
+ customFields,
+ layouts,
+ preferences,
+ })
+ next.registerLayouts(CORE_LAYOUTS)
activeRegistry = next
return next
- }, [widgets, navigation, customFields])
+ }, [widgets, navigation, customFields, layouts, preferences])
return (
<ExtensionContext.Provider value={registry}>
@@ -45,6 +59,7 @@ export const ExtensionProvider = ({
}
const EMPTY_REGISTRY = new ExtensionRegistry()
+EMPTY_REGISTRY.registerLayouts(CORE_LAYOUTS)
/**
* Reads the panel's extension registry. Returns an empty registry when no
diff --git a/packages/dashboard-shared/src/extensions/index.ts b/packages/dashboard-shared/src/extensions/index.ts
index 8e82b8a94..58490d304 100644
--- a/packages/dashboard-shared/src/extensions/index.ts
+++ b/packages/dashboard-shared/src/extensions/index.ts
@@ -10,7 +10,13 @@ export {
type ResolvedDisplays,
type ZoneWidgets,
type WidgetPlacement,
+ type LayoutModule,
+ type PreferenceModule,
+ type SectionWidget,
+ type SectionWidgetMap,
} from "./registry"
+export { resolveRouteOverrides, type RenderDefaultProps } from "./route-layers"
+export { mergeLayoutPreferences, navOverridesFromPreferences } from "./preferences"
export {
ExtensionProvider,
useExtension,
diff --git a/packages/dashboard-shared/src/extensions/preferences.ts b/packages/dashboard-shared/src/extensions/preferences.ts
new file mode 100644
index 000000000..084d6a400
--- /dev/null
+++ b/packages/dashboard-shared/src/extensions/preferences.ts
@@ -0,0 +1,78 @@
+import type {
+ EntryPreference,
+ LayoutPreferences,
+ NavGroupConfig,
+ NavItemOverride,
+ ZonePreference,
+} from "@mercurjs/dashboard-sdk"
+
+/** Field-by-field merge per zone entry, later layers winning. */
+export function mergeLayoutPreferences(layers: LayoutPreferences[]): LayoutPreferences {
+ const result: LayoutPreferences = {}
+
+ for (const layer of layers) {
+ for (const [zone, preference] of Object.entries(layer ?? {})) {
+ const current: ZonePreference = result[zone] ?? {}
+ const entries = { ...(current.entries ?? {}) }
+ for (const [id, entry] of Object.entries(preference.entries ?? {})) {
+ entries[id] = { ...(entries[id] ?? {}), ...entry }
+ }
+
+ const groups = new Map((current.groups ?? []).map((group) => [group.id, group]))
+ for (const group of preference.groups ?? []) {
+ groups.set(group.id, { ...(groups.get(group.id) ?? {}), ...group })
+ }
+
+ result[zone] = {
+ ...(Object.keys(entries).length ? { entries } : {}),
+ ...(groups.size ? { groups: [...groups.values()] } : {}),
+ }
+ }
+ }
+
+ return result
+}
+
+export const NAV_ENTRY_PREFIX = "nav:"
+
+const navId = (entryId: string) =>
+ entryId.slice(NAV_ENTRY_PREFIX.length).replace(/^\//, "")
+
+/**
+ * Translates the sidebar zones of `_layouts.ts` (`nav:<path>` entries,
+ * `groups`) into the override shape the sidebars already consume, layered over
+ * the `_navigation.ts` overrides.
+ */
+export function navOverridesFromPreferences(
+ navigation: { items: NavItemOverride<string>[]; groups: NavGroupConfig[] },
+ zones: Array<ZonePreference | undefined>
+): { items: NavItemOverride<string>[]; groups: NavGroupConfig[] } {
+ const items = new Map(navigation.items.map((item) => [item.id, { ...item }]))
+ const groups = new Map(navigation.groups.map((group) => [group.id, { ...group }]))
+
+ for (const zone of zones) {
+ for (const group of zone?.groups ?? []) {
+ groups.set(group.id, { ...(groups.get(group.id) ?? {}), ...group })
+ }
+ for (const [entryId, entry] of Object.entries(zone?.entries ?? {})) {
+ if (!entryId.startsWith(NAV_ENTRY_PREFIX)) continue
+ const id = navId(entryId)
+ items.set(id, { ...(items.get(id) ?? { id }), ...toNavOverride(id, entry) })
+ }
+ }
+
+ return { items: [...items.values()], groups: [...groups.values()] }
+}
+
+function toNavOverride(id: string, entry: EntryPreference): NavItemOverride<string> {
+ const override: NavItemOverride<string> = { id }
+ if (entry.hidden !== undefined) override.hidden = entry.hidden
+ if (entry.order !== undefined) override.rank = entry.order
+ if (entry.label !== undefined) override.label = entry.label
+ if (entry.icon !== undefined) override.icon = entry.icon
+ if (entry.section !== undefined) override.group = entry.section
+ if ("parent" in entry) {
+ override.nested = entry.parent === null ? null : entry.parent?.replace(/^\//, "")
+ }
+ return override
+}
diff --git a/packages/dashboard-shared/src/extensions/registry.ts b/packages/dashboard-shared/src/extensions/registry.ts
index 1b7094723..16250de2a 100644
--- a/packages/dashboard-shared/src/extensions/registry.ts
+++ b/packages/dashboard-shared/src/extensions/registry.ts
@@ -1,4 +1,4 @@
-import type { ComponentType } from "react"
+import type { ComponentType, ReactNode } from "react"
import type {
ActivityEntry,
CustomColumn,
@@ -7,20 +7,28 @@ import type {
CustomFormField,
CustomListExtension,
CustomListFilter,
+ LayoutConfig,
+ LayoutPreferences,
NavGroupConfig,
NavItemOverride,
Permission,
SectionAction,
+ ZonePreference,
} from "@mercurjs/dashboard-sdk"
+import { NAV_ZONES } from "@mercurjs/dashboard-sdk"
+import { mergeLayoutPreferences, navOverridesFromPreferences } from "./preferences"
export type WidgetPlacement = "before" | "after"
export type Widget = {
- Component: ComponentType<{ data?: unknown }>
+ Component: ComponentType<{ data?: unknown; renderDefault?: () => ReactNode }>
zone: string[]
widgetId: string
permission?: Permission[]
label?: string
+ section?: string
+ order?: number
+ replace?: string
}
export type WidgetModule = { widgets?: Widget[] }
@@ -29,6 +37,8 @@ export type NavigationModule = {
items?: NavItemOverride<string>[]
}
export type CustomFieldsModule = { configs?: CustomFieldsConfig[] }
+export type LayoutModule = { layouts?: LayoutConfig[] }
+export type PreferenceModule = { layers?: LayoutPreferences[] }
export type ResolvedFormField = { name: string; field: CustomFormField }
type ResolvedFormEntry = ResolvedFormField & { zone: string; tab?: string }
@@ -65,6 +75,17 @@ export type ZoneWidgets = {
after: ResolvedWidget[]
}
+/** A widget resolved for a composer page, keyed by the section it lands in. */
+export type SectionWidget = {
+ Component: Widget["Component"]
+ /** Entry id, `widget:<id>` */
+ widgetId: string
+ permission?: Permission[]
+ order?: number
+ replace?: string
+}
+export type SectionWidgetMap = Record<string, SectionWidget[]>
+
const PLACEMENTS: WidgetPlacement[] = ["before", "after"]
function splitZone(zone: string): { slot: string; placement: WidgetPlacement } {
@@ -86,21 +107,99 @@ function splitZone(zone: string): { slot: string; placement: WidgetPlacement } {
*/
export class ExtensionRegistry {
private widgets = new Map<string, ZoneWidgets>()
+ private rawWidgets: Widget[] = []
private navOverrides: NavItemOverride<string>[] = []
private navGroups: NavGroupConfig[] = []
private customFields: CustomFieldsConfig[] = []
+ private layouts = new Map<string, LayoutConfig>()
+ private preferences: LayoutPreferences = {}
constructor(
input: {
widgets?: WidgetModule
navigation?: NavigationModule
customFields?: CustomFieldsModule
+ layouts?: LayoutModule
+ preferences?: PreferenceModule
} = {}
) {
- this.populateWidgets(input.widgets?.widgets ?? [])
- this.navOverrides = input.navigation?.items ?? []
- this.navGroups = input.navigation?.groups ?? []
+ this.rawWidgets = input.widgets?.widgets ?? []
+ this.populateWidgets(this.rawWidgets)
this.customFields = input.customFields?.configs ?? []
+ for (const layout of input.layouts?.layouts ?? []) {
+ this.layouts.set(layout.id, layout)
+ }
+ this.preferences = mergeLayoutPreferences(input.preferences?.layers ?? [])
+
+ // `_navigation.ts` overrides first, then the sidebar zones of `_layouts.ts`
+ // layered over them field by field.
+ const nav = navOverridesFromPreferences(
+ { items: input.navigation?.items ?? [], groups: input.navigation?.groups ?? [] },
+ [this.preferences[NAV_ZONES.MAIN], this.preferences[NAV_ZONES.SETTINGS]]
+ )
+ this.navOverrides = nav.items
+ this.navGroups = nav.groups
+ }
+
+ getLayout(id: string): LayoutConfig | undefined {
+ return this.layouts.get(id)
+ }
+
+ registerLayouts(layouts: LayoutConfig[]): void {
+ for (const layout of layouts) {
+ if (!this.layouts.has(layout.id)) this.layouts.set(layout.id, layout)
+ }
+ }
+
+ getLayoutPreference(zone: string): ZonePreference {
+ return this.preferences[zone] ?? {}
+ }
+
+ /**
+ * Widgets for a composer page, keyed by the layout section each lands in. A
+ * zone is the page prefix (`product.details`) or a section under it
+ * (`product.details.side`); the legacy `.before` / `.after` suffixes map to
+ * the first and last order of that section. An explicit `section` wins.
+ */
+ getWidgetsForSections(prefix: string, sections: string[]): SectionWidgetMap {
+ const result: SectionWidgetMap = {}
+ const defaultSection = sections.includes("main") ? "main" : sections[0]
+ const seen = new Map<string, number>()
+
+ for (const widget of this.rawWidgets) {
+ for (const zone of widget.zone) {
+ if (zone !== prefix && !zone.startsWith(`${prefix}.`)) continue
+
+ let suffix = zone === prefix ? "" : zone.slice(prefix.length + 1)
+ let order = widget.order
+ if (suffix === "before" || suffix.endsWith(".before")) {
+ suffix = suffix.replace(/\.?before$/, "")
+ order ??= Number.NEGATIVE_INFINITY
+ } else if (suffix === "after" || suffix.endsWith(".after")) {
+ suffix = suffix.replace(/\.?after$/, "")
+ order ??= Number.POSITIVE_INFINITY
+ }
+ if (suffix && !sections.includes(suffix)) continue
+
+ const section = widget.section ?? (suffix || defaultSection)
+ if (!section) continue
+
+ const base = `widget:${widget.widgetId}`
+ const count = seen.get(base) ?? 0
+ seen.set(base, count + 1)
+
+ result[section] ??= []
+ result[section].push({
+ Component: widget.Component,
+ widgetId: count === 0 ? base : `${base}#${count + 1}`,
+ permission: widget.permission,
+ order,
+ replace: widget.replace,
+ })
+ }
+ }
+
+ return result
}
private ensureSlot(slot: string): ZoneWidgets {
diff --git a/packages/dashboard-shared/src/extensions/route-layers.spec.tsx b/packages/dashboard-shared/src/extensions/route-layers.spec.tsx
new file mode 100644
index 000000000..58ba394f1
--- /dev/null
+++ b/packages/dashboard-shared/src/extensions/route-layers.spec.tsx
@@ -0,0 +1,43 @@
+import { createElement, type ReactNode } from "react"
+import { renderToStaticMarkup } from "react-dom/server"
+import { describe, expect, test } from "vitest"
+import { resolveRouteOverrides, type RenderDefaultProps } from "./route-layers"
+
+const Core = () => createElement("p", null, "core")
+const Plugin = ({ renderDefault }: RenderDefaultProps) =>
+ createElement("section", null, "plugin", renderDefault?.() as ReactNode)
+const Project = ({ renderDefault }: RenderDefaultProps) =>
+ createElement("main", null, "project", renderDefault?.() as ReactNode)
+
+describe("resolveRouteOverrides", () => {
+ test("last route at a path wins and renders the previous one through renderDefault", () => {
+ const routes = resolveRouteOverrides([
+ { path: "/disputes", Component: Core },
+ { path: "/reports", Component: Core },
+ { path: "/disputes", Component: Plugin },
+ { path: "disputes/", Component: Project },
+ ])
+
+ expect(routes.map((r) => r.path)).toEqual(["/disputes", "/reports"])
+ expect(renderToStaticMarkup(createElement(routes[0].Component))).toBe(
+ "<main>project<section>plugin<p>core</p></section></main>"
+ )
+ })
+
+ test("children are kept from the earlier route unless the later one declares its own", () => {
+ const [route] = resolveRouteOverrides([
+ { path: "/disputes", Component: Core, children: [{ path: "/disputes/edit", Component: Core }] },
+ { path: "/disputes", Component: Plugin },
+ ])
+ expect(route.children?.map((c) => c.path)).toEqual(["/disputes/edit"])
+
+ const [merged] = resolveRouteOverrides([
+ { path: "/disputes", Component: Core, children: [{ path: "/disputes/edit", Component: Core }] },
+ { path: "/disputes", Component: Plugin, children: [{ path: "/disputes/edit", Component: Plugin }, { path: "/disputes/cancel", Component: Plugin }] },
+ ])
+ expect(merged.children?.map((c) => c.path)).toEqual(["/disputes/edit", "/disputes/cancel"])
+ expect(renderToStaticMarkup(createElement(merged.children![0].Component))).toBe(
+ "<section>plugin<p>core</p></section>"
+ )
+ })
+})
diff --git a/packages/dashboard-shared/src/extensions/route-layers.tsx b/packages/dashboard-shared/src/extensions/route-layers.tsx
new file mode 100644
index 000000000..c867edabd
--- /dev/null
+++ b/packages/dashboard-shared/src/extensions/route-layers.tsx
@@ -0,0 +1,55 @@
+import { createElement, type ComponentType, type ReactNode } from "react"
+
+export type RenderDefaultProps = { renderDefault?: () => ReactNode }
+
+type LayeredRoute = {
+ Component: ComponentType<RenderDefaultProps>
+ path: string
+ children?: LayeredRoute[]
+}
+
+const normalize = (path: string) => {
+ let start = 0
+ let end = path.length
+ while (start < end && path.charCodeAt(start) === 47) start++
+ while (end > start && path.charCodeAt(end - 1) === 47) end--
+ return path.slice(start, end)
+}
+
+function override<T extends LayeredRoute>(previous: T, next: T): T {
+ const Previous = previous.Component
+ const Next = next.Component
+ const Component = (props: RenderDefaultProps) =>
+ createElement(Next, {
+ ...props,
+ renderDefault: () => createElement(Previous, { renderDefault: props.renderDefault }),
+ })
+ Component.displayName = Next.displayName ?? Next.name ?? "RouteOverride"
+
+ return {
+ ...next,
+ path: previous.path,
+ Component,
+ children: next.children
+ ? resolveRouteOverrides([...(previous.children ?? []), ...next.children])
+ : previous.children,
+ }
+}
+
+/**
+ * Collapses routes emitted in layer order so the last route at a path wins and
+ * receives the previous page as `renderDefault`. Parallel (modal) children at
+ * the same path resolve the same way; a later route without children keeps the
+ * earlier route's.
+ */
+export function resolveRouteOverrides<T extends LayeredRoute>(routes: T[]): T[] {
+ const byPath = new Map<string, T>()
+
+ for (const route of routes) {
+ const key = normalize(route.path)
+ const previous = byPath.get(key)
+ byPath.set(key, previous ? override(previous, route) : route)
+ }
+
+ return [...byPath.values()]
+}
diff --git a/packages/dashboard-shared/src/index.ts b/packages/dashboard-shared/src/index.ts
index 2d2b1b7cd..c82adbb8e 100644
--- a/packages/dashboard-shared/src/index.ts
+++ b/packages/dashboard-shared/src/index.ts
@@ -33,6 +33,7 @@ export * from "./hooks"
export * from "./permissions"
export * from "./providers"
export * from "./extensions"
+export * from "./layout-composer"
export * from "./price-lists"
export * from "./utils/images-conventer"
export * from "./lib/rich-text"
diff --git a/packages/dashboard-shared/src/layout-composer/core-layouts.tsx b/packages/dashboard-shared/src/layout-composer/core-layouts.tsx
new file mode 100644
index 000000000..9ab7099f3
--- /dev/null
+++ b/packages/dashboard-shared/src/layout-composer/core-layouts.tsx
@@ -0,0 +1,34 @@
+import { clx } from "@medusajs/ui"
+import type { LayoutConfig, LayoutComponentProps } from "@mercurjs/dashboard-sdk"
+import { CORE_LAYOUT_IDS } from "@mercurjs/dashboard-sdk"
+
+export const SingleColumnLayoutComponent = ({ sections, className }: LayoutComponentProps) => (
+ <div className={clx("flex flex-col gap-y-3", className)}>{sections.main}</div>
+)
+
+export const TwoColumnLayoutComponent = ({ sections, className }: LayoutComponentProps) => (
+ <div
+ className={clx(
+ "flex w-full flex-col items-start gap-x-4 gap-y-3 xl:grid xl:grid-cols-[minmax(0,_1fr)_440px]",
+ className
+ )}
+ >
+ <div className="flex w-full min-w-0 flex-col gap-y-3">{sections.main}</div>
+ <div className="flex w-full max-w-[100%] flex-col gap-y-3 xl:mt-0 xl:max-w-[440px]">
+ {sections.side}
+ </div>
+ </div>
+)
+
+export const CORE_LAYOUTS: LayoutConfig[] = [
+ {
+ id: CORE_LAYOUT_IDS.SINGLE_COLUMN,
+ sections: [{ id: "main" }],
+ Component: SingleColumnLayoutComponent,
+ },
+ {
+ id: CORE_LAYOUT_IDS.TWO_COLUMN,
+ sections: [{ id: "main" }, { id: "side" }],
+ Component: TwoColumnLayoutComponent,
+ },
+]
diff --git a/packages/dashboard-shared/src/layout-composer/detail-page-defaults.tsx b/packages/dashboard-shared/src/layout-composer/detail-page-defaults.tsx
new file mode 100644
index 000000000..f7bed0986
--- /dev/null
+++ b/packages/dashboard-shared/src/layout-composer/detail-page-defaults.tsx
@@ -0,0 +1,33 @@
+import type { ReactNode } from "react"
+import { JsonViewSection } from "../components/common/json-view-section"
+import { MetadataSection } from "../components/common/metadata-section"
+import { LayoutEntry } from "./entry"
+
+export type DetailPageDefaultsOptions = {
+ metadata?: boolean
+ jsonView?: boolean
+}
+
+/**
+ * The sections every detail page ends with, each a stable entry so a
+ * preference can hide or move them.
+ */
+export function detailPageDefaultEntries(
+ data: object,
+ { metadata = true, jsonView = true }: DetailPageDefaultsOptions = {}
+): ReactNode {
+ return (
+ <>
+ {metadata && (
+ <LayoutEntry id="MetadataSection">
+ <MetadataSection data={data} />
+ </LayoutEntry>
+ )}
+ {jsonView && (
+ <LayoutEntry id="JsonViewSection">
+ <JsonViewSection data={data} />
+ </LayoutEntry>
+ )}
+ </>
+ )
+}
diff --git a/packages/dashboard-shared/src/layout-composer/entries.spec.ts b/packages/dashboard-shared/src/layout-composer/entries.spec.ts
new file mode 100644
index 000000000..7519a7234
--- /dev/null
+++ b/packages/dashboard-shared/src/layout-composer/entries.spec.ts
@@ -0,0 +1,147 @@
+import { Fragment, createElement } from "react"
+import { describe, expect, test } from "vitest"
+import { ExtensionRegistry } from "../extensions/registry"
+import {
+ applyReplacements,
+ buildCoreEntries,
+ buildDisplayEntries,
+ buildWidgetEntries,
+ extractSectionElements,
+} from "./entries"
+import { LayoutEntry } from "./entry"
+
+const General = () => null
+const Media = () => null
+const Widget = () => null
+
+const sections = () =>
+ extractSectionElements({
+ main: createElement(
+ Fragment,
+ null,
+ createElement(LayoutEntry, { id: "ProductGeneralSection" }, createElement(General)),
+ createElement(Media)
+ ),
+ side: createElement(LayoutEntry, { id: "ProductOrganizationSection" }, null),
+ })
+
+describe("layout composer entries", () => {
+ test("core entries take the Entry id, else the component name", () => {
+ const elements = extractSectionElements({
+ main: [
+ createElement(LayoutEntry, { id: "ProductGeneralSection", key: "a" }, null),
+ createElement(Media, { key: "b" }),
+ createElement(Media, { key: "c" }),
+ ],
+ })
+ expect(buildCoreEntries(elements).map((e) => [e.entryId, e.naturalSection])).toEqual([
+ ["core:ProductGeneralSection", "main"],
+ ["core:Media", "main"],
+ ["core:Media#2", "main"],
+ ])
+ })
+
+ test("a replacing widget takes the slot and gets renderDefault", () => {
+ const elements = extractSectionElements({
+ main: [
+ createElement(LayoutEntry, { id: "ProductGeneralSection", key: "a" }, createElement(General)),
+ createElement(Media, { key: "b" }),
+ ],
+ })
+ const core = buildCoreEntries(elements)
+ const widgets = buildWidgetEntries({
+ main: [
+ { Component: Widget, widgetId: "widget:seller", replace: "core:ProductGeneralSection" },
+ { Component: Widget, widgetId: "widget:missing", replace: "core:Nope" },
+ ],
+ })
+
+ const result = applyReplacements(core, widgets)
+ expect(result.map((e) => e.entryId)).toEqual(["widget:seller", "core:Media", "widget:missing"])
+
+ const rendered = result[0].render({ id: "p" }) as { props: { renderDefault: () => unknown } }
+ const fallback = rendered.props.renderDefault() as { type: unknown }
+ expect(fallback.type).toBe(LayoutEntry)
+ })
+
+ test("preferences hide, reorder and move entries; unknown sections fall back", () => {
+ const core = buildCoreEntries(sections())
+ const widgets = buildWidgetEntries({
+ side: [{ Component: Widget, widgetId: "widget:kpi", order: -1 }],
+ })
+ const valid = new Set(["main", "side"])
+
+ const result = buildDisplayEntries(
+ [...core, ...widgets],
+ {
+ entries: {
+ "core:Media": { hidden: true },
+ "core:ProductOrganizationSection": { section: "main", order: -5 },
+ "widget:kpi": { section: "nowhere" },
+ },
+ },
+ valid
+ )
+
+ expect(result.main.map((e) => [e.entryId, e.order, e.hidden])).toEqual([
+ ["core:ProductOrganizationSection", -5, false],
+ ["core:ProductGeneralSection", 0, false],
+ ["core:Media", 0, true],
+ ])
+ expect(result.side.map((e) => e.entryId)).toEqual(["widget:kpi"])
+ })
+
+ test("registry resolves widgets per section with legacy suffixes", () => {
+ const registry = new ExtensionRegistry({
+ widgets: {
+ widgets: [
+ { Component: Widget, zone: ["product.detail.side.before"], widgetId: "a" },
+ { Component: Widget, zone: ["product.detail"], widgetId: "b", section: "side", order: 3 },
+ { Component: Widget, zone: ["product.detail.main.after"], widgetId: "c" },
+ { Component: Widget, zone: ["product.details"], widgetId: "other" },
+ { Component: Widget, zone: ["product.detail.tabs"], widgetId: "tab" },
+ ],
+ },
+ })
+
+ const result = registry.getWidgetsForSections("product.detail", ["main", "side"])
+ expect(result.side.map((w) => [w.widgetId, w.order])).toEqual([
+ ["widget:a", Number.NEGATIVE_INFINITY],
+ ["widget:b", 3],
+ ])
+ expect(result.main.map((w) => [w.widgetId, w.order])).toEqual([
+ ["widget:c", Number.POSITIVE_INFINITY],
+ ])
+ })
+
+ test("registry merges preferences across layers and derives nav overrides", () => {
+ const Icon = () => null
+ const registry = new ExtensionRegistry({
+ navigation: { items: [{ id: "payouts", rank: 9 }], groups: [] },
+ preferences: {
+ layers: [
+ {
+ "product.detail": { entries: { "core:Media": { hidden: true, order: 2 } } },
+ "nav.main": {
+ groups: [{ id: "finance", label: "Finance" }],
+ entries: { "nav:/payouts": { section: "finance", hidden: true } },
+ },
+ },
+ {
+ "product.detail": { entries: { "core:Media": { hidden: false } } },
+ "nav.main": { entries: { "nav:/products": { label: "Catalog", icon: Icon, parent: null, order: -1 } } },
+ },
+ ],
+ },
+ })
+
+ expect(registry.getLayoutPreference("product.detail")).toEqual({
+ entries: { "core:Media": { hidden: false, order: 2 } },
+ })
+ expect(registry.getNavGroups()).toEqual([{ id: "finance", label: "Finance" }])
+ expect(registry.getNavOverrides()).toEqual([
+ { id: "payouts", rank: 9, group: "finance", hidden: true },
+ { id: "products", label: "Catalog", icon: Icon, nested: null, rank: -1 },
+ ])
+ })
+})
diff --git a/packages/dashboard-shared/src/layout-composer/entries.ts b/packages/dashboard-shared/src/layout-composer/entries.ts
new file mode 100644
index 000000000..156c4a8a8
--- /dev/null
+++ b/packages/dashboard-shared/src/layout-composer/entries.ts
@@ -0,0 +1,167 @@
+import {
+ Children,
+ Fragment,
+ createElement,
+ isValidElement,
+ type ComponentType,
+ type ReactElement,
+ type ReactNode,
+} from "react"
+import type { ZonePreference } from "@mercurjs/dashboard-sdk"
+import type { SectionWidgetMap } from "../extensions/registry"
+import { LayoutEntry, type LayoutEntryProps } from "./entry"
+import type { DisplayEntry, RawEntry } from "./types"
+
+export const CORE_ENTRY_PREFIX = "core:"
+
+function getElementName(element: ReactElement): string {
+ const { type } = element
+ if (typeof type === "string") return type
+ return (type as ComponentType).displayName ?? (type as ComponentType).name ?? "unknown"
+}
+
+function isLayoutEntry(element: ReactElement): element is ReactElement<LayoutEntryProps> {
+ return element.type === LayoutEntry
+}
+
+function getCoreEntryKey(element: ReactElement): string {
+ return isLayoutEntry(element) ? element.props.id : getElementName(element)
+}
+
+function collectElements(node: ReactNode): ReactElement[] {
+ const elements: ReactElement[] = []
+ Children.forEach(node, (child) => {
+ if (!isValidElement(child)) return
+ if (child.type === Fragment) {
+ elements.push(...collectElements((child.props as { children?: ReactNode }).children))
+ return
+ }
+ elements.push(child)
+ })
+ return elements
+}
+
+export function extractSectionElements(
+ sections: Record<string, ReactNode>
+): Record<string, ReactElement[]> {
+ const result: Record<string, ReactElement[]> = {}
+ for (const [section, node] of Object.entries(sections)) {
+ result[section] = collectElements(node)
+ }
+ return result
+}
+
+/**
+ * One entry per element across all sections, in source order. Duplicate ids
+ * get a `#n` suffix from one counter shared across sections, so two same-named
+ * entries stay distinct. The id omits the section so an entry keeps its
+ * identity (and its preference) when its natural section changes in code.
+ */
+export function buildCoreEntries(elementsBySection: Record<string, ReactElement[]>): RawEntry[] {
+ const entries: RawEntry[] = []
+ const seen = new Map<string, number>()
+
+ for (const [section, elements] of Object.entries(elementsBySection)) {
+ for (const element of elements) {
+ const base = `${CORE_ENTRY_PREFIX}${getCoreEntryKey(element)}`
+ const count = seen.get(base) ?? 0
+ seen.set(base, count + 1)
+ entries.push({
+ entryId: count === 0 ? base : `${base}#${count + 1}`,
+ render: () => element,
+ naturalSection: section,
+ })
+ }
+ }
+
+ return entries
+}
+
+export function buildWidgetEntries(widgets: SectionWidgetMap): RawEntry[] {
+ const entries: RawEntry[] = []
+ for (const [section, list] of Object.entries(widgets)) {
+ for (const widget of list) {
+ const Component = widget.Component
+ entries.push({
+ entryId: widget.widgetId,
+ render: (data, renderDefault?: () => ReactNode) =>
+ createElement(Component, { data, renderDefault }),
+ naturalSection: section,
+ order: widget.order,
+ replace: widget.replace,
+ })
+ }
+ }
+ return entries
+}
+
+const warned = new Set<string>()
+
+/**
+ * Lets a widget with `replace` take the slot of the entry it names: same
+ * section and order, and the replaced entry becomes its `renderDefault`. A
+ * target that is not on the page is reported once and the widget appends.
+ */
+export function applyReplacements(core: RawEntry[], widgets: RawEntry[]): RawEntry[] {
+ const result = [...core]
+
+ for (const widget of widgets) {
+ const target = widget.replace ? result.findIndex((e) => e.entryId === widget.replace) : -1
+
+ if (target === -1) {
+ if (widget.replace && !warned.has(widget.replace)) {
+ warned.add(widget.replace)
+ console.warn(
+ `[mercur] Widget "${widget.entryId}" replaces "${widget.replace}", which this page does not render; rendering it after the section instead.`
+ )
+ }
+ result.push(widget)
+ continue
+ }
+
+ const replaced = result[target]
+ const render = widget.render as (data: unknown, renderDefault?: () => ReactNode) => ReactNode
+ result[target] = {
+ entryId: widget.entryId,
+ naturalSection: replaced.naturalSection,
+ order: replaced.order,
+ render: (data) => render(data, () => replaced.render(data)),
+ }
+ }
+
+ return result
+}
+
+/**
+ * Applies a zone's preference to the raw entries: effective section (a section
+ * the layout does not render falls back to the natural one), order (preference,
+ * then the widget's own, then 0 so source order holds) and hidden.
+ */
+export function buildDisplayEntries(
+ raw: RawEntry[],
+ preference: ZonePreference,
+ validSections: Set<string>
+): Record<string, DisplayEntry[]> {
+ const result: Record<string, DisplayEntry[]> = {}
+
+ for (const entry of raw) {
+ const pref = preference.entries?.[entry.entryId]
+ const section =
+ pref?.section && validSections.has(pref.section) ? pref.section : entry.naturalSection
+ if (!validSections.has(section)) continue
+
+ result[section] ??= []
+ result[section].push({
+ entryId: entry.entryId,
+ render: entry.render,
+ order: pref?.order ?? entry.order ?? 0,
+ hidden: pref?.hidden ?? false,
+ })
+ }
+
+ for (const section of Object.keys(result)) {
+ result[section].sort((a, b) => a.order - b.order)
+ }
+
+ return result
+}
diff --git a/packages/dashboard-shared/src/layout-composer/entry.tsx b/packages/dashboard-shared/src/layout-composer/entry.tsx
new file mode 100644
index 000000000..986b120cf
--- /dev/null
+++ b/packages/dashboard-shared/src/layout-composer/entry.tsx
@@ -0,0 +1,13 @@
+import { Fragment, type ReactNode } from "react"
+
+export type LayoutEntryProps = {
+ /** Stable identity for this entry; survives component renames and minification. */
+ id: string
+ children: ReactNode
+}
+
+export function LayoutEntry({ children }: LayoutEntryProps) {
+ return <Fragment>{children}</Fragment>
+}
+
+LayoutEntry.displayName = "LayoutEntry"
diff --git a/packages/dashboard-shared/src/layout-composer/index.ts b/packages/dashboard-shared/src/layout-composer/index.ts
new file mode 100644
index 000000000..9ec97c38b
--- /dev/null
+++ b/packages/dashboard-shared/src/layout-composer/index.ts
@@ -0,0 +1,17 @@
+export { LayoutComposer, type LayoutComposerProps } from "./layout-composer"
+export { LayoutEntry, type LayoutEntryProps } from "./entry"
+export {
+ CORE_LAYOUTS,
+ SingleColumnLayoutComponent,
+ TwoColumnLayoutComponent,
+} from "./core-layouts"
+export { detailPageDefaultEntries, type DetailPageDefaultsOptions } from "./detail-page-defaults"
+export {
+ applyReplacements,
+ buildCoreEntries,
+ buildDisplayEntries,
+ buildWidgetEntries,
+ extractSectionElements,
+ CORE_ENTRY_PREFIX,
+} from "./entries"
+export type { DisplayEntry, RawEntry, EntryRenderer } from "./types"
diff --git a/packages/dashboard-shared/src/layout-composer/layout-composer.tsx b/packages/dashboard-shared/src/layout-composer/layout-composer.tsx
new file mode 100644
index 000000000..1574d8ed1
--- /dev/null
+++ b/packages/dashboard-shared/src/layout-composer/layout-composer.tsx
@@ -0,0 +1,94 @@
+import { Fragment, useContext, useMemo, type ReactNode } from "react"
+import { Outlet } from "react-router-dom"
+import type { Layouts, SectionNameFor, LayoutComponentProps } from "@mercurjs/dashboard-sdk"
+import { useExtension } from "../extensions/context"
+import { isPermitted } from "../permissions/permission-check"
+import { PermissionsContext } from "../permissions/permissions-context"
+import {
+ applyReplacements,
+ buildCoreEntries,
+ buildDisplayEntries,
+ buildWidgetEntries,
+ extractSectionElements,
+} from "./entries"
+import { LayoutEntry } from "./entry"
+
+export type LayoutComposerProps<TLayoutId extends Layouts, TData> = {
+ /** Zone prefix widgets and preferences target, e.g. `product.details`. */
+ widgetsZonePrefix: string
+ /** Layout to render the page with, e.g. `core:two-column`. */
+ preferredLayoutId: TLayoutId
+ /** Content per section of that layout. */
+ sections: Record<SectionNameFor<TLayoutId>, ReactNode>
+ /** Passed to every widget as `data`. */
+ data?: TData
+ /** Render an `Outlet` after the layout for modal child routes. @default true */
+ hasOutlet?: boolean
+ /** Compose only the page's own entries; no widget is resolved for the prefix. */
+ disableWidgets?: boolean
+ layoutProps?: Omit<LayoutComponentProps, "sections" | "data">
+ "data-testid"?: string
+}
+
+const LayoutComposerRoot = <TLayoutId extends Layouts, TData>({
+ widgetsZonePrefix,
+ preferredLayoutId,
+ sections,
+ data,
+ hasOutlet = true,
+ disableWidgets = false,
+ layoutProps = {},
+ "data-testid": testId,
+}: LayoutComposerProps<TLayoutId, TData>) => {
+ const registry = useExtension()
+ const permissions = useContext(PermissionsContext)
+ const layout = registry.getLayout(preferredLayoutId)
+
+ const entriesBySection = useMemo(() => {
+ const sectionIds = layout?.sections.map((section) => section.id) ?? []
+ const validSections = new Set(sectionIds)
+ const core = buildCoreEntries(extractSectionElements(sections as Record<string, ReactNode>))
+
+ const widgets = disableWidgets
+ ? {}
+ : registry.getWidgetsForSections(widgetsZonePrefix, sectionIds)
+ for (const section of Object.keys(widgets)) {
+ widgets[section] = widgets[section].filter((widget) =>
+ isPermitted(permissions, widget.permission)
+ )
+ }
+
+ return buildDisplayEntries(
+ applyReplacements(core, buildWidgetEntries(widgets)),
+ registry.getLayoutPreference(widgetsZonePrefix),
+ validSections
+ )
+ }, [sections, widgetsZonePrefix, layout, disableWidgets, registry, permissions])
+
+ if (!layout) {
+ if (process.env.NODE_ENV === "development") {
+ console.warn(`[mercur] Unknown layout "${preferredLayoutId}".`)
+ }
+ return null
+ }
+
+ const rendered: Record<string, ReactNode> = {}
+ for (const section of layout.sections) {
+ rendered[section.id] = (entriesBySection[section.id] ?? [])
+ .filter((entry) => !entry.hidden)
+ .map((entry) => <Fragment key={entry.entryId}>{entry.render(data)}</Fragment>)
+ }
+
+ const LayoutComponent = layout.Component
+
+ return (
+ <div className="flex w-full flex-col gap-y-3" data-testid={testId}>
+ <LayoutComponent sections={rendered} data={data} {...layoutProps} />
+ {hasOutlet && <Outlet />}
+ </div>
+ )
+}
+
+export const LayoutComposer = Object.assign(LayoutComposerRoot, {
+ Entry: LayoutEntry,
+})
diff --git a/packages/dashboard-shared/src/layout-composer/types.ts b/packages/dashboard-shared/src/layout-composer/types.ts
new file mode 100644
index 000000000..99e15040d
--- /dev/null
+++ b/packages/dashboard-shared/src/layout-composer/types.ts
@@ -0,0 +1,27 @@
+import type { ReactNode } from "react"
+import type {
+ LayoutComponentProps,
+ LayoutConfig,
+ Layouts,
+ SectionNameFor,
+} from "@mercurjs/dashboard-sdk"
+
+export type { LayoutComponentProps, LayoutConfig, Layouts, SectionNameFor }
+
+export type EntryRenderer = (data: unknown) => ReactNode
+
+export type RawEntry = {
+ entryId: string
+ render: EntryRenderer
+ naturalSection: string
+ order?: number
+ /** Entry id this one takes the place of. */
+ replace?: string
+}
+
+export type DisplayEntry = {
+ entryId: string
+ render: EntryRenderer
+ order: number
+ hidden: boolean
+}
diff --git a/packages/vendor/scripts/generate-extension-targets.ts b/packages/vendor/scripts/generate-extension-targets.ts
index 15b0f9fef..46b23e1b4 100644
--- a/packages/vendor/scripts/generate-extension-targets.ts
+++ b/packages/vendor/scripts/generate-extension-targets.ts
@@ -5,6 +5,8 @@
*
* - `<WidgetZone id="…">` usages, → WidgetZoneRegistry (+ placement suffixes)
* `useWidgetTabs("…")` calls
+ * - `<LayoutComposer widgetsZonePrefix>` → WidgetZoneRegistry (prefix + its layout sections)
+ * `<LayoutComposer.Entry id>` → LayoutEntryRegistry (`core:<id>`)
* - `useCoreRoutes()` `to:` literals → NavItemRegistry / NavParentRegistry
* - settings sidebar `to:` / group `id:` → NavItemRegistry / NavGroupRegistry
* - `<FormExtensionZone model zone>` / → CustomFieldsRegistry (form/display zones)
@@ -33,6 +35,39 @@ function walk(dir: string, out: string[] = []): string[] {
return out
}
+const LAYOUT_SECTIONS: Record<string, string[]> = {
+ "CORE_LAYOUT_IDS.SINGLE_COLUMN": ["main"],
+ "CORE_LAYOUT_IDS.TWO_COLUMN": ["main", "side"],
+}
+
+/**
+ * Composer pages: the zone prefix itself, one zone per section of the layout
+ * the page picked, and the `core:<id>` entry ids a widget may `replace`.
+ */
+function collectComposers(files: string[]): { zones: Set<string>; entries: Set<string> } {
+ const zones = new Set<string>()
+ const entries = new Set<string>()
+ const composerRe = /<LayoutComposer\b[^>]*?widgetsZonePrefix=["'`]([^"'`]+)["'`][^>]*?preferredLayoutId=\{([^}]+)\}/gs
+ const entryRe = /<LayoutComposer\.Entry\b[^>]*?\bid=["'`]([^"'`]+)["'`]/g
+ const defaultsRe = /detailPageDefaultEntries\(/
+ for (const file of files) {
+ const code = fs.readFileSync(file, "utf-8")
+ let m: RegExpExecArray | null
+ while ((m = composerRe.exec(code))) {
+ zones.add(m[1])
+ for (const section of LAYOUT_SECTIONS[m[2].trim()] ?? ["main"]) {
+ zones.add(`${m[1]}.${section}`)
+ }
+ }
+ while ((m = entryRe.exec(code))) entries.add(`core:${m[1]}`)
+ if (defaultsRe.test(code)) {
+ entries.add("core:MetadataSection")
+ entries.add("core:JsonViewSection")
+ }
+ }
+ return { zones, entries }
+}
+
function collectWidgetSlots(files: string[]): Set<string> {
const slots = new Set<string>()
const re = /<WidgetZone[^>]*\bid=["'`]([^"'`]+)["'`]/g
@@ -273,10 +308,17 @@ function keys(values: Iterable<string>): string {
function main() {
const files = walk(SRC)
const slots = collectWidgetSlots(files)
+ const composers = collectComposers(files)
const zoneIds = new Set<string>()
for (const slot of slots) {
for (const p of PLACEMENTS) zoneIds.add(`${slot}.${p}`)
}
+ for (const zone of composers.zones) {
+ zoneIds.add(zone)
+ if (zone.includes(".main") || zone.includes(".side")) {
+ for (const p of PLACEMENTS) zoneIds.add(`${zone}.${p}`)
+ }
+ }
const mainLayout = path.join(
SRC,
@@ -312,6 +354,10 @@ declare module "@mercurjs/dashboard-sdk" {
${keys(zoneIds)}
}
+ interface LayoutEntryRegistry {
+${keys(composers.entries)}
+ }
+
interface NavItemRegistry {
${keys(nav.items)}
}
diff --git a/packages/vendor/src/app.tsx b/packages/vendor/src/app.tsx
index 95bfe9bbc..0f781df54 100644
--- a/packages/vendor/src/app.tsx
+++ b/packages/vendor/src/app.tsx
@@ -2,9 +2,11 @@ import { customRoutes } from "virtual:mercur/routes";
import widgets from "virtual:mercur/widgets";
import navigation from "virtual:mercur/navigation";
import customFields from "virtual:mercur/custom-fields";
+import layouts from "virtual:mercur/layouts";
+import preferences from "virtual:mercur/preferences";
import { HelmetProvider } from "react-helmet-async";
import { QueryClientProvider } from "@tanstack/react-query";
-import { ExtensionProvider } from "@mercurjs/dashboard-shared";
+import { ExtensionProvider, resolveRouteOverrides } from "@mercurjs/dashboard-shared";
import { ThemeProvider } from "./providers";
import { I18nProvider, Toaster, TooltipProvider } from "@medusajs/ui";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
@@ -16,10 +18,11 @@ import { queryClient } from "./lib/query-client";
export default function App() {
const routes = useMemo(() => {
+ const resolved = resolveRouteOverrides(customRoutes);
return {
- settingsRoutes: createRouteMap(getRoutesByType(customRoutes, "settings")),
- mainRoutes: createRouteMap(getRoutesByType(customRoutes, "main")),
- publicRoutes: createRouteMap(getRoutesByType(customRoutes, "public")),
+ settingsRoutes: createRouteMap(getRoutesByType(resolved, "settings")),
+ mainRoutes: createRouteMap(getRoutesByType(resolved, "main")),
+ publicRoutes: createRouteMap(getRoutesByType(resolved, "public")),
};
}, []);
@@ -32,6 +35,8 @@ export default function App() {
widgets={widgets}
navigation={navigation}
customFields={customFields}
+ layouts={layouts}
+ preferences={preferences}
>
<I18n />
<I18nProvider>
diff --git a/packages/vendor/src/extension-targets.d.ts b/packages/vendor/src/extension-targets.d.ts
index b2af10256..87ef4b397 100644
--- a/packages/vendor/src/extension-targets.d.ts
+++ b/packages/vendor/src/extension-targets.d.ts
@@ -54,8 +54,11 @@ declare module "@mercurjs/dashboard-sdk" {
"offer-variants.detail.main.before": true
"offer-variants.detail.side.after": true
"offer-variants.detail.side.before": true
+ "offers.detail": true
+ "offers.detail.main": true
"offers.detail.main.after": true
"offers.detail.main.before": true
+ "offers.detail.side": true
"offers.detail.side.after": true
"offers.detail.side.before": true
"offers.list.after": true
@@ -134,6 +137,13 @@ declare module "@mercurjs/dashboard-sdk" {
"topbar.before": true
}
+ interface LayoutEntryRegistry {
+ "core:OfferAssociatedProductSection": true
+ "core:OfferDetailGeneralSection": true
+ "core:OfferVariantsSection": true
+ "core:ProductMediaSection": true
+ }
+
interface NavItemRegistry {
"campaigns": true
"categories": true
diff --git a/packages/vendor/src/get-route-map.tsx b/packages/vendor/src/get-route-map.tsx
index 8dac77785..1a101a566 100644
--- a/packages/vendor/src/get-route-map.tsx
+++ b/packages/vendor/src/get-route-map.tsx
@@ -30,10 +30,18 @@ function mergeRoutes(
if (existingIndex !== -1) {
const { children: customChildren, ...customRest } = customRoute;
+ const baseHandle = result[existingIndex].handle as object | undefined;
+ const customHandle = customRest.handle as object | undefined;
result[existingIndex] = {
...result[existingIndex],
...customRest,
path: result[existingIndex].path,
+ // Merge rather than replace, so a custom route declaring only
+ // `permissions` doesn't drop the base route's `breadcrumb`.
+ handle:
+ baseHandle || customHandle
+ ? { ...baseHandle, ...customHandle }
+ : undefined,
children: customChildren
? mergeRoutes(result[existingIndex].children ?? [], customChildren)
: result[existingIndex].children,
diff --git a/packages/vendor/src/module.d.ts b/packages/vendor/src/module.d.ts
index 1b93cc7ed..d1cd63990 100644
--- a/packages/vendor/src/module.d.ts
+++ b/packages/vendor/src/module.d.ts
@@ -40,3 +40,15 @@ declare module "virtual:mercur/custom-fields" {
export default customFields
}
+
+declare module "virtual:mercur/layouts" {
+ import { LayoutModule } from '@mercurjs/dashboard-shared'
+ const layouts: LayoutModule
+ export default layouts
+}
+
+declare module "virtual:mercur/preferences" {
+ import { PreferenceModule } from '@mercurjs/dashboard-shared'
+ const preferences: PreferenceModule
+ export default preferences
+}
diff --git a/packages/vendor/src/pages/offers/[id]/offer-detail-page.tsx b/packages/vendor/src/pages/offers/[id]/offer-detail-page.tsx
index d5f2b1d31..037b20bdf 100644
--- a/packages/vendor/src/pages/offers/[id]/offer-detail-page.tsx
+++ b/packages/vendor/src/pages/offers/[id]/offer-detail-page.tsx
@@ -1,16 +1,15 @@
-import { Children, ReactNode } from "react"
import { useLoaderData, useParams } from "react-router-dom"
import { Container } from "@medusajs/ui"
+import { CORE_LAYOUT_IDS } from "@mercurjs/dashboard-sdk"
import {
isForbidden,
+ LayoutComposer,
SectionNoAccess,
useLinkQuery,
- WidgetZone,
} from "@mercurjs/dashboard-shared"
import { TwoColumnPageSkeleton } from "../../../components/common/skeleton"
-import { TwoColumnPage } from "../../../components/layout/pages"
import { useProduct } from "../../../hooks/api/products"
import { ProductMediaSection } from "../../products/[id]/_components/product-media-section"
import { OFFER_PRODUCT_DETAIL_FIELDS } from "../common/constants"
@@ -20,7 +19,7 @@ import { OfferVariantsSection } from "./_components/offer-variants-section"
import { OfferAssociatedProductSection } from "./_components/offer-associated-product-section"
import { loader } from "./loader"
-const Root = ({ children }: { children?: ReactNode }) => {
+export const OfferDetailPage = () => {
const { id } = useParams()
const initialData = useLoaderData() as Awaited<ReturnType<typeof loader>>
const query = useLinkQuery("offer", OFFER_PRODUCT_DETAIL_FIELDS)
@@ -47,39 +46,35 @@ const Root = ({ children }: { children?: ReactNode }) => {
const typed = product as OfferProduct
return (
- <>
- {Children.count(children) > 0 ? (
- children
- ) : (
- <TwoColumnPage data={typed} hasOutlet>
- <TwoColumnPage.Main>
- <WidgetZone id="offers.detail.main" data={typed}>
+ <LayoutComposer
+ widgetsZonePrefix="offers.detail"
+ preferredLayoutId={CORE_LAYOUT_IDS.TWO_COLUMN}
+ data={typed}
+ sections={{
+ main: (
+ <>
+ <LayoutComposer.Entry id="OfferDetailGeneralSection">
<OfferDetailGeneralSection product={typed} />
+ </LayoutComposer.Entry>
+ <LayoutComposer.Entry id="ProductMediaSection">
<ProductMediaSection product={typed} readOnly />
+ </LayoutComposer.Entry>
+ <LayoutComposer.Entry id="OfferVariantsSection">
<OfferVariantsSection
variants={typed.variants}
thumbnail={typed.thumbnail}
/>
- </WidgetZone>
- </TwoColumnPage.Main>
- <TwoColumnPage.Sidebar>
- <WidgetZone id="offers.detail.side" data={typed}>
- <OfferAssociatedProductSection product={typed} />
- </WidgetZone>
- </TwoColumnPage.Sidebar>
- </TwoColumnPage>
- )}
- </>
+ </LayoutComposer.Entry>
+ </>
+ ),
+ side: (
+ <LayoutComposer.Entry id="OfferAssociatedProductSection">
+ <OfferAssociatedProductSection product={typed} />
+ </LayoutComposer.Entry>
+ ),
+ }}
+ />
)
}
-export const OfferDetailPage = Object.assign(Root, {
- Main: TwoColumnPage.Main,
- Sidebar: TwoColumnPage.Sidebar,
- General: OfferDetailGeneralSection,
- Media: ProductMediaSection,
- Variants: OfferVariantsSection,
- AssociatedProduct: OfferAssociatedProductSection,
-})
-
-export const Component = Root
+export const Component = OfferDetailPage
diff --git a/packages/vendor/src/utils/routes.ts b/packages/vendor/src/utils/routes.ts
index 40faa87ec..68a16b1f2 100644
--- a/packages/vendor/src/utils/routes.ts
+++ b/packages/vendor/src/utils/routes.ts
@@ -1,10 +1,11 @@
import { ComponentType } from "react"
import { LoaderFunction, RouteObject } from "react-router-dom"
import type { Permission, RouteHandle } from "@mercurjs/dashboard-sdk"
+import type { RenderDefaultProps } from "@mercurjs/dashboard-shared"
import { ErrorBoundary } from "../components/utilities/error-boundary"
export type Route = {
- Component: ComponentType
+ Component: ComponentType<RenderDefaultProps>
path: string
loader?: LoaderFunction
handle?: RouteHandle
diff --git a/packages/vendor/tsup.config.ts b/packages/vendor/tsup.config.ts
index dd32b89ca..a503b30dd 100644
--- a/packages/vendor/tsup.config.ts
+++ b/packages/vendor/tsup.config.ts
@@ -5,5 +5,5 @@ export default defineConfig({
dts: true,
entry: ["src/index.ts", "src/index.css", 'src/pages/index.ts'],
format: ["esm"],
- external: ["react", "react-dom", "react-router-dom", "virtual:mercur/config", "virtual:mercur/routes", "virtual:mercur/menu-items", "virtual:mercur/i18n", "virtual:mercur/widgets", "virtual:mercur/navigation", "virtual:mercur/custom-fields"],
+ external: ["react", "react-dom", "react-router-dom", "virtual:mercur/config", "virtual:mercur/routes", "virtual:mercur/menu-items", "virtual:mercur/i18n", "virtual:mercur/widgets", "virtual:mercur/navigation", "virtual:mercur/custom-fields", "virtual:mercur/layouts", "virtual:mercur/preferences"],
});