Created
May 5, 2018 09:02
-
-
Save maslowivan/a5f7b7dad184e0b0ef87a3d681209c04 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { canRoute, customHistory, routeTo } from './preact-router.local'; | |
| import { appRegistry, eventsService } from '../../../services/service-manager'; | |
| /** | |
| * Local setURL function overwrite from preact-router | |
| * | |
| * @param {string} url url, applied to router | |
| * @param {string} type optional operation name, default = push | |
| * @param {{ realURL: string, displayURL: string }} newState state object | |
| */ | |
| function setUrl(url, type = 'push', newState = null) { | |
| eventsService.triggerEvent('route:beforechange'); | |
| const baseHref = appRegistry.dataGet('lang', 'base-href') || ''; | |
| const fixedUrl = url === baseHref ? '/' : url.replace(`${ baseHref }/`, '/'); | |
| const fixedNewState = !newState ? null : { | |
| realURL: newState.realURL === baseHref ? '/' : newState.realURL.replace(`${ baseHref }/`, '/'), | |
| displayURL: `${ baseHref || '' }${ newState.displayURL === baseHref ? '' : newState.displayURL }`, | |
| }; | |
| if (customHistory && customHistory[type]) { | |
| customHistory[type](newState && newState.realURL ? fixedNewState.realURL : fixedUrl); | |
| } | |
| else if (typeof window.history !== 'undefined' && window.history[`${ type }State`]) { | |
| const nextVisibleURL = `${ baseHref || '' }${ fixedUrl === baseHref ? '' : fixedUrl }`; | |
| window.history[`${ type }State`](fixedNewState, null, nextVisibleURL); | |
| } | |
| eventsService.triggerEvent(`route:${ type }`, { url: fixedUrl, newState: fixedNewState }); | |
| } | |
| /* eslint prefer-destructuring: "off" */ | |
| /* eslint no-param-reassign: "off" */ | |
| /** | |
| * Do navigate to the specific route | |
| * | |
| * @param {string} url target route url | |
| * @param {string} replace operation name, default push | |
| * @param {string} displayURL url, displaying on a browser's url string | |
| * @returns {boolean} | |
| */ | |
| export default function route(url, replace = false, displayURL = null) { | |
| if (typeof url !== 'string' && url.url) { | |
| replace = url.replace; | |
| url = url.url; | |
| } | |
| // only push URL into history if we can handle it | |
| if (canRoute(url)) { | |
| const targetURL = displayURL || url; | |
| const targetType = replace ? 'replace' : 'push'; | |
| const targetState = { displayURL: displayURL || url, realURL: url }; | |
| setUrl(targetURL, targetType, targetState); | |
| } | |
| return routeTo(url); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment