2023-07-05 11:59:28 +03:00
|
|
|
import { useLayoutEffect } from 'preact/hooks';
|
2023-01-29 10:19:26 +03:00
|
|
|
import { matchPath } from 'react-router-dom';
|
2023-04-14 10:28:52 +03:00
|
|
|
import { subscribeKey } from 'valtio/utils';
|
2023-01-29 10:19:26 +03:00
|
|
|
|
|
|
|
import states from './states';
|
2022-12-10 12:14:48 +03:00
|
|
|
|
|
|
|
const { VITE_CLIENT_NAME: CLIENT_NAME } = import.meta.env;
|
|
|
|
|
2023-01-29 10:19:26 +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);
|
|
|
|
}
|
2023-07-05 11:59:28 +03:00
|
|
|
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
|
|
|
|
2023-07-05 11:59:28 +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
|
|
|
}
|