2023-07-13 11:18:09 -04:00
|
|
|
import type { PropsWithChildren } from 'react';
|
|
|
|
import React from 'react';
|
|
|
|
|
|
|
|
import { Router as OriginalRouter } from 'react-router';
|
|
|
|
|
2023-10-19 13:44:55 -04:00
|
|
|
import type { LocationDescriptor, Path } from 'history';
|
|
|
|
import { createBrowserHistory } from 'history';
|
|
|
|
|
2023-07-13 11:18:09 -04:00
|
|
|
import { layoutFromWindow } from 'mastodon/is_mobile';
|
|
|
|
|
2023-07-17 11:32:46 -04:00
|
|
|
interface MastodonLocationState {
|
|
|
|
fromMastodon?: boolean;
|
|
|
|
mastodonModalKey?: string;
|
|
|
|
}
|
2023-10-19 13:44:55 -04:00
|
|
|
type HistoryPath = Path | LocationDescriptor<MastodonLocationState>;
|
2023-07-17 11:32:46 -04:00
|
|
|
|
|
|
|
const browserHistory = createBrowserHistory<
|
|
|
|
MastodonLocationState | undefined
|
|
|
|
>();
|
2023-07-13 11:18:09 -04:00
|
|
|
const originalPush = browserHistory.push.bind(browserHistory);
|
2023-07-17 11:32:46 -04:00
|
|
|
const originalReplace = browserHistory.replace.bind(browserHistory);
|
|
|
|
|
2023-10-19 13:44:55 -04:00
|
|
|
function extractRealPath(path: HistoryPath) {
|
|
|
|
if (typeof path === 'string') return path;
|
|
|
|
else return path.pathname;
|
|
|
|
}
|
|
|
|
|
|
|
|
browserHistory.push = (path: HistoryPath, state?: MastodonLocationState) => {
|
2023-07-17 11:32:46 -04:00
|
|
|
state = state ?? {};
|
|
|
|
state.fromMastodon = true;
|
2023-07-13 11:18:09 -04:00
|
|
|
|
2023-10-19 13:44:55 -04:00
|
|
|
const realPath = extractRealPath(path);
|
|
|
|
if (!realPath) return;
|
|
|
|
|
|
|
|
if (layoutFromWindow() === 'multi-column' && !realPath.startsWith('/deck')) {
|
|
|
|
originalPush(`/deck${realPath}`, state);
|
2023-07-13 11:18:09 -04:00
|
|
|
} else {
|
|
|
|
originalPush(path, state);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-10-19 13:44:55 -04:00
|
|
|
browserHistory.replace = (path: HistoryPath, state?: MastodonLocationState) => {
|
2023-07-17 11:32:46 -04:00
|
|
|
if (browserHistory.location.state?.fromMastodon) {
|
|
|
|
state = state ?? {};
|
|
|
|
state.fromMastodon = true;
|
|
|
|
}
|
|
|
|
|
2023-10-19 13:44:55 -04:00
|
|
|
const realPath = extractRealPath(path);
|
|
|
|
if (!realPath) return;
|
|
|
|
|
|
|
|
if (layoutFromWindow() === 'multi-column' && !realPath.startsWith('/deck')) {
|
|
|
|
originalReplace(`/deck${realPath}`, state);
|
2023-07-17 11:32:46 -04:00
|
|
|
} else {
|
|
|
|
originalReplace(path, state);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-07-13 11:18:09 -04:00
|
|
|
export const Router: React.FC<PropsWithChildren> = ({ children }) => {
|
|
|
|
return <OriginalRouter history={browserHistory}>{children}</OriginalRouter>;
|
|
|
|
};
|