1 |
|
2 | import createHistory from "__KOOT_CLIENT_REQUIRE_CREATE_HISTORY__"
|
3 | import { parsePath } from 'history/lib/PathUtils'
|
4 | import isI18nEnabled from '../i18n/is-enabled'
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | const kootUseBasename = (createHistory) =>
|
19 | (options = {}) => {
|
20 | const history = createHistory(options)
|
21 | const { basename } = options
|
22 |
|
23 | const addBasename = (location) => {
|
24 | if (!location)
|
25 | return location
|
26 |
|
27 | if (basename && location.basename == null) {
|
28 | if (location.pathname.toLowerCase().indexOf(basename.toLowerCase()) === 0) {
|
29 | location.pathname = location.pathname.substring(basename.length)
|
30 | location.basename = basename
|
31 |
|
32 | if (location.pathname === '')
|
33 | location.pathname = '/'
|
34 | } else {
|
35 | location.basename = ''
|
36 | }
|
37 | }
|
38 |
|
39 | return location
|
40 | }
|
41 |
|
42 | const prependBasename = (location) => {
|
43 | if (!basename)
|
44 | return location
|
45 |
|
46 | const object = typeof location === 'string' ? parsePath(location) : location
|
47 | const pname = object.pathname
|
48 | const normalizedBasename = basename.slice(-1) === '/' ? basename : `${basename}/`
|
49 | const normalizedPathname = pname.charAt(0) === '/' ? pname.slice(1) : pname
|
50 | const pathname = normalizedBasename + normalizedPathname
|
51 |
|
52 | return {
|
53 | ...object,
|
54 | pathname
|
55 | }
|
56 | }
|
57 |
|
58 |
|
59 | const push = (location) =>
|
60 | history.push(prependBasename(location))
|
61 |
|
62 | const replace = (location) =>
|
63 | history.replace(prependBasename(location))
|
64 |
|
65 | const createPath = (location) =>
|
66 | history.createPath(prependBasename(location))
|
67 |
|
68 | const createHref = (location) =>
|
69 | history.createHref(prependBasename(location))
|
70 |
|
71 | const createLocation = (location, ...args) =>
|
72 | addBasename(history.createLocation(prependBasename(location), ...args))
|
73 |
|
74 | return {
|
75 | ...history,
|
76 | push,
|
77 | replace,
|
78 | createPath,
|
79 | createHref,
|
80 | createLocation
|
81 | }
|
82 | }
|
83 |
|
84 | let historyClient
|
85 |
|
86 | const history = (() => {
|
87 | if (__CLIENT__) {
|
88 | if (!historyClient) {
|
89 | const initialState = window.__REDUX_STATE__ || {}
|
90 | const historyConfig = { basename: '/' }
|
91 | if (isI18nEnabled() &&
|
92 | process.env.KOOT_I18N_URL_USE === 'router' &&
|
93 | initialState.localeId
|
94 | ) {
|
95 | historyConfig.basename = `/${initialState.localeId}`
|
96 | historyClient = kootUseBasename(createHistory)(historyConfig)
|
97 | } else {
|
98 |
|
99 | historyClient = createHistory()
|
100 | }
|
101 |
|
102 |
|
103 |
|
104 |
|
105 | }
|
106 | return historyClient
|
107 | }
|
108 |
|
109 | if (__SERVER__) {
|
110 | return undefined
|
111 | }
|
112 | })()
|
113 |
|
114 | export default history
|