forked from freeCodeCamp/freeCodeCamp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
use-lang-routes.js
44 lines (41 loc) · 1.11 KB
/
use-lang-routes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { addLang, getLangFromPath } from '../../common/app/utils/lang.js';
function addLangToLocation(location, lang) {
if (!location) {
return location;
}
if (typeof location === 'string') {
return addLang(location, lang);
}
return {
...location,
pathname: addLang(location.pathname, lang)
};
}
function getLangFromLocation(location) {
if (!location) {
return location;
}
if (typeof location === 'string') {
return getLangFromPath(location);
}
return getLangFromPath(location.pathname);
}
export default function useLangRoutes(createHistory, primaryLang) {
return (options = {}) => {
let lang = primaryLang || 'en';
const history = createHistory(options);
const unsubscribeFromHistory = history.listen(nextLocation => {
lang = getLangFromLocation(nextLocation);
});
const push = location => history.push(addLangToLocation(location, lang));
const replace = location => history.replace(
addLangToLocation(location, lang)
);
return {
...history,
push,
replace,
unsubscribe() { unsubscribeFromHistory(); }
};
};
}