The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
feat(dashboard-sdk): add nav groups API to _navigation (#1621)
Viktor Holik0a477094ca5d
diff --git a/apps/docs/references/panel-extensions/create-page.mdx b/apps/docs/references/panel-extensions/create-page.mdxindex 4483ca36a..d15dbceba 100644--- a/apps/docs/references/panel-extensions/create-page.mdx+++ b/apps/docs/references/panel-extensions/create-page.mdx@@ -101,6 +101,7 @@ The `config` object controls the page's sidebar entry.| `icon` | `ComponentType` (optional) | Sidebar icon, from `@medusajs/icons`. || `rank` | `number` (optional) | Order among sibling items. Lower ranks first. || `nested` | `string` (optional) | Parent item id to nest this entry under. |+| `group` | `string` (optional) | Sidebar group to list the entry under, as a string literal. See [Groups](#groups). || `translationNs` | `string` (optional) | i18n namespace used to resolve `label` as a translation key. || `public` | `boolean` (optional) | Render the route before authentication under the public layout. |@@ -131,7 +132,7 @@ Read the loader's result with `useLoaderData()` inside the component.## Reshape built-in navigation-Use `defineNavigationConfig` to reorder, hide, relabel, or re-parent built-in+Use `defineNavigationConfig` to reorder, hide, relabel, re-parent, or group built-insidebar items. It lives in a single host-owned file, `src/_navigation.ts`. Blockscannot contribute navigation overrides.@@ -159,6 +160,49 @@ Each entry is a `NavItemOverride`.| `label` | `string` (optional) | i18n key or literal replacing the item's label. || `icon` | `ComponentType` (optional) | Icon component replacing the item's icon, from `@medusajs/icons`. || `nested` | `NavParentId \| null` (optional) | Re-parent under a built-in parent id. `null` promotes a nested item to top level. |+| `group` | `NavGroupId` (optional) | List the item under a group declared in `groups`, or a built-in settings group. |++### Groups++`groups` declares group headings by keyword, and an item's `group` assigns it to+one. A group renders in whichever sidebar its items live in.++The main sidebar has no built-in groups. Top-level items assigned to a declared+group render below the ungrouped list, under the group's heading. The settings+sidebar ships `general`, `developer`, and `myAccount` in the admin panel and+`general` in the vendor portal, which `groups` can also override by id. Settings+items are targeted as `settings/<segment>`.++```ts apps/admin/src/_navigation.ts+import { defineNavigationConfig } from "@mercurjs/dashboard-sdk"++export default defineNavigationConfig({+ groups: [+ { id: "catalog", label: "Catalog" },+ { id: "integrations", label: "Integrations", rank: 1 },+ { id: "developer", hidden: true },+ ],+ items: [+ { id: "products", group: "catalog" },+ { id: "inventory", group: "catalog" },+ { id: "settings/tax-regions", group: "integrations" },+ ],+})+```++Each entry is a `NavGroupConfig`.++| Field | Type | Description |+| --------------- | -------------------- | --------------------------------------------------------------------------- |+| `id` | `string` | A new keyword that declares a group, or a built-in settings group id to override. |+| `label` | `string` (optional) | Heading text. A literal, or an i18n key with `translationNs`. Defaults to the `id`. |+| `translationNs` | `string` (optional) | i18n namespace used to resolve `label`. |+| `rank` | `number` (optional) | Order among groups, lower first. Defaults to declaration order. Built-in settings groups rank `0`, `1`, `2`. |+| `hidden` | `boolean` (optional) | Remove the group and its items from the sidebar. |++A custom page joins a group through `config.group`. An undeclared group falls+back to the default placement (the ungrouped list, or the first settings group),+and a group with no visible items isn't rendered.Navigation overrides reshape existing items only. To add a new item, register apage with a `config.label` as shown above.diff --git a/apps/docs/resources/customization/extending-panels.mdx b/apps/docs/resources/customization/extending-panels.mdxindex 63c03089c..7cc895971 100644--- a/apps/docs/resources/customization/extending-panels.mdx+++ b/apps/docs/resources/customization/extending-panels.mdx@@ -151,6 +151,7 @@ export default defineNavigationConfig({- `id` targets any built-in item, top-level routes or nested children, by its stable id, typed as `NavItemId`.- `rank` orders an item within its parent, `hidden` removes it from the sidebar, `label` and `icon` relabel it, and `nested` re-parents it (`nested: null` promotes to top level, typed against `NavParentId`).+- `groups` declares group headings by keyword, and an item's `group` lists it under one, in the main sidebar or the settings sidebar (settings items are targeted as `settings/<segment>`). The built-in settings groups can be reshaped by id. A custom page picks its group with `group` in its route config.- Navigation is a single host-owned file. Installed blocks cannot reorder the sidebar, so it stays one source of truth. It does not change custom routes, which still place themselves via `defineRouteConfig`.Walk through it in [Customize navigation](/rc/resources/tutorials/customize-navigation).@@ -242,6 +243,7 @@ For the full walkthrough (forms, sections, and list columns), see [Extend forms| `icon` | `ComponentType` | Icon component (for example from `@medusajs/icons`) || `rank` | `number` | Sort order (lower numbers appear first) || `nested` | `string` | Parent path for nested menu items |+ | `group` | `string` | Sidebar group declared in `_navigation.ts` to list the item under || `translationNs` | `string` | i18n namespace for the label || `public` | `boolean` | If `true`, the route is accessible without authentication |diff --git a/apps/docs/resources/tutorials/customize-navigation.mdx b/apps/docs/resources/tutorials/customize-navigation.mdxindex d2ac194dd..2ee9d55ac 100644--- a/apps/docs/resources/tutorials/customize-navigation.mdx+++ b/apps/docs/resources/tutorials/customize-navigation.mdx@@ -1,7 +1,7 @@---title: "How to Customize Navigation"sidebarTitle: "Customize Navigation"-description: "Reorder, hide, relabel, and re-parent the panel's built-in sidebar items from a single _navigation.ts file."+description: "Reorder, hide, relabel, re-parent, and group the panel's built-in sidebar items from a single _navigation.ts file."---Reshape the built-in sidebar without replacing it. You author one host-owned file, `src/_navigation.ts`, and it reorders, hides, relabels, and re-parents the built-in items.@@ -55,8 +55,9 @@ With it present, `id` and `nested` autocomplete and an unknown id fails `tsc`.| `label` | `string` | Relabel with an i18n key or literal. || `icon` | `ComponentType` | Replace its icon. || `nested` | `NavParentId \| null` | Re-parent under another top-level item. `null` promotes a nested item to top level. |+ | `group` | `NavGroupId` | List the item under a [group heading](#group-items-under-headings). |- Both `id` and `nested` are checked against the panel's generated `NavItemRegistry` and `NavParentRegistry`.+ `id`, `nested`, and `group` are checked against the panel's generated `NavItemRegistry`, `NavParentRegistry`, and `NavGroupRegistry`.</Step><Step title="Reload the panel">Open the vendor portal. Orders sits at the top, Price Lists is gone from the menu, and Campaigns now appears under Orders.@@ -80,6 +81,80 @@ export default defineNavigationConfig({})```+## Group items under headings++Declare groups by keyword in `groups`, then assign items to them with `group`. A group renders in whichever sidebar its items live in, and a group with no visible items isn't rendered.++### Main sidebar++The main sidebar ships without groups. Items you assign to a declared group move out of the default list and render below it, under the group's heading.++```ts apps/vendor/src/_navigation.ts+import { defineNavigationConfig } from "@mercurjs/dashboard-sdk"++export default defineNavigationConfig({+ groups: [+ { id: "catalog", label: "Catalog" },+ { id: "finance", label: "Finance" },+ ],+ items: [+ { id: "products", group: "catalog" },+ { id: "inventory", group: "catalog" },+ { id: "payouts", group: "finance" },+ ],+})+```++Only top-level items can be grouped. Nested children follow their parent.++### Settings sidebar++The settings sidebar already lists its items under groups. The admin panel ships `general`, `developer`, and `myAccount`. The vendor portal ships `general`. You can reshape these built-in groups, add your own, and move items between them. Settings items are targeted by their path without the leading slash, such as `settings/users`.++```ts apps/admin/src/_navigation.ts+import { defineNavigationConfig } from "@mercurjs/dashboard-sdk"++export default defineNavigationConfig({+ groups: [+ { id: "integrations", label: "Integrations", rank: 1 }, // new group, after General+ { id: "developer", label: "API" }, // relabel a built-in group+ ],+ items: [+ { id: "settings/secret-api-keys", group: "integrations" },+ { id: "settings/tax-regions", group: "integrations", rank: 0 },+ ],+})+```++### Group fields++| Field | Type | Effect |+|-------|------|--------|+| `id` | `string` | **Required.** A new keyword to declare a group, or a built-in settings group id to override. |+| `label` | `string` | Heading text. A literal, or an i18n key when `translationNs` is set. Defaults to the `id`. |+| `translationNs` | `string` | i18n namespace used to resolve `label`. |+| `rank` | `number` | Order among groups, lower first. Defaults to declaration order. Built-in settings groups rank `0`, `1`, `2`. |+| `hidden` | `boolean` | Remove the group and its items from the sidebar. |++An item's `group` only accepts a built-in group id or an id declared in the same file's `groups`, so a typo fails `tsc`.++### Group a custom page++A custom page picks its group in its own route config with the same keyword.++```tsx apps/admin/src/routes/settings/webhooks/page.tsx+import type { RouteConfig } from "@mercurjs/dashboard-sdk"++export const config: RouteConfig = {+ label: "Webhooks",+ group: "integrations",+}+```++<Note>+ A page whose group isn't declared falls back to the default placement: the ungrouped list in the main sidebar, or the first group in the settings sidebar.+</Note>+## Verify1. The top-level order reflects your `rank` values, with `orders` first.@@ -94,6 +169,9 @@ export default defineNavigationConfig({<Accordion title="Can an installed block reorder the sidebar?">No. Navigation is deliberately host-only. Blocks can ship pages, widgets, and custom fields, but the sidebar order stays a single source of truth in your app's `_navigation.ts`.</Accordion>+ <Accordion title="Can a block put its page in a group?">+ Yes. A block's page sets `group` in its route config like any other page. If the host hasn't declared that group, the page falls back to the default placement.+ </Accordion><Accordion title="What ids can I target?">Any built-in item, top-level or nested, by its own id, such as `orders`, `products`, `categories`, `collections`, `campaigns`, or `customer-groups`. Let your editor autocomplete `id:` against `NavItemId`. The full set is generated into your panel's `extension-targets.d.ts`.</Accordion>diff --git a/packages/admin/scripts/generate-extension-targets.ts b/packages/admin/scripts/generate-extension-targets.tsindex 1e7a2f4e1..15b0f9fef 100644--- a/packages/admin/scripts/generate-extension-targets.ts+++ b/packages/admin/scripts/generate-extension-targets.ts@@ -6,6 +6,7 @@* - `<WidgetZone id="…">` usages, → WidgetZoneRegistry (+ placement suffixes)* `useWidgetTabs("…")` calls* - `useCoreRoutes()` `to:` literals → NavItemRegistry / NavParentRegistry+ * - settings sidebar `to:` / group `id:` → NavItemRegistry / NavGroupRegistry* - `<FormExtensionZone model zone>` / → CustomFieldsRegistry (form/display zones)* `<DisplayExtensionZone model zone>`*@@ -86,6 +87,26 @@ function collectNav(mainLayout: string): { items: Set<string>; parents: Set<strireturn { items, parents }}+function collectSettingsNav(settingsLayout: string): {+ items: Set<string>+ groups: Set<string>+} {+ const items = new Set<string>()+ const groups = new Set<string>()+ const code = fs+ .readFileSync(settingsLayout, "utf-8")+ .replace(/\/\*[\s\S]*?\*\//g, "")+ .replace(/\/\/[^\n]*/g, "")++ let m: RegExpExecArray | null+ const toRe = /\bto:\s*["'`](\/settings\/[^"'`]+)["'`]/g+ while ((m = toRe.exec(code))) items.add(m[1].replace(/^\//, ""))+ const groupRe = /\bid:\s*["'`]([^"'`]+)["'`]/g+ while ((m = groupRe.exec(code))) groups.add(m[1])++ return { items, groups }+}+type ModelZones = {formZones: Set<string>displayZones: Set<string>@@ -268,6 +289,18 @@ function main() {? collectNav(mainLayout): { items: new Set<string>(), parents: new Set<string>() }+ const settingsLayout = path.join(+ SRC,+ "components",+ "layout",+ "settings-layout",+ "settings-layout.tsx"+ )+ const settingsNav = fs.existsSync(settingsLayout)+ ? collectSettingsNav(settingsLayout)+ : { items: new Set<string>(), groups: new Set<string>() }+ for (const id of settingsNav.items) nav.items.add(id)+const models = collectCustomFields(files)const contents = `// GENERATED by scripts/generate-extension-targets.ts — do not edit by hand.@@ -287,6 +320,10 @@ ${keys(nav.items)}${keys(nav.parents)}}+ interface NavGroupRegistry {+${keys(settingsNav.groups)}+ }+${customFieldsBlock(models)}}`@@ -302,7 +339,7 @@ ${customFieldsBlock(models)}}console.log(- `extension-targets.d.ts: ${zoneIds.size} widget zones, ${nav.items.size} nav items, ${nav.parents.size} nav parents, ${models.size} custom-field models`+ `extension-targets.d.ts: ${zoneIds.size} widget zones, ${nav.items.size} nav items, ${nav.parents.size} nav parents, ${settingsNav.groups.size} nav groups, ${models.size} custom-field models`)}diff --git a/packages/admin/src/components/layout/main-layout/main-layout.tsx b/packages/admin/src/components/layout/main-layout/main-layout.tsxindex 6fd92c21c..a089de454 100644--- a/packages/admin/src/components/layout/main-layout/main-layout.tsx+++ b/packages/admin/src/components/layout/main-layout/main-layout.tsx@@ -35,6 +35,8 @@ import { UserMenu } from "../user-menu";import menuItemsModule from "virtual:mercur/menu-items";import {applyNavOverrides,+ groupNavItems,+ type NavItemGroup,useExtension,usePermissions,type CoreNavItem,@@ -89,9 +91,12 @@ const addNestedItems = (return [...(items ?? []), ...nestedNavItems];};+type SidebarRoute = Omit<INavItem, "pathname"> & { group?: string };+const useSidebarRoutes = () => {const coreRoutes = useCoreRoutes();- const navOverrides = useExtension().getNavOverrides();+ const extension = useExtension();+ const navOverrides = extension.getNavOverrides();const permissions = usePermissions();const { hasAnyPermission, hasAllPermissions } = permissions;@@ -129,22 +134,36 @@ const useSidebarRoutes = () => {to: item.path,icon: item.icon ? <item.icon /> : undefined,translationNs: item.translationNs,+ group: item.group,items: addNestedItems(item.path, visibleMenuItems),}));- return { routesWithNested, customRoutesWithNested };+ const groupById = new Map<string, string | undefined>(+ navOverrides.map((o) => [o.id, o.group]),+ );++ return groupNavItems<SidebarRoute>(+ [+ ...routesWithNested.map((route) => ({+ ...route,+ group: groupById.get(route.id),+ })),+ ...customRoutesWithNested,+ ],+ extension.getNavGroups(),+ );};// First sidebar entry the actor can open, in sidebar order. Falls back to the// profile page, which needs no permission.export const useLandingRoute = () => {- const { routesWithNested, customRoutesWithNested } = useSidebarRoutes();- const first = [...routesWithNested, ...customRoutesWithNested][0];+ const { ungrouped, groups } = useSidebarRoutes();+ const first = [...ungrouped, ...groups.flatMap((group) => group.items)][0];return first?.to ?? "/settings/profile";};const MainSidebar = () => {- const { routesWithNested, customRoutesWithNested } = useSidebarRoutes();+ const { ungrouped, groups } = useSidebarRoutes();return (<aside@@ -168,12 +187,12 @@ const MainSidebar = () => {data-testid="sidebar-core-routes"><Searchbar />- {routesWithNested.map((route) => {- return <NavItem key={route.to} {...route} />;- })}- {customRoutesWithNested.map((route) => (+ {ungrouped.map((route) => (<NavItem key={route.to} {...route} />))}+ {groups.map((group) => (+ <SidebarGroup key={group.id} group={group} />+ ))}</nav></div><UtilitySection />@@ -189,6 +208,33 @@ const MainSidebar = () => {);};+const SidebarGroup = ({ group }: { group: NavItemGroup<SidebarRoute> }) => {+ const { t } = useTranslation(group.translationNs);++ return (+ <div+ className="flex flex-col gap-y-1 pt-2"+ data-testid={`sidebar-group-${group.id}`}+ >+ <div className="px-3">+ <div+ className={clx(+ "flex h-7 items-center overflow-hidden whitespace-nowrap px-2 text-ui-fg-muted",+ SIDEBAR_RAIL_FADE,+ )}+ >+ <Text size="small" leading="compact">+ {group.translationNs ? t(group.label) : group.label}+ </Text>+ </div>+ </div>+ {group.items.map((route) => (+ <NavItem key={route.to} {...route} />+ ))}+ </div>+ );+};+const Logout = () => {const { t } = useTranslation();const navigate = useNavigate();diff --git a/packages/admin/src/components/layout/settings-layout/settings-layout.tsx b/packages/admin/src/components/layout/settings-layout/settings-layout.tsxindex 7160961d2..3f0339c66 100644--- a/packages/admin/src/components/layout/settings-layout/settings-layout.tsx+++ b/packages/admin/src/components/layout/settings-layout/settings-layout.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useState } from "react";+import { Fragment, useCallback, useEffect, useMemo, useState } from "react";import { ArrowUturnLeft, MinusMini } from "@medusajs/icons";import { Divider, IconButton, Text, clx } from "@medusajs/ui";@@ -11,7 +11,13 @@ import { type INavItem, NavItem } from "@components/layout/nav-item";import { Shell } from "@components/layout/shell";import { UserMenu } from "@components/layout/user-menu";import menuItemsModule from "virtual:mercur/menu-items";-import { usePermissions } from "@mercurjs/dashboard-shared";+import {+ type NavGroup,+ type NavGroupItem,+ applyNavGroups,+ useExtension,+ usePermissions,+} from "@mercurjs/dashboard-shared";import { useExpandedSidebar } from "../../../providers/sidebar-provider";import {filterMenuItemsByPermissions,@@ -32,8 +38,17 @@ export const SettingsLayout = () => {const allMenuItems = menuItemsModule.menuItems ?? [];-const useExtensionNavItems = (): INavItem[] => {+const navId = (to: string) => to.replace(/^\//, "");++const toGroupItem = ({ label, to }: INavItem): NavGroupItem => ({+ id: navId(to),+ label,+ to,+});++const useExtensionNavItems = () => {const { hasAnyPermission, hasAllPermissions } = usePermissions();+ const canReach = useCanReach();return useMemo(() =>@@ -44,19 +59,21 @@ const useExtensionNavItems = (): INavItem[] => {}),"settings",)- .sort((a, b) => (a.rank ?? 0) - (b.rank ?? 0)).map((item) => ({+ id: navId(item.path),label: item.label,to: item.path,translationNs: item.translationNs,- })),- [hasAnyPermission, hasAllPermissions],+ group: item.group,+ rank: item.rank,+ }))+ .filter(canReach),+ [hasAnyPermission, hasAllPermissions, canReach],);};const useSettingRoutes = (): INavItem[] => {const { t } = useTranslation();- const extensionNavItems = useExtensionNavItems();return useMemo(() => [@@ -108,9 +125,8 @@ const useSettingRoutes = (): INavItem[] => {label: t("commissions.domain"),to: "/settings/commissions",},- ...extensionNavItems,],- [t, extensionNavItems],+ [t],);};@@ -163,7 +179,58 @@ const getSafeFromValue = (from: string, landing: string) => {const useCanReach = () => {const permissions = usePermissions();- return ({ to }: INavItem) => canReachRoute(permissions, to);+ return useCallback(+ ({ to }: { to: string }) => canReachRoute(permissions, to),+ [permissions],+ );+};++const useSettingsGroups = (): NavGroup[] => {+ const { t } = useTranslation();+ const canReach = useCanReach();+ const extension = useExtension();++ const routes = useSettingRoutes();+ const developerRoutes = useDeveloperRoutes();+ const myAccountRoutes = useMyAccountRoutes();+ const extensionNavItems = useExtensionNavItems();++ return useMemo(+ () =>+ applyNavGroups(+ [+ {+ id: "general",+ label: t("app.nav.settings.general"),+ items: routes.filter(canReach).map(toGroupItem),+ },+ {+ id: "developer",+ label: t("app.nav.settings.developer"),+ items: developerRoutes.filter(canReach).map(toGroupItem),+ },+ {+ id: "myAccount",+ label: t("app.nav.settings.myAccount"),+ items: myAccountRoutes.map(toGroupItem),+ },+ ],+ extensionNavItems,+ {+ groups: extension.getNavGroups(),+ items: extension.getNavOverrides(),+ },+ ),+ [+ t,+ canReach,+ extension,+ routes,+ developerRoutes,+ myAccountRoutes,+ extensionNavItems,+ ],+ );};const PROFILE_ROUTE = "/settings/profile";@@ -171,20 +238,13 @@ const PROFILE_ROUTE = "/settings/profile";// Where `/settings` lands: the first settings page the actor can open, or// their own profile, which needs no permission.export const useSettingsLandingRoute = () => {- const canReach = useCanReach();- const routes = [...useSettingRoutes(), ...useDeveloperRoutes()].filter(canReach);+ const routes = useSettingsGroups().flatMap((group) => group.items);return routes.find(({ to }) => to !== PROFILE_ROUTE)?.to ?? PROFILE_ROUTE;};const SettingsSidebar = () => {- const canReach = useCanReach();-- const routes = useSettingRoutes().filter(canReach);- const developerRoutes = useDeveloperRoutes().filter(canReach);- const myAccountRoutes = useMyAccountRoutes();-- const { t } = useTranslation();+ const groups = useSettingsGroups();return (<aside className="relative flex flex-1 flex-col justify-between overflow-y-auto">@@ -196,24 +256,16 @@ const SettingsSidebar = () => {</div><div className="flex flex-1 flex-col"><div className="flex flex-1 flex-col overflow-y-auto">- <RadixCollapsibleSection- label={t("app.nav.settings.general")}- items={routes}- />- <div className="flex items-center justify-center px-3">- <Divider variant="dashed" />- </div>- <RadixCollapsibleSection- label={t("app.nav.settings.developer")}- items={developerRoutes}- />- <div className="flex items-center justify-center px-3">- <Divider variant="dashed" />- </div>- <RadixCollapsibleSection- label={t("app.nav.settings.myAccount")}- items={myAccountRoutes}- />+ {groups.map((group, index) => (+ <Fragment key={group.id}>+ {index > 0 && (+ <div className="flex items-center justify-center px-3">+ <Divider variant="dashed" />+ </div>+ )}+ <RadixCollapsibleSection group={group} />+ </Fragment>+ ))}</div><div className="sticky bottom-0 bg-ui-bg-subtle"><UserSection />@@ -260,13 +312,10 @@ const Header = () => {);};-const RadixCollapsibleSection = ({- label,- items,-}: {- label: string;- items: INavItem[];-}) => {+const RadixCollapsibleSection = ({ group }: { group: NavGroup }) => {+ const { t } = useTranslation(group.translationNs);+ const label = group.translationNs ? t(group.label) : group.label;+return (<RadixCollapsible.Root defaultOpen className="py-3"><div className="px-3">@@ -284,7 +333,7 @@ const RadixCollapsibleSection = ({<RadixCollapsible.Content><div className="pt-0.5"><nav className="flex flex-col gap-y-0.5">- {items.map((setting) => (+ {group.items.map(({ id: _id, ...setting }) => (<NavItem key={setting.to} type="setting" {...setting} />))}</nav>diff --git a/packages/admin/src/extension-targets.d.ts b/packages/admin/src/extension-targets.d.tsindex da1638579..af2051a58 100644--- a/packages/admin/src/extension-targets.d.ts+++ b/packages/admin/src/extension-targets.d.ts@@ -175,6 +175,21 @@ declare module "@mercurjs/dashboard-sdk" {"promotions": true"reservations": true"reviews": true+ "settings/attributes": true+ "settings/commissions": true+ "settings/locations": true+ "settings/marketplace": true+ "settings/product-tags": true+ "settings/product-types": true+ "settings/profile": true+ "settings/publishable-api-keys": true+ "settings/refund-reasons": true+ "settings/regions": true+ "settings/return-reasons": true+ "settings/sales-channels": true+ "settings/secret-api-keys": true+ "settings/tax-regions": true+ "settings/users": true"stores": true}@@ -189,6 +204,12 @@ declare module "@mercurjs/dashboard-sdk" {"stores": true}+ interface NavGroupRegistry {+ "developer": true+ "general": true+ "myAccount": true+ }+interface CustomFieldsRegistry {"attribute": {formZones: "create"diff --git a/packages/admin/src/utils/routes.ts b/packages/admin/src/utils/routes.tsindex 754aa337c..ee1657470 100644--- a/packages/admin/src/utils/routes.ts+++ b/packages/admin/src/utils/routes.ts@@ -18,6 +18,7 @@ export type MenuItem = {path: stringrank?: numbernested?: string+ group?: stringtranslationNs?: stringpermissions?: Permission[]requireAll?: booleandiff --git a/packages/dashboard-sdk/src/__tests__/menu-items.spec.ts b/packages/dashboard-sdk/src/__tests__/menu-items.spec.tsnew file mode 100644index 000000000..41ce8ff56--- /dev/null+++ b/packages/dashboard-sdk/src/__tests__/menu-items.spec.ts@@ -0,0 +1,51 @@+import fs from "fs"+import os from "os"+import path from "path"+import { afterEach, describe, expect, test } from "vitest"+import { parseMenuItemFile } from "../menu-items"++const tmpDirs: string[] = []++const writeRoute = (route: string, source: string) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mercur-menu-items-"))+ tmpDirs.push(root)+ const routesDir = path.join(root, "src", "routes")+ const file = path.join(routesDir, route, "page.tsx")+ fs.mkdirSync(path.dirname(file), { recursive: true })+ fs.writeFileSync(file, source)+ return { file, routesDir }+}++afterEach(() => {+ for (const dir of tmpDirs.splice(0)) {+ fs.rmSync(dir, { recursive: true, force: true })+ }+})++describe("parseMenuItemFile", () => {+ test("extracts the settings group from the route config", () => {+ const { file, routesDir } = writeRoute(+ "settings/webhooks",+ `import type { RouteConfig } from "@mercurjs/dashboard-sdk"+export const config: RouteConfig = { label: "Webhooks", group: "developer" }+export default () => null+`+ )++ expect(parseMenuItemFile(file, routesDir, 0)?.menuItem).toMatchObject({+ path: "/settings/webhooks",+ group: "developer",+ })+ })++ test("leaves the group undefined when the config has none", () => {+ const { file, routesDir } = writeRoute(+ "settings/erp",+ `export const config = { label: "ERP" }+export default () => null+`+ )++ expect(parseMenuItemFile(file, routesDir, 0)?.menuItem.group).toBeUndefined()+ })+})diff --git a/packages/dashboard-sdk/src/config/types.ts b/packages/dashboard-sdk/src/config/types.tsindex f1a1c9d8c..3a9fb8118 100644--- a/packages/dashboard-sdk/src/config/types.ts+++ b/packages/dashboard-sdk/src/config/types.ts@@ -17,6 +17,7 @@ import type { Permission } from "../permissions"export interface WidgetZoneRegistry {}export interface NavItemRegistry {}export interface NavParentRegistry {}+export interface NavGroupRegistry {}export type WidgetZoneId = keyof WidgetZoneRegistry extends never? string@@ -30,6 +31,10 @@ export type NavParentId = keyof NavParentRegistry extends never? string: keyof NavParentRegistry+export type NavGroupId = keyof NavGroupRegistry extends never+ ? string+ : 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@@ -53,7 +58,7 @@ export interface WidgetConfig {}/** Override for a single built-in navigation item. */-export interface NavItemOverride {+export interface NavItemOverride<TGroup extends string = never> {id: NavItemId/** Order within the item's parent (or among top-level items). */rank?: number@@ -68,8 +73,29 @@ export interface NavItemOverride {* children; `null` promotes a nested item to the top level.*/nested?: NavParentId | null+ /**+ * List the item under a group heading: a built-in settings group id or one+ * declared in `groups`. Main sidebar items only join declared groups.+ */+ group?: NavGroupId | TGroup+}++/**+ * Declares a sidebar group, or overrides a built-in settings group by id. A+ * group renders in whichever sidebar its items live in.+ */+export interface NavGroupConfig<TId extends string = string> {+ id: NavGroupId | TId+ /** i18n key (with `translationNs`) or literal. Falls back to the id. */+ label?: string+ translationNs?: string+ /** Order among groups, lower first. Built-in settings groups rank 0, 1, 2… */+ rank?: number+ /** Remove the group and its items from the sidebar. */+ hidden?: boolean}-export interface NavigationConfig {- items: NavItemOverride[]+export interface NavigationConfig<TGroup extends string = never> {+ groups?: NavGroupConfig<TGroup>[]+ items?: NavItemOverride<NoInfer<TGroup>>[]}diff --git a/packages/dashboard-sdk/src/config/utils.ts b/packages/dashboard-sdk/src/config/utils.tsindex 750677bd4..3fbf1a57c 100644--- a/packages/dashboard-sdk/src/config/utils.ts+++ b/packages/dashboard-sdk/src/config/utils.ts@@ -21,9 +21,9 @@ export function defineWidgetConfig(config: WidgetConfig): WidgetConfig {return createConfigHelper(config)}-export function defineNavigationConfig(- config: NavigationConfig-): NavigationConfig {+export function defineNavigationConfig<TGroup extends string = never>(+ config: NavigationConfig<TGroup>+): NavigationConfig<TGroup> {return createConfigHelper(config)}diff --git a/packages/dashboard-sdk/src/menu-items.ts b/packages/dashboard-sdk/src/menu-items.tsindex f45e46053..214a7d6c2 100644--- a/packages/dashboard-sdk/src/menu-items.ts+++ b/packages/dashboard-sdk/src/menu-items.ts@@ -22,6 +22,7 @@ type MenuItemConfig = {icon?: booleanrank?: numbernested?: string+ group?: stringtranslationNs?: stringpermissions?: booleanrequireAll?: boolean@@ -33,6 +34,7 @@ type MenuItem = {path: stringrank?: numbernested?: string+ group?: stringtranslationNs?: stringpermissions?: stringrequireAll?: boolean@@ -158,6 +160,14 @@ function processConfigProperties(nestedValue = nested.value.value}+ const group = properties.find(+ (prop) => isObjectProperty(prop) && isIdentifier(prop.key, { name: "group" })+ )+ let groupValue: string | undefined+ if (group && isObjectProperty(group) && isStringLiteral(group.value)) {+ groupValue = group.value.value+ }+const translationNs = properties.find((prop) => isObjectProperty(prop) && isIdentifier(prop.key, { name: "translationNs" }))@@ -187,6 +197,7 @@ function processConfigProperties(icon: hasIcon,rank: rankValue,nested: nestedValue,+ group: groupValue,translationNs: translationNsValue,// Referenced by identifier at runtime rather than extracted here, so// the array may be computed instead of a string-literal list.@@ -248,6 +259,7 @@ function generateMenuItem(path: getRoute(file, routesDir),rank: config.rank,nested: config.nested,+ group: config.group,translationNs: config.translationNs? `${configName}.translationNs`: undefined,@@ -265,6 +277,7 @@ export function formatMenuItem(menuItem: MenuItem): string {` path: "${menuItem.path}"`,` rank: ${menuItem.rank !== undefined ? menuItem.rank : "undefined"}`,` nested: ${menuItem.nested ? `"${menuItem.nested}"` : "undefined"}`,+ ` group: ${menuItem.group ? JSON.stringify(menuItem.group) : "undefined"}`,` translationNs: ${menuItem.translationNs || "undefined"}`,` permissions: ${menuItem.permissions || "undefined"}`,` requireAll: ${menuItem.requireAll !== undefined ? menuItem.requireAll : "undefined"}`,diff --git a/packages/dashboard-sdk/src/types.ts b/packages/dashboard-sdk/src/types.tsindex bf5adc6d3..1e61376c8 100644--- a/packages/dashboard-sdk/src/types.ts+++ b/packages/dashboard-sdk/src/types.ts@@ -1,4 +1,5 @@import { ComponentType, ReactNode } from "react";+import type { NavGroupId } from "./config/types";import type { Permission } from "./permissions";/**@@ -70,6 +71,12 @@ export type RouteConfig = {icon?: ComponentTyperank?: numbernested?: string+ /**+ * Sidebar group to list the route under: one declared in `_navigation.ts`+ * or, for a `/settings/*` route, a built-in settings group. Must be a+ * string literal.+ */+ group?: NavGroupId | (string & {})translationNs?: stringpublic?: boolean/**diff --git a/packages/dashboard-shared/src/extensions/index.ts b/packages/dashboard-shared/src/extensions/index.tsindex bb9415ef0..fe6b1e788 100644--- a/packages/dashboard-shared/src/extensions/index.ts+++ b/packages/dashboard-shared/src/extensions/index.ts@@ -17,7 +17,15 @@ export {} from "./context"export { WidgetZone, type WidgetZoneProps } from "./widget-zone"export { useWidgetTabs, type WidgetTab, type WidgetTabs } from "./use-widget-tabs"-export { applyNavOverrides, type CoreNavItem } from "./nav"+export {+ applyNavOverrides,+ applyNavGroups,+ groupNavItems,+ type NavItemGroup,+ type CoreNavItem,+ type NavGroup,+ type NavGroupItem,+} from "./nav"export {FormExtensionZone,type FormExtensionZoneProps,diff --git a/packages/dashboard-shared/src/extensions/nav.spec.ts b/packages/dashboard-shared/src/extensions/nav.spec.tsnew file mode 100644index 000000000..583f4fb00--- /dev/null+++ b/packages/dashboard-shared/src/extensions/nav.spec.ts@@ -0,0 +1,156 @@+import { describe, expect, test } from "vitest"++import { applyNavGroups, groupNavItems, type NavGroup } from "./nav"++const item = (to: string) => ({ id: to.replace(/^\//, ""), label: to, to })++const coreGroups = (): NavGroup[] => [+ {+ id: "general",+ label: "General",+ items: [item("/settings/users"), item("/settings/regions")],+ },+ {+ id: "developer",+ label: "Developer",+ items: [item("/settings/secret-api-keys")],+ },+ { id: "myAccount", label: "My Account", items: [item("/settings/profile")] },+]++const shape = (groups: NavGroup[]) =>+ groups.map((g) => [g.id, g.items.map((i) => i.to)])++describe("applyNavGroups", () => {+ test("returns the built-in groups unchanged without config", () => {+ expect(shape(applyNavGroups(coreGroups()))).toEqual([+ ["general", ["/settings/users", "/settings/regions"]],+ ["developer", ["/settings/secret-api-keys"]],+ ["myAccount", ["/settings/profile"]],+ ])+ })++ test("lists extension routes in their group, defaulting to the first", () => {+ const groups = applyNavGroups(coreGroups(), [+ { ...item("/settings/webhooks"), group: "developer", rank: 2 },+ { ...item("/settings/audit"), group: "developer", rank: 1 },+ item("/settings/erp"),+ { ...item("/settings/typo"), group: "nope" },+ ])++ expect(shape(groups)).toEqual([+ [+ "general",+ [+ "/settings/users",+ "/settings/regions",+ "/settings/erp",+ "/settings/typo",+ ],+ ],+ [+ "developer",+ ["/settings/secret-api-keys", "/settings/audit", "/settings/webhooks"],+ ],+ ["myAccount", ["/settings/profile"]],+ ])+ })++ test("declares a new group and moves built-in items into it", () => {+ const groups = applyNavGroups(+ coreGroups(),+ [{ ...item("/settings/erp"), group: "integrations" }],+ {+ groups: [+ { id: "integrations", label: "nav.integrations", translationNs: "erp", rank: 1 },+ ],+ items: [{ id: "settings/secret-api-keys", group: "integrations" }],+ }+ )++ expect(shape(groups)).toEqual([+ ["general", ["/settings/users", "/settings/regions"]],+ ["integrations", ["/settings/secret-api-keys", "/settings/erp"]],+ ["myAccount", ["/settings/profile"]],+ ])+ expect(groups[1]).toMatchObject({+ label: "nav.integrations",+ translationNs: "erp",+ })+ })++ test("appends new groups after the built-ins and falls back to the id as label", () => {+ const groups = applyNavGroups(coreGroups(), [], {+ groups: [{ id: "billing" }],+ items: [{ id: "settings/regions", group: "billing" }],+ })++ expect(groups.map((g) => [g.id, g.label])).toEqual([+ ["general", "General"],+ ["developer", "Developer"],+ ["myAccount", "My Account"],+ ["billing", "billing"],+ ])+ })++ test("overrides a built-in group's label, rank and visibility", () => {+ const groups = applyNavGroups(coreGroups(), [], {+ groups: [+ { id: "myAccount", rank: -1 },+ { id: "developer", hidden: true },+ { id: "general", label: "Marketplace" },+ ],+ })++ expect(groups.map((g) => [g.id, g.label])).toEqual([+ ["myAccount", "My Account"],+ ["general", "Marketplace"],+ ])+ })++ test("applies rank, hidden and label overrides to items", () => {+ const groups = applyNavGroups(coreGroups(), [], {+ items: [+ { id: "settings/regions", rank: -1, label: "Markets" },+ { id: "settings/secret-api-keys", hidden: true },+ ],+ })++ expect(groups.map((g) => [g.id, g.items.map((i) => i.label)])).toEqual([+ ["general", ["Markets", "/settings/users"]],+ ["myAccount", ["/settings/profile"]],+ ])+ })+})++describe("groupNavItems", () => {+ const items = [+ { to: "/orders" },+ { to: "/products", group: "catalog" },+ { to: "/payouts", group: "finance" },+ { to: "/inventory", group: "catalog" },+ { to: "/reviews", group: "undeclared" },+ { to: "/secret", group: "internal" },+ ]++ test("keeps everything ungrouped without declared groups", () => {+ expect(groupNavItems(items)).toEqual({ ungrouped: items, groups: [] })+ })++ test("splits items into declared groups ordered by rank", () => {+ const result = groupNavItems(items, [+ { id: "catalog", label: "Catalog" },+ { id: "finance", rank: -1 },+ { id: "internal", hidden: true },+ { id: "empty", label: "Empty" },+ ])++ expect(result.ungrouped.map((i) => i.to)).toEqual(["/orders", "/reviews"])+ expect(+ result.groups.map((g) => [g.id, g.label, g.items.map((i) => i.to)])+ ).toEqual([+ ["finance", "finance", ["/payouts"]],+ ["catalog", "Catalog", ["/products", "/inventory"]],+ ])+ })+})diff --git a/packages/dashboard-shared/src/extensions/nav.ts b/packages/dashboard-shared/src/extensions/nav.tsindex 66be93228..64e96aaf1 100644--- a/packages/dashboard-shared/src/extensions/nav.ts+++ b/packages/dashboard-shared/src/extensions/nav.ts@@ -1,5 +1,5 @@import { createElement, type ReactNode } from "react"-import type { NavItemOverride } from "@mercurjs/dashboard-sdk"+import type { NavGroupConfig, NavItemOverride } from "@mercurjs/dashboard-sdk"export type CoreNavItem = {id: string@@ -74,3 +74,167 @@ export function applyNavOverrides(return items.length ? { ...f.item, items } : f.item})}++export type NavGroupItem = {+ id: string+ label: string+ to: string+ translationNs?: string+}++export type NavGroup = {+ id: string+ label: string+ translationNs?: string+ items: NavGroupItem[]+}++type ExtensionNavGroupItem = NavGroupItem & { group?: string; rank?: number }++/**+ * Resolves the grouped settings sidebar: the panel's built-in groups, plus the+ * groups and per-item overrides (`group`/`rank`/`hidden`/`label`) from the+ * host's `_navigation.ts`, plus extension routes placed by their route+ * config's `group`. An unknown group id falls back to the first built-in+ * group, extension routes list after a group's built-in items, and groups+ * left without items are dropped.+ */+export function applyNavGroups(+ coreGroups: NavGroup[],+ extensionItems: ExtensionNavGroupItem[] = [],+ config: {+ groups?: NavGroupConfig[]+ items?: NavItemOverride<string>[]+ } = {}+): NavGroup[] {+ type Def = Omit<NavGroup, "items"> & { rank: number; hidden: boolean }++ const defs = new Map<string, Def>()+ coreGroups.forEach((group, index) => {+ defs.set(group.id, {+ id: group.id,+ label: group.label,+ translationNs: group.translationNs,+ rank: index,+ hidden: false,+ })+ })++ let nextRank = coreGroups.length+ for (const group of config.groups ?? []) {+ if (!group?.id) continue+ const existing = defs.get(group.id)+ defs.set(group.id, {+ id: group.id,+ label: group.label ?? existing?.label ?? group.id,+ translationNs: group.label ? group.translationNs : existing?.translationNs,+ rank: group.rank ?? existing?.rank ?? nextRank++,+ hidden: group.hidden ?? existing?.hidden ?? false,+ })+ }++ const fallbackId = coreGroups[0]?.id+ const resolveGroup = (id: string | undefined, defaultId?: string) =>+ id && defs.has(id) ? id : defaultId ?? fallbackId++ const overrideById = new Map<string, NavItemOverride<string>>()+ for (const o of config.items ?? []) {+ if (o?.id) overrideById.set(o.id, o)+ }++ const buckets = new Map<string, { item: NavGroupItem; rank: number }[]>()+ const place = (groupId: string | undefined, item: NavGroupItem, rank: number) => {+ if (!groupId) return+ const bucket = buckets.get(groupId) ?? []+ bucket.push({ item, rank })+ buckets.set(groupId, bucket)+ }++ let order = 0+ for (const group of coreGroups) {+ for (const item of group.items) {+ const o = overrideById.get(item.id)+ const rank = o?.rank ?? order+++ if (o?.hidden) continue+ place(+ resolveGroup(o?.group, group.id),+ { ...item, label: o?.label ?? item.label },+ rank+ )+ }+ }++ const extensions = new Map<string, { item: NavGroupItem; rank: number }[]>()+ for (const { group, rank, ...item } of extensionItems) {+ const groupId = resolveGroup(group)+ if (!groupId) continue+ const bucket = extensions.get(groupId) ?? []+ bucket.push({ item, rank: rank ?? 0 })+ extensions.set(groupId, bucket)+ }++ const byRank = (a: { rank: number }, b: { rank: number }) => a.rank - b.rank++ return [...defs.values()]+ .filter((def) => !def.hidden)+ .sort(byRank)+ .map(({ id, label, translationNs }) => ({+ id,+ label,+ translationNs,+ items: [+ ...(buckets.get(id) ?? []).sort(byRank),+ ...(extensions.get(id) ?? []).sort(byRank),+ ].map(({ item }) => item),+ }))+ .filter((group) => group.items.length > 0)+}++export type NavItemGroup<T> = {+ id: string+ label: string+ translationNs?: string+ items: T[]+}++/**+ * Splits main sidebar items into the ungrouped list and the groups declared in+ * the host's `_navigation.ts`. The main sidebar has no built-in groups, so an+ * item whose group isn't declared stays ungrouped. Item order is preserved.+ */+export function groupNavItems<T extends { group?: string }>(+ items: T[],+ groups: NavGroupConfig[] = []+): { ungrouped: T[]; groups: NavItemGroup<T>[] } {+ const defs = new Map<string, NavGroupConfig & { rank: number }>()+ groups.forEach((group, index) => {+ if (group?.id) defs.set(group.id, { ...group, rank: group.rank ?? index })+ })++ const ungrouped: T[] = []+ const buckets = new Map<string, T[]>()+ for (const item of items) {+ const def = item.group ? defs.get(item.group) : undefined+ if (!def) {+ ungrouped.push(item)+ continue+ }+ if (def.hidden) continue+ const bucket = buckets.get(def.id) ?? []+ bucket.push(item)+ buckets.set(def.id, bucket)+ }++ return {+ ungrouped,+ groups: [...defs.values()]+ .filter((def) => buckets.has(def.id))+ .sort((a, b) => a.rank - b.rank)+ .map((def) => ({+ id: def.id,+ label: def.label ?? def.id,+ translationNs: def.label ? def.translationNs : undefined,+ items: buckets.get(def.id) ?? [],+ })),+ }+}diff --git a/packages/dashboard-shared/src/extensions/registry.ts b/packages/dashboard-shared/src/extensions/registry.tsindex 0230e8779..97940892c 100644--- a/packages/dashboard-shared/src/extensions/registry.ts+++ b/packages/dashboard-shared/src/extensions/registry.ts@@ -5,6 +5,7 @@ import type {CustomFieldsConfig,CustomFormField,CustomListExtension,+ NavGroupConfig,NavItemOverride,Permission,SectionAction,@@ -21,7 +22,10 @@ export type Widget = {}export type WidgetModule = { widgets?: Widget[] }-export type NavigationModule = { items?: NavItemOverride[] }+export type NavigationModule = {+ groups?: NavGroupConfig[]+ items?: NavItemOverride<string>[]+}export type CustomFieldsModule = { configs?: CustomFieldsConfig[] }export type ResolvedFormField = { name: string; field: CustomFormField }@@ -63,7 +67,8 @@ function splitZone(zone: string): { slot: string; placement: WidgetPlacement } {*/export class ExtensionRegistry {private widgets = new Map<string, ZoneWidgets>()- private navOverrides: NavItemOverride[] = []+ private navOverrides: NavItemOverride<string>[] = []+ private navGroups: NavGroupConfig[] = []private customFields: CustomFieldsConfig[] = []constructor(@@ -75,6 +80,7 @@ export class ExtensionRegistry {) {this.populateWidgets(input.widgets?.widgets ?? [])this.navOverrides = input.navigation?.items ?? []+ this.navGroups = input.navigation?.groups ?? []this.customFields = input.customFields?.configs ?? []}@@ -108,10 +114,14 @@ export class ExtensionRegistry {return this.widgets.get(slot) ?? { before: [], after: [] }}- getNavOverrides(): NavItemOverride[] {+ getNavOverrides(): NavItemOverride<string>[] {return this.navOverrides}+ getNavGroups(): NavGroupConfig[] {+ return this.navGroups+ }+private configsFor(model: string): CustomFieldsConfig[] {return this.customFields.filter((c) => c.model === model)}diff --git a/packages/vendor/scripts/generate-extension-targets.ts b/packages/vendor/scripts/generate-extension-targets.tsindex 1e7a2f4e1..15b0f9fef 100644--- a/packages/vendor/scripts/generate-extension-targets.ts+++ b/packages/vendor/scripts/generate-extension-targets.ts@@ -6,6 +6,7 @@* - `<WidgetZone id="…">` usages, → WidgetZoneRegistry (+ placement suffixes)* `useWidgetTabs("…")` calls* - `useCoreRoutes()` `to:` literals → NavItemRegistry / NavParentRegistry+ * - settings sidebar `to:` / group `id:` → NavItemRegistry / NavGroupRegistry* - `<FormExtensionZone model zone>` / → CustomFieldsRegistry (form/display zones)* `<DisplayExtensionZone model zone>`*@@ -86,6 +87,26 @@ function collectNav(mainLayout: string): { items: Set<string>; parents: Set<strireturn { items, parents }}+function collectSettingsNav(settingsLayout: string): {+ items: Set<string>+ groups: Set<string>+} {+ const items = new Set<string>()+ const groups = new Set<string>()+ const code = fs+ .readFileSync(settingsLayout, "utf-8")+ .replace(/\/\*[\s\S]*?\*\//g, "")+ .replace(/\/\/[^\n]*/g, "")++ let m: RegExpExecArray | null+ const toRe = /\bto:\s*["'`](\/settings\/[^"'`]+)["'`]/g+ while ((m = toRe.exec(code))) items.add(m[1].replace(/^\//, ""))+ const groupRe = /\bid:\s*["'`]([^"'`]+)["'`]/g+ while ((m = groupRe.exec(code))) groups.add(m[1])++ return { items, groups }+}+type ModelZones = {formZones: Set<string>displayZones: Set<string>@@ -268,6 +289,18 @@ function main() {? collectNav(mainLayout): { items: new Set<string>(), parents: new Set<string>() }+ const settingsLayout = path.join(+ SRC,+ "components",+ "layout",+ "settings-layout",+ "settings-layout.tsx"+ )+ const settingsNav = fs.existsSync(settingsLayout)+ ? collectSettingsNav(settingsLayout)+ : { items: new Set<string>(), groups: new Set<string>() }+ for (const id of settingsNav.items) nav.items.add(id)+const models = collectCustomFields(files)const contents = `// GENERATED by scripts/generate-extension-targets.ts — do not edit by hand.@@ -287,6 +320,10 @@ ${keys(nav.items)}${keys(nav.parents)}}+ interface NavGroupRegistry {+${keys(settingsNav.groups)}+ }+${customFieldsBlock(models)}}`@@ -302,7 +339,7 @@ ${customFieldsBlock(models)}}console.log(- `extension-targets.d.ts: ${zoneIds.size} widget zones, ${nav.items.size} nav items, ${nav.parents.size} nav parents, ${models.size} custom-field models`+ `extension-targets.d.ts: ${zoneIds.size} widget zones, ${nav.items.size} nav items, ${nav.parents.size} nav parents, ${settingsNav.groups.size} nav groups, ${models.size} custom-field models`)}diff --git a/packages/vendor/src/components/layout/main-layout/main-layout.tsx b/packages/vendor/src/components/layout/main-layout/main-layout.tsxindex 3d7193e3a..c122d08ad 100644--- a/packages/vendor/src/components/layout/main-layout/main-layout.tsx+++ b/packages/vendor/src/components/layout/main-layout/main-layout.tsx@@ -33,6 +33,8 @@ import { useDocumentDirection } from "../../../hooks/use-document-direction";import menuItemsModule from "virtual:mercur/menu-items";import {applyNavOverrides,+ groupNavItems,+ type NavItemGroup,useExtension,usePermissions,type CoreNavItem,@@ -87,9 +89,12 @@ const addNestedItems = (return [...(items ?? []), ...nestedNavItems];};+type SidebarRoute = Omit<INavItem, "pathname"> & { group?: string };+const useSidebarRoutes = () => {const coreRoutes = useCoreRoutes();- const navOverrides = useExtension().getNavOverrides();+ const extension = useExtension();+ const navOverrides = extension.getNavOverrides();const permissions = usePermissions();const { hasAnyPermission, hasAllPermissions } = permissions;@@ -129,23 +134,37 @@ const useSidebarRoutes = () => {to: item.path,icon: Icon ? <Icon /> : undefined,translationNs: item.translationNs,+ group: item.group,items: addNestedItems(item.path, visibleMenuItems),};});- return { routesWithNested, customRoutesWithNested };+ const groupById = new Map<string, string | undefined>(+ navOverrides.map((o) => [o.id, o.group]),+ );++ return groupNavItems<SidebarRoute>(+ [+ ...routesWithNested.map((route) => ({+ ...route,+ group: groupById.get(route.id),+ })),+ ...customRoutesWithNested,+ ],+ extension.getNavGroups(),+ );};// First sidebar entry the actor can open, in sidebar order. Falls back to the// profile page, which needs no permission.export const useLandingRoute = () => {- const { routesWithNested, customRoutesWithNested } = useSidebarRoutes();- const first = [...routesWithNested, ...customRoutesWithNested][0];+ const { ungrouped, groups } = useSidebarRoutes();+ const first = [...ungrouped, ...groups.flatMap((group) => group.items)][0];return first?.to ?? "/settings/profile";};const MainSidebar = () => {- const { routesWithNested, customRoutesWithNested } = useSidebarRoutes();+ const { ungrouped, groups } = useSidebarRoutes();return (<aside className="flex flex-1 flex-col justify-between overflow-y-auto overflow-x-hidden">@@ -160,12 +179,12 @@ const MainSidebar = () => {<div className="flex flex-1 flex-col"><nav className="flex flex-col gap-y-1 py-3"><Searchbar />- {routesWithNested.map((route) => {- return <NavItem key={route.to} {...route} />;- })}- {customRoutesWithNested.map((route) => (+ {ungrouped.map((route) => (<NavItem key={route.to} {...route} />))}+ {groups.map((group) => (+ <SidebarGroup key={group.id} group={group} />+ ))}</nav></div><UtilitySection />@@ -179,6 +198,33 @@ const MainSidebar = () => {);};+const SidebarGroup = ({ group }: { group: NavItemGroup<SidebarRoute> }) => {+ const { t } = useTranslation(group.translationNs);++ return (+ <div+ className="flex flex-col gap-y-1 pt-2"+ data-testid={`sidebar-group-${group.id}`}+ >+ <div className="px-3">+ <div+ className={clx(+ "flex h-7 items-center overflow-hidden whitespace-nowrap px-2 text-ui-fg-muted",+ SIDEBAR_RAIL_FADE,+ )}+ >+ <Text size="small" leading="compact">+ {group.translationNs ? t(group.label) : group.label}+ </Text>+ </div>+ </div>+ {group.items.map((route) => (+ <NavItem key={route.to} {...route} />+ ))}+ </div>+ );+};+const StoreList = ({ currentSellerId }: { currentSellerId: string }) => {const { t } = useTranslation();const navigate = useNavigate();diff --git a/packages/vendor/src/components/layout/settings-layout/settings-layout.tsx b/packages/vendor/src/components/layout/settings-layout/settings-layout.tsxindex a110a9eef..1b5930813 100644--- a/packages/vendor/src/components/layout/settings-layout/settings-layout.tsx+++ b/packages/vendor/src/components/layout/settings-layout/settings-layout.tsx@@ -1,7 +1,7 @@import { ArrowUturnLeft, MinusMini } from "@medusajs/icons";import { clx, Divider, IconButton, Text } from "@medusajs/ui";import { Collapsible as RadixCollapsible } from "radix-ui";-import { useEffect, useMemo, useState } from "react";+import { Fragment, useCallback, useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { Link, useLocation } from "react-router-dom";@@ -9,7 +9,13 @@ import { INavItem, NavItem } from "../nav-item";import { Shell } from "../shell";import { UserMenu } from "../user-menu";import menuItemsModule from "virtual:mercur/menu-items";-import { usePermissions } from "@mercurjs/dashboard-shared";+import {+ type NavGroup,+ type NavGroupItem,+ applyNavGroups,+ useExtension,+ usePermissions,+} from "@mercurjs/dashboard-shared";import { useExpandedSidebar } from "../../../providers/sidebar-provider";import {filterMenuItemsByPermissions,@@ -30,8 +36,17 @@ export const SettingsLayout = () => {const allMenuItems = menuItemsModule.menuItems ?? [];-const useExtensionNavItems = (): INavItem[] => {+const navId = (to: string) => to.replace(/^\//, "");++const toGroupItem = ({ label, to }: INavItem): NavGroupItem => ({+ id: navId(to),+ label,+ to,+});++const useExtensionNavItems = () => {const { hasAnyPermission, hasAllPermissions } = usePermissions();+ const canReach = useCanReach();return useMemo(() =>@@ -42,19 +57,21 @@ const useExtensionNavItems = (): INavItem[] => {}),"settings",)- .sort((a, b) => (a.rank ?? 0) - (b.rank ?? 0)).map((item) => ({+ id: navId(item.path),label: item.label,to: item.path,translationNs: item.translationNs,- })),- [hasAnyPermission, hasAllPermissions],+ group: item.group,+ rank: item.rank,+ }))+ .filter(canReach),+ [hasAnyPermission, hasAllPermissions, canReach],);};const useSettingRoutes = (): INavItem[] => {const { t } = useTranslation();- const extensionNavItems = useExtensionNavItems();return useMemo(() => [@@ -82,9 +99,8 @@ const useSettingRoutes = (): INavItem[] => {label: t("stockLocations.domain"),to: "/settings/locations",},- ...extensionNavItems,],- [t, extensionNavItems],+ [t],);};@@ -105,7 +121,38 @@ const getSafeFromValue = (from: string, landing: string) => {const useCanReach = () => {const permissions = usePermissions();- return ({ to }: INavItem) => canReachRoute(permissions, to);+ return useCallback(+ ({ to }: { to: string }) => canReachRoute(permissions, to),+ [permissions],+ );+};++const useSettingsGroups = (): NavGroup[] => {+ const { t } = useTranslation();+ const canReach = useCanReach();+ const extension = useExtension();++ const routes = useSettingRoutes();+ const extensionNavItems = useExtensionNavItems();++ return useMemo(+ () =>+ applyNavGroups(+ [+ {+ id: "general",+ label: t("app.nav.settings.general"),+ items: routes.filter(canReach).map(toGroupItem),+ },+ ],+ extensionNavItems,+ {+ groups: extension.getNavGroups(),+ items: extension.getNavOverrides(),+ },+ ),+ [t, canReach, extension, routes, extensionNavItems],+ );};const PROFILE_ROUTE = "/settings/profile";@@ -113,18 +160,13 @@ const PROFILE_ROUTE = "/settings/profile";// Where `/settings` lands: the first settings page the actor can open, or// their own profile, which needs no permission.export const useSettingsLandingRoute = () => {- const canReach = useCanReach();- const routes = useSettingRoutes().filter(canReach);+ const routes = useSettingsGroups().flatMap((group) => group.items);return routes.find(({ to }) => to !== PROFILE_ROUTE)?.to ?? PROFILE_ROUTE;};const SettingsSidebar = () => {- const canReach = useCanReach();-- const generalRoutes = useSettingRoutes().filter(canReach);-- const { t } = useTranslation();+ const groups = useSettingsGroups();return (<aside className="relative flex flex-1 flex-col justify-between overflow-y-auto">@@ -136,10 +178,16 @@ const SettingsSidebar = () => {</div><div className="flex flex-1 flex-col"><div className="flex flex-1 flex-col overflow-y-auto">- <RadixCollapsibleSection- label={t("app.nav.settings.general")}- items={generalRoutes}- />+ {groups.map((group, index) => (+ <Fragment key={group.id}>+ {index > 0 && (+ <div className="flex items-center justify-center px-3">+ <Divider variant="dashed" />+ </div>+ )}+ <RadixCollapsibleSection group={group} />+ </Fragment>+ ))}</div><div className="bg-ui-bg-subtle sticky bottom-0"><UserSection />@@ -186,13 +234,10 @@ const Header = () => {);};-const RadixCollapsibleSection = ({- label,- items,-}: {- label: string;- items: INavItem[];-}) => {+const RadixCollapsibleSection = ({ group }: { group: NavGroup }) => {+ const { t } = useTranslation(group.translationNs);+ const label = group.translationNs ? t(group.label) : group.label;+return (<RadixCollapsible.Root defaultOpen className="py-3"><div className="px-3">@@ -210,7 +255,7 @@ const RadixCollapsibleSection = ({<RadixCollapsible.Content><div className="pt-0.5"><nav className="flex flex-col gap-y-0.5">- {items.map((setting) => (+ {group.items.map(({ id: _id, ...setting }) => (<NavItem key={setting.to} type="setting" {...setting} />))}</nav>diff --git a/packages/vendor/src/extension-targets.d.ts b/packages/vendor/src/extension-targets.d.tsindex 2bd59b6cc..b2af10256 100644--- a/packages/vendor/src/extension-targets.d.ts+++ b/packages/vendor/src/extension-targets.d.ts@@ -149,6 +149,12 @@ declare module "@mercurjs/dashboard-sdk" {"promotions": true"reservations": true"reviews": true+ "settings/locations": true+ "settings/product-tags": true+ "settings/product-types": true+ "settings/profile": true+ "settings/store": true+ "settings/users": true}interface NavParentRegistry {@@ -162,6 +168,10 @@ declare module "@mercurjs/dashboard-sdk" {"reviews": true}+ interface NavGroupRegistry {+ "general": true+ }+interface CustomFieldsRegistry {"campaign": {formZones: "edit"diff --git a/packages/vendor/src/utils/routes.ts b/packages/vendor/src/utils/routes.tsindex 5f7a91ead..40faa87ec 100644--- a/packages/vendor/src/utils/routes.ts+++ b/packages/vendor/src/utils/routes.ts@@ -18,6 +18,7 @@ export type MenuItem = {path: stringrank?: numbernested?: string+ group?: stringtranslationNs?: stringpermissions?: Permission[]requireAll?: booleandiff --git a/templates/basic/apps/admin/src/README.md b/templates/basic/apps/admin/src/README.mdindex 0b386e048..80cf00550 100644--- a/templates/basic/apps/admin/src/README.md+++ b/templates/basic/apps/admin/src/README.md@@ -73,6 +73,7 @@ export default BlogPage| `icon` | `ComponentType` | Icon component shown next to the label || `rank` | `number` | Controls ordering in the sidebar || `nested` | `string` | Parent menu item path to nest under |+| `group` | `string` | Sidebar group declared in `_navigation.ts` to list the item under || `translationNs` | `string` | i18n translation namespace for the label |## 4. Add Data Loading@@ -213,5 +214,22 @@ export default defineNavigationConfig({})```+Group sidebar items under headings by declaring a keyword in `groups` and+assigning items to it with `group`. It works for the main sidebar and for+settings items (`settings/<segment>`):++```ts+export default defineNavigationConfig({+ groups: [+ { id: "catalog", label: "Catalog" },+ { id: "integrations", label: "Integrations" },+ ],+ items: [+ { id: "products", group: "catalog" },+ { id: "settings/users", group: "integrations" },+ ],+})+```+> See the full contract in the Mercur documentation (SPEC-021, Panel Extension> API).diff --git a/templates/basic/apps/vendor/src/README.md b/templates/basic/apps/vendor/src/README.mdindex 59297343f..6192ed66b 100644--- a/templates/basic/apps/vendor/src/README.md+++ b/templates/basic/apps/vendor/src/README.md@@ -73,6 +73,7 @@ export default BlogPage| `icon` | `ComponentType` | Icon component shown next to the label || `rank` | `number` | Controls ordering in the sidebar || `nested` | `string` | Parent menu item path to nest under |+| `group` | `string` | Sidebar group declared in `_navigation.ts` to list the item under || `translationNs` | `string` | i18n translation namespace for the label |## 4. Add Data Loading@@ -216,5 +217,22 @@ export default defineNavigationConfig({})```+Group sidebar items under headings by declaring a keyword in `groups` and+assigning items to it with `group`. It works for the main sidebar and for+settings items (`settings/<segment>`):++```ts+export default defineNavigationConfig({+ groups: [+ { id: "catalog", label: "Catalog" },+ { id: "integrations", label: "Integrations" },+ ],+ items: [+ { id: "products", group: "catalog" },+ { id: "settings/users", group: "integrations" },+ ],+})+```+> See the full contract in the Mercur documentation (SPEC-021, Panel Extension> API).