phanpy/src/utils/useTitle.js

38 lines
1.2 KiB
JavaScript
Raw Normal View History

import { useLayoutEffect } from 'preact/hooks';
import { matchPath } from 'react-router-dom';
2023-04-14 07:28:52 +00:00
import { subscribeKey } from 'valtio/utils';
import states from './states';
2022-12-10 09:14:48 +00:00
2023-12-25 11:25:48 +00:00
const { PHANPY_CLIENT_NAME: CLIENT_NAME } = import.meta.env;
2022-12-10 09:14:48 +00:00
export default function useTitle(title, path) {
2023-04-14 07:28:52 +00:00
function setTitle() {
const { currentLocation } = states;
const hasPaths = Array.isArray(path);
let paths = hasPaths ? path : [];
// Workaround for matchPath not working for optional path segments
// https://github.com/remix-run/react-router/discussions/9862
if (!hasPaths && /:?\w+\?/.test(path)) {
paths.push(path.replace(/(:\w+)\?/g, '$1'));
paths.push(path.replace(/\/?:\w+\?/g, ''));
}
let matched = false;
if (paths.length) {
matched = paths.some((p) => matchPath(p, currentLocation));
} else if (path) {
matched = matchPath(path, currentLocation);
}
console.debug('setTitle', { title, path, currentLocation, paths, matched });
2023-04-14 07:28:52 +00:00
if (matched) {
document.title = title ? `${title} / ${CLIENT_NAME}` : CLIENT_NAME;
}
2023-02-11 09:57:26 +00:00
}
2023-04-14 07:28:52 +00:00
useLayoutEffect(() => {
2023-09-10 07:29:52 +00:00
const unsub = subscribeKey(states, 'currentLocation', setTitle);
2023-04-14 07:28:52 +00:00
setTitle();
2023-09-10 07:29:52 +00:00
return unsub;
2023-04-14 07:28:52 +00:00
}, [title, path]);
2022-12-16 05:27:04 +00:00
}