Skip to content

Commit

Permalink
Merge pull request #4 from koordinates/route-event-onload-meta-flag
Browse files Browse the repository at this point in the history
  • Loading branch information
UberMouse authored Aug 4, 2022
2 parents 4cb0fe6 + 57ee3e9 commit eaff56e
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/routing/createRoute/createRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,11 @@ export type SharedMeta = {
* If true, use history.replace instead history.push
*/
replace?: boolean;

/**
* true if the event was triggered by the initial match of the URL on load
*/
onloadEvent?: boolean;
};

/**
Expand Down
10 changes: 10 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,13 @@ export type StateMachineToInterpreter<T> = T extends StateMachine<
>
? Interpreter<TContext, TSchema, TEvents, TState, any>
: never;

export function isLikelyPageLoad(): boolean {
// without performance API, we can't tell if this is a page load
if (typeof performance === "undefined") {
return false;
}

// if it's been < 5 seconds since the page was loaded, it's probably a page load
return performance.now() < 5000;
}
5 changes: 4 additions & 1 deletion src/xstateTree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,14 @@ import {
Route,
RoutingContext,
RoutingEvent,
SharedMeta,
} from "./routing";
import { useActiveRouteEvents } from "./routing/providers";
import { GetSlotNames, Slot } from "./slots";
import { XstateTreeMachineStateSchema, GlobalEvents } from "./types";
import { useConstant } from "./useConstant";
import { useService } from "./useService";
import { isLikelyPageLoad } from "./utils";

export const emitter = new TinyEmitter();

Expand Down Expand Up @@ -361,7 +363,8 @@ export function buildRootComponent<
routing.basePath,
getPathName(),
getQueryString(),
setActiveRouteEvents
setActiveRouteEvents,
{ onloadEvent: isLikelyPageLoad() } as SharedMeta
);

// Hack to ensure the initial location doesn't have undefined state
Expand Down
1 change: 1 addition & 0 deletions xstate-tree.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,7 @@ export type SharedMeta = {
doNotNotifyReactRouter?: boolean;
indexEvent?: boolean;
replace?: boolean;
onloadEvent?: boolean;
};

// @public (undocumented)
Expand Down

0 comments on commit eaff56e

Please sign in to comment.