import {BrowserHistoryBuildOptions, HashHistoryBuildOptions, History, MemoryHistoryBuildOptions} from "history"; import createBrowserHistory from "history/createBrowserHistory"; import createMemoryHistory from "history/createMemoryHistory"; import {IS_CLIENT, IS_SERVER} from "../check-environment"; import {createLogger} from "../debug/create-logger"; import {LOG_LEVEL} from "../debug/levels"; import {GlobalVariable} from "../pattern/global-page-data"; export const REACT_ROUTE_BASE_VARNAME = 'routingBaseUri'; export type HistoryOptionTypes = BrowserHistoryBuildOptions|HashHistoryBuildOptions|MemoryHistoryBuildOptions; export type HistoryCreator = (opt: HistoryOptionTypes) => History; const debug = createLogger(LOG_LEVEL.SILLY, 'history'); const warn = createLogger(LOG_LEVEL.WARN, 'history'); export interface MyHistoryOptions { baseUri?: string; current?: string; } const historyCreator = IS_CLIENT? createBrowserHistory : createMemoryHistory; export function replaceSingletonHistory(global: GlobalVariable, history: History) { global.set('history', history); } export function createSingletonHistory(global: GlobalVariable, options: MyHistoryOptions, creator: HistoryCreator = historyCreator,): History { let history = global.get('history'); // console.log(history,History) if (!history || !history.listen) { const baseUri = options.baseUri || global.get(REACT_ROUTE_BASE_VARNAME) || '/'; global.set(REACT_ROUTE_BASE_VARNAME, baseUri); let current; if (IS_SERVER) { if (!options.current) { throw new TypeError('createSingletonHistory(): require a "current" option on server. got: ' + JSON.stringify(options)); } current = options.current.replace(baseUri, '/').replace(/^\/\//, '/'); } else if (options.current) { warn('createSingletonHistory(): "current" option no effect on client.') } debug('createSingletonHistory(): baseUri=%s, current=%s', baseUri, current || '{browser-location}'); history = creator({ basename: baseUri, initialEntries: [current], initialIndex: 0, keyLength: 6, }); replaceSingletonHistory(global, history); } // console.log(history) return history; }