history#parsePath TypeScript Examples

The following examples show how to use history#parsePath. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: historyExtended.ts    From next-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Override history for standalone micro apps.
 *
 * when `push` or `replace` to other apps, force page refresh.
 */
function standaloneHistoryOverridden(
  browserHistory: History<PluginHistoryState>
): Pick<History<PluginHistoryState>, "push" | "replace"> {
  const { push: originalPush, replace: originalReplace } = browserHistory;
  function updateFactory(
    method: "push" | "replace"
  ): History<PluginHistoryState>["push"] {
    return function update(path, state?) {
      let pathname: string;
      const pathIsString = typeof path === "string";
      if (pathIsString) {
        pathname = parsePath(path).pathname;
      } else {
        pathname = path.pathname;
      }
      if (pathname === "" || _internalApiHasMatchedApp(pathname)) {
        return (method === "push" ? originalPush : originalReplace)(
          path as string,
          state
        );
      }
      // Going to outside apps.
      return location[method === "push" ? "assign" : "replace"](
        pathIsString
          ? getBasePath() + path.replace(/^\//, "")
          : browserHistory.createHref(
              path as LocationDescriptorObject<PluginHistoryState>
            )
      );
    };
  }
  return {
    push: updateFactory("push"),
    replace: updateFactory("replace"),
  };
}
Example #2
Source File: index.tsx    From react-resource-router with Apache License 2.0 4 votes vote down vote up
actions: AllRouterActions = {
  /**
   * Bootstraps the store with initial data.
   *
   */
  bootstrapStore: props => ({ setState, dispatch }) => {
    const {
      resourceContext,
      resourceData,
      basePath = '',
      routes,
      initialRoute,
      ...initialProps
    } = props;
    const { history, isStatic } = initialProps;
    const routerContext = findRouterContext(
      initialRoute ? [initialRoute] : routes,
      { location: history.location, basePath }
    );

    setState({
      ...initialProps,
      ...routerContext,
      basePath,
      routes,
      location: history.location,
      action: history.action,
    });
    getResourceStore().actions.hydrate({ resourceContext, resourceData });

    if (!isStatic) {
      dispatch(actions.listen());
    }
  },

  /**
   * Duplicate method that uses isServerEnvironment instead of removed isStatic prop
   * internally. We can remove this when UniversalRouter replaces Router completely.
   */
  bootstrapStoreUniversal: props => ({ setState, dispatch }) => {
    const {
      resourceContext,
      resourceData,
      basePath = '',
      ...initialProps
    } = props;
    const { history, routes } = initialProps;
    const routerContext = findRouterContext(routes, {
      location: history.location,
      basePath,
    });

    setState({
      ...initialProps,
      ...routerContext,
      basePath,
      location: history.location,
      action: history.action,
    });
    getResourceStore().actions.hydrate({ resourceContext, resourceData });

    if (!isServerEnvironment()) {
      dispatch(actions.listen());
    }
  },

  /**
   * Uses the resource store to request resources for the route.
   * Must be dispatched after setting state with the new route context.
   *
   */
  requestRouteResources: (options = {}) => ({ getState }) => {
    const { route, match, query } = getState();

    return getResourceStore().actions.requestAllResources(
      {
        route,
        match,
        query,
      },
      options
    );
  },

  prefetchNextRouteResources: (path, nextContext) => ({ getState }) => {
    const { routes, basePath, onPrefetch, route, match, query } = getState();
    const {
      cleanExpiredResources,
      requestResources,
      getContext: getResourceStoreContext,
    } = getResourceStore().actions;

    if (!nextContext && !isExternalAbsolutePath(path)) {
      const location = parsePath(getRelativePath(path, basePath) as any);
      nextContext = findRouterContext(routes, { location, basePath });
    }

    if (nextContext == null) return;
    const nextLocationContext = nextContext;

    const nextResources = getResourcesForNextLocation(
      { route, match, query },
      nextLocationContext,
      getResourceStoreContext()
    );

    batch(() => {
      cleanExpiredResources(nextResources, nextLocationContext);
      requestResources(nextResources, nextLocationContext, { prefetch: true });
      if (onPrefetch) onPrefetch(nextLocationContext);
    });
  },

  /**
   * Starts listening to browser history and sets the unlisten function in state.
   * Will request route resources on route change.
   *
   */
  listen: () => ({ getState, setState }) => {
    const { history } = getState();

    type LocationUpateV4 = [Location, Action];
    type LocationUpateV5 = [{ location: Location; action: Action }];

    const stopListening = history.listen(
      (...update: LocationUpateV4 | LocationUpateV5) => {
        const location = update.length === 2 ? update[0] : update[0].location;
        const action = update.length === 2 ? update[1] : update[0].action;

        const {
          routes,
          basePath,
          match: currentMatch,
          route: currentRoute,
          query: currentQuery,
        } = getState();

        const {
          cleanExpiredResources,
          requestResources,
          getContext: getResourceStoreContext,
        } = getResourceStore().actions;

        const nextContext = findRouterContext(routes, { location, basePath });
        const nextLocationContext = {
          route: nextContext.route,
          match: nextContext.match,
          query: nextContext.query,
        };
        const nextResources = getResourcesForNextLocation(
          {
            route: currentRoute,
            match: currentMatch,
            query: currentQuery,
          },
          nextLocationContext,
          getResourceStoreContext()
        );

        /* Explicitly batch update
         * as we need resources cleaned + route changed + resource fetch started together
         * If we do not batch, React might be re-render when route changes but resource
         * fetching has not started yet, making the app render with data null */

        batch(() => {
          cleanExpiredResources(nextResources, nextLocationContext);
          setState({
            ...nextContext,
            location,
            action,
          });
          requestResources(nextResources, nextLocationContext, {});
        });
      }
    );

    setState({
      unlisten: stopListening,
    });
  },

  push: path => ({ getState }) => {
    const { history, basePath } = getState();
    if (isExternalAbsolutePath(path)) {
      window.location.assign(path as string);
    } else {
      history.push(getRelativePath(path, basePath) as any);
    }
  },

  pushTo: (route, attributes = {}) => ({ getState }) => {
    const { history, basePath } = getState();
    const location = generateLocationFromPath(route.path, {
      ...attributes,
      basePath,
    });
    warmupMatchRouteCache(route, location.pathname, attributes.query, basePath);
    history.push(location as any);
  },

  replace: path => ({ getState }) => {
    const { history, basePath } = getState();
    if (isExternalAbsolutePath(path)) {
      window.location.replace(path as string);
    } else {
      history.replace(getRelativePath(path, basePath) as any);
    }
  },

  replaceTo: (route, attributes = {}) => ({ getState }) => {
    const { history, basePath } = getState();
    const location = generateLocationFromPath(route.path, {
      ...attributes,
      basePath,
    });
    warmupMatchRouteCache(route, location.pathname, attributes.query, basePath);
    history.replace(location as any);
  },

  goBack: () => ({ getState }) => {
    const { history } = getState();

    history.goBack();
  },

  goForward: () => ({ getState }) => {
    const { history } = getState();

    history.goForward();
  },

  registerBlock: blocker => ({ getState }) => {
    const { history } = getState();

    return history.block(blocker);
  },

  getContext: () => ({ getState }) => {
    const { query, route, match } = getState();

    return { query, route, match };
  },

  getBasePath: () => ({ getState }) => {
    const { basePath } = getState();

    return basePath;
  },

  updateQueryParam: (params, updateType = 'push') => ({ getState }) => {
    const { query: existingQueryParams, history, location } = getState();
    const updatedQueryParams = { ...existingQueryParams, ...params };
    // remove undefined keys
    Object.keys(updatedQueryParams).forEach(
      key =>
        updatedQueryParams[key] === undefined && delete updatedQueryParams[key]
    );
    const existingPath = updateQueryParams(location, existingQueryParams);
    const updatedPath = updateQueryParams(
      location,
      updatedQueryParams as Query
    );

    if (updatedPath !== existingPath) {
      history[updateType](updatedPath);
    }
  },

  updatePathParam: (params, updateType = 'push') => ({ getState }) => {
    const {
      history,
      location,
      route: { path },
      match: { params: existingPathParams },
      basePath,
    } = getState();
    const pathWithBasePath = basePath + path;
    const updatedPathParams = { ...existingPathParams, ...params };
    const updatedPath = generatePathUsingPathParams(
      pathWithBasePath,
      updatedPathParams
    );
    const updatedLocation = { ...location, pathname: updatedPath };

    const existingRelativePath = getRelativeURLFromLocation(location);
    const updatedRelativePath = getRelativeURLFromLocation(updatedLocation);

    if (updatedRelativePath !== existingRelativePath) {
      history[updateType](updatedRelativePath);
    }
  },
}