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