Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,99 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { createRoutesStub, Link, Outlet } from "react-router";
import { HiveGridMeta } from "./HiveGridMeta";
afterEach(() => {
cleanup();
document.head.querySelectorAll("title").forEach((title) => title.remove());
});
describe("HiveGridMeta router integration", () => {
it("uses a loader-only leaf title and renders exactly one document title", async () => {
const Stub = createTitleRoutesStub({ leafData: { title: "Aufgaben" } });
render(<Stub initialEntries={["/tasks"]} />);
await waitFor(() => expect(document.title).toBe("Aufgaben | HiveGrid"));
expect(document.head.querySelectorAll("title")).toHaveLength(1);
});
it("normalizes a leaf route's explicit meta output", async () => {
const Stub = createTitleRoutesStub({ leafData: { title: "Kontakte | Application Starter" }, leafHasMeta: true });
render(<Stub initialEntries={["/tasks"]} />);
await waitFor(() => expect(document.title).toBe("Kontakte | HiveGrid"));
expect(document.head.querySelectorAll("title")).toHaveLength(1);
});
it("inherits the root title when the leaf exposes no page title", async () => {
const Stub = createTitleRoutesStub({ leafData: {} });
render(<Stub initialEntries={["/tasks"]} />);
await waitFor(() => expect(document.title).toBe("HiveGrid"));
expect(document.head.querySelectorAll("title")).toHaveLength(1);
});
it("updates the title after client-side navigation", async () => {
const Stub = createRoutesStub([
{
id: "root",
path: "/",
Component: () => (
<>
<HiveGridMeta />
<Link to="/contacts">Kontakte öffnen</Link>
<Outlet />
</>
),
loader: () => ({ metatags: [{ title: "HiveGrid" }] }),
HydrateFallback: () => null,
meta: ({ data }) => (data as { metatags: Array<{ title: string }> }).metatags,
children: [
{ id: "routes/tasks", path: "tasks", Component: () => <main>Tasks</main>, loader: () => ({ title: "Aufgaben" }) },
{ id: "routes/contacts", path: "contacts", Component: () => <main>Contacts</main>, loader: () => ({ title: "Kontakte" }) },
],
},
]);
render(<Stub initialEntries={["/tasks"]} />);
await waitFor(() => expect(document.title).toBe("Aufgaben | HiveGrid"));
fireEvent.click(screen.getByRole("link", { name: "Kontakte öffnen" }));
await waitFor(() => expect(document.title).toBe("Kontakte | HiveGrid"));
expect(document.head.querySelectorAll("title")).toHaveLength(1);
});
});
function createTitleRoutesStub({ leafData, leafHasMeta = false }: { leafData: Record<string, unknown>; leafHasMeta?: boolean }) {
return createRoutesStub([
{
id: "root",
path: "/",
Component: () => (
<>
<HiveGridMeta />
<Outlet />
</>
),
loader: () => ({ metatags: [{ title: "HiveGrid" }] }),
HydrateFallback: () => null,
meta: ({ data }) => (data as { metatags: Array<{ title: string }> }).metatags,
children: [
{
id: "routes/tasks",
path: "tasks",
Component: () => <main>Tasks</main>,
loader: () => leafData,
...(leafHasMeta
? {
meta: ({ data }: { data: unknown }) => [{ title: (data as { title: string }).title }],
}
: {}),
},
],
},
]);
}
@@ -0,0 +1,120 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import type { MetaDescriptor, MetaFunction } from "react-router";
import { createHiveGridMetaFunction, formatHiveGridDocumentTitle } from "./HiveGridMeta";
describe("HiveGrid document title contract", () => {
it.each([
["Dashboard", "Dashboard | HiveGrid"],
["Dashboard | HiveGrid", "Dashboard | HiveGrid"],
["Dashboard | HiveGrid | HiveGrid", "Dashboard | HiveGrid"],
["Dashboard | Application Starter", "Dashboard | HiveGrid"],
["Aufgabe · Heizungswartung | Wissensbasis | HiveGrid", "Aufgabe · Heizungswartung | Wissensbasis | HiveGrid"],
["Küche | Bad", "Küche | Bad | HiveGrid"],
["HiveGrid", "HiveGrid"],
[" ", "HiveGrid"],
[undefined, "HiveGrid"],
])("normalizes %j to %j", (input, expected) => {
expect(formatHiveGridDocumentTitle(input)).toBe(expected);
});
it("normalizes an existing route meta title and keeps its other descriptors", () => {
const meta = createHiveGridMetaFunction(() => [
{ title: "Passwort vergessen | Anwendungsstarter" },
{ name: "description", content: "Passwort zurücksetzen" },
]);
expect(meta(metaArgs({ title: "ignored" }))).toEqual([
{ title: "Passwort vergessen | HiveGrid" },
{ name: "description", content: "Passwort zurücksetzen" },
]);
});
it("uses a loader title when a leaf route has no meta export", () => {
const meta = createHiveGridMetaFunction();
expect(meta(metaArgs({ title: "Benachrichtigungen" }, [{ title: "Dashboard | HiveGrid" }, { name: "robots", content: "noindex" }]))).toEqual([
{ title: "Benachrichtigungen | HiveGrid" },
{ name: "robots", content: "noindex" },
]);
});
it("replaces the configured app name without truncating pipes inside the page title", () => {
const meta = createHiveGridMetaFunction();
const rootData = { metatags: [{ title: "Lokale App" }] };
expect(meta(metaArgs({ title: "Küche | Bad | Lokale App" }, [], rootData))).toEqual([{ title: "Küche | Bad | HiveGrid" }]);
expect(meta(metaArgs({ title: "Küche | Bad" }, [], rootData))).toEqual([{ title: "Küche | Bad | HiveGrid" }]);
});
it("supports the shell's nested meta.title fallback", () => {
const meta = createHiveGridMetaFunction();
expect(meta(metaArgs({ meta: { title: "Profil" } }))).toEqual([{ title: "Profil | HiveGrid" }]);
});
it("uses loader metatags for routes without a meta export", () => {
const meta = createHiveGridMetaFunction();
expect(
meta(
metaArgs({
metatags: [{ title: "Kundenportal" }, { tagName: "link", rel: "canonical", href: "https://portal.hivegrid.de" }],
})
)
).toEqual([{ title: "Kundenportal | HiveGrid" }, { tagName: "link", rel: "canonical", href: "https://portal.hivegrid.de" }]);
});
it("inherits the parent metadata and de-duplicates title descriptors", () => {
const meta = createHiveGridMetaFunction();
expect(meta(metaArgs(undefined, [{ title: "Projekte | HiveGrid" }, { title: "stale" }, { property: "og:type", content: "website" }]))).toEqual([
{ title: "stale | HiveGrid" },
{ property: "og:type", content: "website" },
]);
});
it("falls back to the loader or parent title when an explicit meta function returns no title", () => {
const meta = createHiveGridMetaFunction(() => [{ name: "description", content: "Details" }]);
expect(meta(metaArgs({ title: "Aufgabendetail" }, [{ title: "Aufgaben | HiveGrid" }]))).toEqual([
{ title: "Aufgabendetail | HiveGrid" },
{ name: "description", content: "Details" },
]);
});
});
function metaArgs(data: unknown, parentMeta: MetaDescriptor[] = [], rootData?: unknown): Parameters<MetaFunction>[0] {
return {
data,
loaderData: data,
params: {},
location: {
pathname: "/acme/example",
search: "",
hash: "",
state: null,
key: "test",
},
matches: [
{
id: "root",
pathname: "/",
data: rootData,
loaderData: rootData,
params: {},
meta: parentMeta,
},
{
id: "routes/example",
pathname: "/acme/example",
data,
loaderData: data,
params: {},
meta: [],
},
],
} as Parameters<MetaFunction>[0];
}
@@ -0,0 +1,174 @@
import { useContext } from "react";
import { Meta, type MetaDescriptor, type MetaFunction, UNSAFE_FrameworkContext, useMatches } from "react-router";
import { defaultBrandTokens } from "@hivegrid/brand";
const HIVEGRID_PRODUCT_NAME = defaultBrandTokens.productName;
const TITLE_SEPARATOR = " | ";
const LEGACY_PRODUCT_NAMES = ["Application Starter", "Anwendungsstarter"] as const;
export function formatHiveGridDocumentTitle(rawTitle: unknown, configuredProductNames: readonly string[] = []): string {
if (typeof rawTitle !== "string") return HIVEGRID_PRODUCT_NAME;
const productNames = new Set(
[HIVEGRID_PRODUCT_NAME, ...LEGACY_PRODUCT_NAMES, ...configuredProductNames].map((name) => name.trim().toLocaleLowerCase()).filter(Boolean)
);
let pageTitle = rawTitle.trim();
// Strip only known product suffixes from the right. Page/entity names may
// legitimately contain pipes (for example "Küche | Bad") and must survive.
while (pageTitle) {
const separatorIndex = pageTitle.lastIndexOf("|");
const trailingSegment = pageTitle.slice(separatorIndex + 1).trim();
if (!productNames.has(trailingSegment.toLocaleLowerCase())) break;
pageTitle = separatorIndex >= 0 ? pageTitle.slice(0, separatorIndex).trim() : "";
}
if (!pageTitle) return HIVEGRID_PRODUCT_NAME;
return `${pageTitle}${TITLE_SEPARATOR}${HIVEGRID_PRODUCT_NAME}`;
}
export function createHiveGridMetaFunction(originalMeta?: MetaFunction): MetaFunction {
return (args) => {
const inheritedDescriptors = args.matches.at(-2)?.meta ?? [];
const loaderData = args.loaderData ?? args.data;
const loaderDescriptors = extractLoaderMetaDescriptors(loaderData);
const loaderTitle = extractLoaderTitle(loaderData);
const configuredProductNames = extractConfiguredProductNames(args);
let descriptors: MetaDescriptor[];
if (originalMeta) {
descriptors = flattenMetaDescriptors(originalMeta(args));
} else if (loaderDescriptors.length > 0) {
descriptors = loaderDescriptors;
} else {
descriptors = [...inheritedDescriptors];
}
// A route without `meta` can still expose the page title used by the shell
// and breadcrumbs. Prefer that title over the inherited parent title.
const titleOverride = !originalMeta && loaderTitle ? loaderTitle : undefined;
const fallbackTitle = loaderTitle ?? findDocumentTitle(inheritedDescriptors) ?? HIVEGRID_PRODUCT_NAME;
return enforceHiveGridTitle(descriptors, fallbackTitle, configuredProductNames, titleOverride);
};
}
/**
* React Router renders only the deepest route's metadata. This adapter keeps
* its renderer and route-level meta functions intact, but installs one title
* contract for Core, Admin, public pages and the customer portal. It also lets
* routes that already return `loaderData.title` participate without hundreds
* of repetitive `meta` exports.
*
* React Router is pinned in the workspace; the focused tests guard this small
* framework-context seam when the dependency is upgraded.
*/
export function HiveGridMeta() {
const frameworkContext = useContext(UNSAFE_FrameworkContext);
const activeRouteIds = new Set(useMatches().map((match) => match.id));
if (!frameworkContext) return <Meta />;
const routeModules = Object.fromEntries(
Object.entries(frameworkContext.routeModules).map(([routeId, routeModule]) => [
routeId,
routeModule && activeRouteIds.has(routeId)
? {
...routeModule,
meta: createHiveGridMetaFunction(routeModule.meta),
}
: routeModule,
])
) as typeof frameworkContext.routeModules;
return (
<UNSAFE_FrameworkContext.Provider value={{ ...frameworkContext, routeModules }}>
<Meta />
</UNSAFE_FrameworkContext.Provider>
);
}
function enforceHiveGridTitle(
descriptors: readonly MetaDescriptor[],
fallbackTitle: unknown,
configuredProductNames: readonly string[],
titleOverride?: string
): MetaDescriptor[] {
const flattened = flattenMetaDescriptors(descriptors);
const explicitTitle = titleOverride ?? findDocumentTitle(flattened);
const normalizedTitle = formatHiveGridDocumentTitle(explicitTitle ?? fallbackTitle, configuredProductNames);
const normalized: MetaDescriptor[] = [];
let titleInserted = false;
for (const descriptor of flattened) {
if (isDocumentTitleDescriptor(descriptor)) {
if (!titleInserted) {
normalized.push({ title: normalizedTitle });
titleInserted = true;
}
continue;
}
normalized.push(descriptor);
}
if (!titleInserted) normalized.unshift({ title: normalizedTitle });
return normalized;
}
function extractConfiguredProductNames(args: Parameters<MetaFunction>[0]): string[] {
const rootTitle = extractLoaderTitle(args.matches[0]?.loaderData);
if (!rootTitle) return [];
const configuredProductName = rootTitle.slice(rootTitle.lastIndexOf("|") + 1).trim();
return configuredProductName ? [configuredProductName] : [];
}
function extractLoaderTitle(loaderData: unknown): string | undefined {
if (!isRecord(loaderData)) return undefined;
const directTitle = nonEmptyString(loaderData.title);
if (directTitle) return directTitle;
if (isRecord(loaderData.meta)) {
const nestedTitle = nonEmptyString(loaderData.meta.title);
if (nestedTitle) return nestedTitle;
}
return findDocumentTitle(extractLoaderMetaDescriptors(loaderData));
}
function extractLoaderMetaDescriptors(loaderData: unknown): MetaDescriptor[] {
if (!isRecord(loaderData)) return [];
for (const key of ["metatags", "metadata"] as const) {
const descriptors = flattenMetaDescriptors(loaderData[key]);
if (descriptors.length > 0) return descriptors;
}
return [];
}
function findDocumentTitle(descriptors: readonly MetaDescriptor[]): string | undefined {
let title: string | undefined;
for (const descriptor of descriptors) {
if (!isDocumentTitleDescriptor(descriptor)) continue;
title = nonEmptyString(descriptor.title) ?? title;
}
return title;
}
function isDocumentTitleDescriptor(descriptor: MetaDescriptor): descriptor is MetaDescriptor & { title: unknown } {
return !("tagName" in descriptor) && "title" in descriptor;
}
function flattenMetaDescriptors(value: unknown): MetaDescriptor[] {
if (!Array.isArray(value)) return [];
return value.flat(1).filter(isRecord) as MetaDescriptor[];
}
function nonEmptyString(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
const normalized = value.trim();
return normalized.length > 0 ? normalized : undefined;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
@@ -1,6 +1,6 @@
import type { TFunction } from "i18next";
import type { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
type SiteTags = {
title: string;
@@ -1,5 +1,6 @@
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
import { i18nConfig } from "~/locale/i18n";
import { defaultLocale } from "~/locale/i18n";
import { enabledLocales } from "~/locale/i18next.server";
import { getBaseURL } from "~/utils/url.server";
export function getLinkTags(request: Request) {
@@ -7,16 +8,17 @@ export function getLinkTags(request: Request) {
const urlObj = new URL(request.url);
const pathname = `${baseUrl}${urlObj.pathname}`;
const searchParams = urlObj.searchParams;
const lng = searchParams.get("lng") ?? i18nConfig.fallbackLng;
const requestedLocale = searchParams.get("lng");
const lng = requestedLocale && enabledLocales.includes(requestedLocale as (typeof enabledLocales)[number]) ? requestedLocale : defaultLocale;
const linkTags: MetaTagsDto = [];
const canonicalHref = lng === i18nConfig.fallbackLng ? pathname : `${pathname}?lng=${lng}`;
const canonicalHref = lng === defaultLocale ? pathname : `${pathname}?lng=${lng}`;
linkTags.push({ property: "og:locale", content: lng });
linkTags.push({ tagName: "link", rel: "canonical", href: canonicalHref });
linkTags.push({ property: "og:url", content: canonicalHref });
i18nConfig.supportedLngs.forEach((supportedLng) => {
const href = supportedLng === i18nConfig.fallbackLng ? pathname : `${pathname}?lng=${supportedLng}`;
enabledLocales.forEach((supportedLng) => {
const href = supportedLng === defaultLocale ? pathname : `${pathname}?lng=${supportedLng}`;
linkTags.push({ tagName: "link", rel: "alternate", href, hrefLang: supportedLng });
});
linkTags.push({ tagName: "link", rel: "alternate", href: pathname, hrefLang: "x-default" });