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.

fix(dashboard): merge plugin i18n and hoist index breadcrumbs onto branches (#1511)

Viktor Holik44e529c8b761
diff --git a/packages/admin/src/utils/__tests__/routes.spec.ts b/packages/admin/src/utils/__tests__/routes.spec.ts
new file mode 100644
index 000000000..ee5b34214
--- /dev/null
+++ b/packages/admin/src/utils/__tests__/routes.spec.ts
@@ -0,0 +1,77 @@
+import { RouteObject } from "react-router-dom"
+import type { RouteHandle } from "@mercurjs/dashboard-sdk"
+import { describe, expect, test, vi } from "vitest"
+
+vi.mock("../../components/utilities/error-boundary", () => ({
+ ErrorBoundary: () => null,
+}))
+
+const { createRouteMap } = await import("../routes")
+
+const Component = () => null
+const listCrumb = () => "Roles"
+const detailCrumb = () => "Role"
+
+const find = (routes: RouteObject[] | undefined, path: string) =>
+ routes?.find((r) => r.path === path)
+
+const leafHandle = async (route: RouteObject | undefined) => {
+ const lazy = route?.lazy as (() => Promise<{ handle?: RouteHandle }>) | undefined
+ return (await lazy?.())?.handle
+}
+
+describe("createRouteMap breadcrumbs", () => {
+ test("list page crumb moves to the branch and is not duplicated", async () => {
+ const [roles] = createRouteMap(
+ [{ path: "/settings/roles", Component, handle: { breadcrumb: listCrumb } }],
+ "/settings"
+ )
+
+ expect((roles.handle as RouteHandle).breadcrumb).toBe(listCrumb)
+ expect(await leafHandle(find(roles.children, ""))).toBeUndefined()
+ })
+
+ test("detail page matches both the domain crumb and its own", async () => {
+ const [roles] = createRouteMap(
+ [
+ { path: "/settings/roles", Component, handle: { breadcrumb: listCrumb } },
+ { path: "/settings/roles/:id", Component, handle: { breadcrumb: detailCrumb } },
+ ],
+ "/settings"
+ )
+
+ const id = find(roles.children, ":id")
+ expect((roles.handle as RouteHandle).breadcrumb).toBe(listCrumb)
+ expect((id?.handle as RouteHandle | undefined)?.breadcrumb).toBe(detailCrumb)
+ expect(await leafHandle(find(id?.children, ""))).toBeUndefined()
+ })
+
+ test("permissions stay on the index leaf", async () => {
+ const [roles] = createRouteMap(
+ [
+ {
+ path: "/settings/roles",
+ Component,
+ handle: { breadcrumb: listCrumb, permissions: "role:read" } as RouteHandle,
+ },
+ ],
+ "/settings"
+ )
+
+ expect(roles.handle).toEqual({ breadcrumb: listCrumb })
+ expect(await leafHandle(find(roles.children, ""))).toEqual({ permissions: "role:read" })
+ })
+
+ test("a segment without an index page gets no branch handle", async () => {
+ const [ee] = createRouteMap(
+ [
+ { path: "/settings/ee/tos", Component, handle: { breadcrumb: () => "ToS" } },
+ { path: "/settings/ee/dispute-reasons", Component, handle: { breadcrumb: () => "DR" } },
+ ],
+ "/settings"
+ )
+
+ expect(ee.handle).toBeUndefined()
+ expect(find(ee.children, "tos")?.handle).toBeDefined()
+ })
+})
diff --git a/packages/admin/src/utils/routes.ts b/packages/admin/src/utils/routes.ts
index 38ca61918..754aa337c 100644
--- a/packages/admin/src/utils/routes.ts
+++ b/packages/admin/src/utils/routes.ts
@@ -32,6 +32,28 @@ const createBranchRoute = (segment: string): RouteObject => ({
children: [],
})
+/**
+ * Moves a segment index page's breadcrumb onto its branch so it keeps matching
+ * on every route below. Moved rather than copied, otherwise the list page would
+ * show the domain crumb twice.
+ */
+const hoistBreadcrumb = (
+ branch: RouteObject,
+ handle: RouteHandle | undefined,
+ isIndex: boolean
+): RouteHandle | undefined => {
+ const branchHandle = branch.handle as RouteHandle | undefined
+
+ if (!isIndex || !handle?.breadcrumb || branchHandle?.breadcrumb) {
+ return handle
+ }
+
+ branch.handle = { ...branchHandle, breadcrumb: handle.breadcrumb }
+
+ const { breadcrumb: _breadcrumb, ...rest } = handle
+ return Object.keys(rest).length ? rest : undefined
+}
+
/**
* Creates a route object for a leaf node with its component
* @param Component - The React component to render at this route
@@ -164,10 +186,12 @@ const addRoute = (
leaf.children = processParallelRoutes(parallelRoutes, currentFullPath)
Object.assign(route, leaf)
} else {
- // `handle` belongs on the leaf, not on the branch: branches are
- // shared between sibling routes at the same segment, so a branch
- // handle leaks onto every sibling below it.
- const leaf = createLeafRoute(Component, loader, handle)
+ // Permission keys stay on the leaf: branches are shared between sibling
+ // routes, so hoisting them would gate every route below on the index
+ // page's rules. `breadcrumb` is the exception, mirroring the hand-written
+ // settings tree in get-route-map.tsx.
+ const leafHandle = hoistBreadcrumb(route, handle, remainingSegments.length === 0)
+ const leaf = createLeafRoute(Component, loader, leafHandle)
leaf.children = processParallelRoutes(parallelRoutes, currentFullPath)
route.children.push(leaf)
}
diff --git a/packages/dashboard-sdk/src/__tests__/i18n.spec.ts b/packages/dashboard-sdk/src/__tests__/i18n.spec.ts
new file mode 100644
index 000000000..4a882c2bc
--- /dev/null
+++ b/packages/dashboard-sdk/src/__tests__/i18n.spec.ts
@@ -0,0 +1,94 @@
+import fs from "fs"
+import os from "os"
+import path from "path"
+import { afterEach, describe, expect, test } from "vitest"
+import { generateI18n } from "../i18n"
+import type { BuiltMercurConfig } from "../types"
+
+const tmpDirs: string[] = []
+
+const makeDir = () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mercur-i18n-"))
+ tmpDirs.push(dir)
+ return dir
+}
+
+const setup = async ({
+ app,
+ plugins = [],
+}: {
+ app?: Record<string, unknown>
+ plugins?: Record<string, unknown>[]
+}) => {
+ const root = makeDir()
+ const srcDir = path.join(root, "src")
+ fs.mkdirSync(srcDir)
+
+ if (app) {
+ fs.mkdirSync(path.join(srcDir, "i18n"))
+ fs.writeFileSync(
+ path.join(srcDir, "i18n", "index.ts"),
+ `export default ${JSON.stringify(app)}`
+ )
+ }
+
+ const pluginExtensions = plugins.map((i18nModule, i) => {
+ const file = path.join(root, `plugin-${i}.ts`)
+ fs.writeFileSync(file, `export default { i18nModule: ${JSON.stringify(i18nModule)} }`)
+ return file
+ })
+
+ const code = generateI18n({ srcDir, pluginExtensions } as unknown as BuiltMercurConfig)
+ const out = path.join(root, "virtual-i18n.ts")
+ fs.writeFileSync(out, code)
+
+ return (await import(out)).default
+}
+
+afterEach(() => {
+ for (const dir of tmpDirs.splice(0)) {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+})
+
+describe("generateI18n", () => {
+ test("no app file and no plugins yields empty resources", async () => {
+ expect(await setup({})).toEqual({})
+ })
+
+ test("app file only is returned verbatim", async () => {
+ const app = { en: { translation: { a: "1" } } }
+ expect(await setup({ app })).toEqual(app)
+ })
+
+ test("plugin resources are included", async () => {
+ const plugin = { en: { translation: { a: 1 } } }
+ expect(await setup({ plugins: [plugin] })).toEqual(plugin)
+ })
+
+ test("plugin and app deep-merge, app wins on conflicts", async () => {
+ const result = await setup({
+ plugins: [{ en: { translation: { x: { a: 1, c: "plugin" } } } }],
+ app: { en: { translation: { x: { b: 2, c: "app" } } } },
+ })
+ expect(result).toEqual({ en: { translation: { x: { a: 1, b: 2, c: "app" } } } })
+ })
+
+ test("languages from plugin and app are both kept", async () => {
+ const result = await setup({
+ plugins: [{ pl: { translation: { a: "pl" } } }],
+ app: { en: { translation: { a: "en" } } },
+ })
+ expect(result).toEqual({
+ pl: { translation: { a: "pl" } },
+ en: { translation: { a: "en" } },
+ })
+ })
+
+ test("later plugins win over earlier ones", async () => {
+ const result = await setup({
+ plugins: [{ en: { translation: { a: 1 } } }, { en: { translation: { a: 2 } } }],
+ })
+ expect(result).toEqual({ en: { translation: { a: 2 } } })
+ })
+})
diff --git a/packages/dashboard-sdk/src/i18n.ts b/packages/dashboard-sdk/src/i18n.ts
index 8e0e28b6a..596243e4c 100644
--- a/packages/dashboard-sdk/src/i18n.ts
+++ b/packages/dashboard-sdk/src/i18n.ts
@@ -21,15 +21,49 @@ function findI18nIndex(srcDir: string): string | null {
return null
}
-export function generateI18n({ srcDir }: BuiltMercurConfig): string {
+export function generateI18n({ srcDir, pluginExtensions }: BuiltMercurConfig): string {
const indexFile = findI18nIndex(srcDir)
- if (!indexFile) {
- return `export default {}`
- }
+ 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"] : []),
+ ]
- const importPath = normalizePath(indexFile)
+ // deepMerge is inlined because the virtual module has no runtime dependency on @mercurjs/admin.
+ return `${imports.join("\n")}
+
+function deepMerge(target, source) {
+ const result = { ...target }
+ for (const key of Object.keys(source)) {
+ const a = target[key]
+ const b = source[key]
+ result[key] =
+ a && b && typeof a === "object" && typeof b === "object" && !Array.isArray(a) && !Array.isArray(b)
+ ? deepMerge(a, b)
+ : b
+ }
+ return result
+}
+
+function mergeResources(target, source) {
+ const result = { ...target }
+ for (const lng of Object.keys(source)) {
+ result[lng] = { ...(result[lng] ?? {}) }
+ for (const ns of Object.keys(source[lng])) {
+ result[lng][ns] = deepMerge(result[lng][ns] ?? {}, source[lng][ns])
+ }
+ }
+ return result
+}
- return `import i18nResources from "${importPath}"
-export default i18nResources`
+export default [${sources.join(", ")}].reduce(mergeResources, {})
+`
}