phanpy/src/utils/useTitle.js

31 lines
1 KiB
JavaScript
Raw Normal View History

2022-12-10 12:14:48 +03:00
import { useEffect } from 'preact/hooks';
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;
export default function useTitle(title, path) {
const snapStates = useSnapshot(states);
2023-02-11 12:57:26 +03:00
const { currentLocation } = snapStates;
let paths = [];
// Workaround for matchPath not working for optional path segments
// https://github.com/remix-run/react-router/discussions/9862
if (/:?\w+\?/.test(path)) {
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));
} else {
matched = matchPath(path, currentLocation);
}
console.debug({ paths, matched, currentLocation });
2022-12-10 12:14:48 +03:00
useEffect(() => {
2023-02-11 12:57:26 +03:00
if (path && !matched) return;
document.title = title ? `${title} / ${CLIENT_NAME}` : CLIENT_NAME;
}, [title, snapStates.currentLocation]);
2022-12-16 08:27:04 +03:00
}