phanpy/src/utils/useTitle.js

37 lines
1.2 KiB
JavaScript
Raw Normal View History

2022-12-10 09:14:48 +00:00
import { useEffect } 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
const { VITE_CLIENT_NAME: CLIENT_NAME } = import.meta.env;
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.log('setTitle', { title, path, currentLocation, paths, matched });
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
2022-12-10 09:14:48 +00:00
useEffect(() => {
2023-04-14 07:28:52 +00:00
setTitle();
return subscribeKey(states, 'currentLocation', setTitle);
}, [title, path]);
2022-12-16 05:27:04 +00:00
}