router.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import page from 'page';
  2. import stableStringify from 'json-stable-stringify';
  3. import { each } from 'lodash';
  4. import { route } from './actions/request-actions';
  5. import { storageGet, storageSet } from './utils/storage-utils';
  6. import {
  7. decodeURL, encodeURL, isStoreViewStateEnabled, STORAGE_STATE_KEY
  8. } from './utils/router-utils';
  9. // Temporarily detect old topology options to avoid breaking things between releases
  10. // Related to https://github.com/weaveworks/scope/pull/2404
  11. function detectOldOptions(topologyOptions) {
  12. let bad = false;
  13. each(topologyOptions, (topology) => {
  14. each(topology, (option) => {
  15. if (typeof option === 'string') {
  16. bad = true;
  17. }
  18. });
  19. });
  20. return bad;
  21. }
  22. export function getRouter(initialState) {
  23. return (dispatch, getState) => {
  24. // strip any trailing '/'s.
  25. page.base(window.location.pathname.replace(/\/$/, ''));
  26. page('/', () => {
  27. // recover from storage state on empty URL
  28. const storageState = storageGet(STORAGE_STATE_KEY);
  29. if (storageState && isStoreViewStateEnabled(getState())) {
  30. const parsedState = JSON.parse(decodeURL(storageState));
  31. const dirtyOptions = detectOldOptions(parsedState.topologyOptions);
  32. if (dirtyOptions) {
  33. dispatch(route(initialState));
  34. } else {
  35. const mergedState = Object.assign(initialState, parsedState);
  36. // push storage state to URL
  37. window.location.hash = `!/state/${stableStringify(mergedState)}`;
  38. dispatch(route(mergedState));
  39. }
  40. } else {
  41. dispatch(route(initialState));
  42. }
  43. });
  44. page('/state/:state', (ctx) => {
  45. const state = JSON.parse(decodeURL(ctx.params.state));
  46. const dirtyOptions = detectOldOptions(state.topologyOptions);
  47. const nextState = dirtyOptions ? initialState : state;
  48. // back up state in storage and redirect
  49. if (isStoreViewStateEnabled(getState())) {
  50. storageSet(STORAGE_STATE_KEY, encodeURL(stableStringify(state)));
  51. }
  52. dispatch(route(nextState)); //原来的系统自带的
  53. // dispatch(route(initialState)) //后来修改的
  54. });
  55. return page;
  56. };
  57. }