v3: fixed inconsistent page titles
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 41s
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 41s
This commit is contained in:
31
src/hooks/useDocumentTitle.ts
Normal file
31
src/hooks/useDocumentTitle.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { useEffect } from "react";
|
||||
|
||||
// The server injects the configured site name into both <title> and this meta
|
||||
// tag (see api/lib/static.ts / api/middleware/og.ts). Read it once at startup.
|
||||
// In the Vite dev server the placeholder isn't substituted, so fall back.
|
||||
function readSiteName(): string {
|
||||
const meta = document.querySelector('meta[name="site-name"]')
|
||||
?.getAttribute("content")?.trim();
|
||||
if (meta && meta !== "__SITE_NAME__") return meta;
|
||||
return "gerbeur";
|
||||
}
|
||||
|
||||
export const SITE_NAME = readSiteName();
|
||||
|
||||
/**
|
||||
* Keeps document.title in sync with the current page during client-side
|
||||
* navigation. Without this the tab title only ever reflects the server-rendered
|
||||
* <title> from the initial page load and goes stale on every SPA navigation.
|
||||
*
|
||||
* - Pass a non-empty string to show `<title> · <site name>`.
|
||||
* - Pass `null` to show just the site name (home / generic pages).
|
||||
* - Pass `undefined` while the page-specific title is still loading: the title
|
||||
* is left untouched, so a server-rendered OG title survives until data
|
||||
* arrives (avoids a flash to the bare site name on direct loads).
|
||||
*/
|
||||
export function useDocumentTitle(title: string | null | undefined): void {
|
||||
useEffect(() => {
|
||||
if (title === undefined) return;
|
||||
document.title = title ? `${title} · ${SITE_NAME}` : SITE_NAME;
|
||||
}, [title]);
|
||||
}
|
||||
Reference in New Issue
Block a user