@daveyplate/next-page-title
Version:
Automatically set the page title in Next.js based on the current route, or override it with a custom title.
57 lines (56 loc) • 2.95 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.usePageTitle = void 0;
exports.PageTitleProvider = PageTitleProvider;
exports.PageTitle = PageTitle;
var jsx_runtime_1 = require("react/jsx-runtime");
var head_1 = __importDefault(require("next/head"));
var react_1 = require("react");
var router_1 = require("next/router");
var PageTitleContext = (0, react_1.createContext)(undefined);
/**
* Checks if the given path is a base path ("/" or "/[locale]")
*/
var isBasePath = function (path) { return path == "/" || path == "/[locale]"; };
function PageTitleProvider(_a) {
var children = _a.children, formatTitle = _a.formatTitle, _b = _a.siteName, siteName = _b === void 0 ? process.env.NEXT_PUBLIC_SITE_NAME : _b;
var router = (0, router_1.useRouter)();
var _c = (0, react_1.useState)(isBasePath(router.pathname) ? siteName : undefined), pageTitle = _c[0], setPageTitle = _c[1];
return ((0, jsx_runtime_1.jsxs)(PageTitleContext.Provider, { value: { pageTitle: pageTitle, setPageTitle: setPageTitle, formatTitle: formatTitle, siteName: siteName }, children: [(0, jsx_runtime_1.jsx)(PageTitle, {}), children] }));
}
var usePageTitle = function () {
var context = (0, react_1.useContext)(PageTitleContext);
if (!context) {
throw new Error("usePageTitle must be used within a PageTitleProvider");
}
return context;
};
exports.usePageTitle = usePageTitle;
function PageTitle(_a) {
var title = _a.title;
var router = (0, router_1.useRouter)();
var _b = (0, exports.usePageTitle)(), setPageTitle = _b.setPageTitle, formatTitle = _b.formatTitle, siteName = _b.siteName;
if (title == undefined) {
title = formatPathToTitle(router.pathname);
if (formatTitle) {
title = formatTitle(title);
}
}
(0, react_1.useEffect)(function () {
setPageTitle((isBasePath(router.pathname) ? siteName : title) || "");
}, [title, setPageTitle, router.pathname, siteName]);
return ((0, jsx_runtime_1.jsx)(head_1.default, { children: (0, jsx_runtime_1.jsx)("title", { children: isBasePath(router.pathname) ? siteName : (title ? "".concat(title, " | ").concat(siteName) : null) }) }));
}
/**
* Formats a path to a title string.
*/
function formatPathToTitle(path) {
var firstPart = path === null || path === void 0 ? void 0 : path.split('/').filter(Boolean).filter(function (segment) { return segment !== '[locale]'; }).shift(); // Take the first non-empty segment
// Replace hyphens with spaces and capitalize each word
return (firstPart === null || firstPart === void 0 ? void 0 : firstPart.replace("_", "").split('-').map(function (subPart) { return subPart.charAt(0).toUpperCase() + subPart.slice(1); }).join(' ') // Join the sub-parts with spaces
)
|| "";
}