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 10:28:52 +03:00
import { subscribeKey } from 'valtio/utils';
import states from './states';
2022-12-10 12:14:48 +03:00
2023-12-25 14:25:48 +03:00
const { PHANPY_CLIENT_NAME: CLIENT_NAME } = import.meta.env;
2022-12-10 12:14:48 +03:00
export default function useTitle(title, path) {
2023-04-14 10:28:52 +03: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 10:28:52 +03:00
if (matched) {
document.title = title ? `${title} / ${CLIENT_NAME}` : CLIENT_NAME;
}
2023-02-11 12:57:26 +03:00
}
2023-04-14 10:28:52 +03:00
useLayoutEffect(() => {
2023-09-10 10:29:52 +03:00
const unsub = subscribeKey(states, 'currentLocation', setTitle);
2023-04-14 10:28:52 +03:00
setTitle();
2023-09-10 10:29:52 +03:00
return unsub;
2023-04-14 10:28:52 +03:00
}, [title, path]);
2022-12-16 08:27:04 +03:00
}