feat(web): useDocumentTitle hook (restores prior title on unmount) (#57)
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { render } from "@testing-library/react";
|
||||
import "../i18n";
|
||||
import { ConfigProvider } from "../config/config-provider";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useDocumentTitle } from "./use-document-title";
|
||||
|
||||
function Titled({ page }: { page: string }) {
|
||||
useDocumentTitle(page);
|
||||
return null;
|
||||
}
|
||||
|
||||
function wrap(ui: React.ReactElement) {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<ConfigProvider>{ui}</ConfigProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
document.title = "";
|
||||
});
|
||||
|
||||
test("sets document.title to '{page} | {app_name}'", () => {
|
||||
wrap(<Titled page="Objects" />);
|
||||
expect(document.title).toMatch(/^Objects \| .+/);
|
||||
});
|
||||
|
||||
test("restores the previous title on unmount", () => {
|
||||
document.title = "Prev";
|
||||
const { unmount } = wrap(<Titled page="Objects" />);
|
||||
expect(document.title).toMatch(/^Objects \| /);
|
||||
unmount();
|
||||
expect(document.title).toBe("Prev");
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { useConfig } from "../config/config-context";
|
||||
|
||||
export function useDocumentTitle(page: string): void {
|
||||
const { app_name } = useConfig();
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof document === "undefined") return;
|
||||
|
||||
const previous = document.title;
|
||||
|
||||
document.title = `${page} | ${app_name}`;
|
||||
|
||||
return () => {
|
||||
document.title = previous;
|
||||
};
|
||||
}, [page, app_name]);
|
||||
}
|
||||
Reference in New Issue
Block a user