2022-12-10 12:14:48 +03:00
|
|
|
import { useEffect } from 'preact/hooks';
|
2023-01-29 10:19:26 +03:00
|
|
|
import { matchPath } from 'react-router-dom';
|
|
|
|
import { useSnapshot } from 'valtio';
|
|
|
|
|
|
|
|
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) {
|
|
|
|
const snapStates = useSnapshot(states);
|
2023-02-11 12:57:26 +03:00
|
|
|
const { currentLocation } = snapStates;
|
2023-02-25 05:03:34 +03:00
|
|
|
const hasPaths = Array.isArray(path);
|
|
|
|
let paths = hasPaths ? path : [];
|
2023-02-11 12:57:26 +03:00
|
|
|
// Workaround for matchPath not working for optional path segments
|
|
|
|
// https://github.com/remix-run/react-router/discussions/9862
|
2023-02-25 05:03:34 +03:00
|
|
|
if (!hasPaths && /:?\w+\?/.test(path)) {
|
2023-02-11 13:19:23 +03:00
|
|
|
paths.push(path.replace(/(:\w+)\?/g, '$1'));
|
2023-02-11 12:57:26 +03:00
|
|
|
paths.push(path.replace(/\/?:\w+\?/g, ''));
|
|
|
|
}
|
|
|
|
let matched = false;
|
|
|
|
if (paths.length) {
|
|
|
|
matched = paths.some((p) => matchPath(p, currentLocation));
|
2023-02-11 14:36:28 +03:00
|
|
|
} else if (path) {
|
2023-02-11 12:57:26 +03:00
|
|
|
matched = matchPath(path, currentLocation);
|
|
|
|
}
|
2023-02-11 13:19:23 +03:00
|
|
|
console.debug({ paths, matched, currentLocation });
|
2022-12-10 12:14:48 +03:00
|
|
|
useEffect(() => {
|
2023-02-25 05:03:34 +03:00
|
|
|
if (!matched) return;
|
2022-12-15 12:11:15 +03:00
|
|
|
document.title = title ? `${title} / ${CLIENT_NAME}` : CLIENT_NAME;
|
2023-02-25 05:03:34 +03:00
|
|
|
}, [title, matched]);
|
2022-12-16 08:27:04 +03:00
|
|
|
}
|