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