UNPKG

@koordinates/xstate-tree

Version:

Build UIs with Actors using xstate and React

55 lines (54 loc) 2.13 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.handleLocationChange = void 0; const xstateTree_1 = require("../../xstateTree"); const matchRoute_1 = require("../matchRoute"); /** * @internal */ function handleLocationChange(routes, basePath, path, search, meta) { console.debug("[xstate-tree] Matching routes", basePath, path, search, meta); const match = (0, matchRoute_1.matchRoute)(routes, basePath, path, search); if (match.type === "no-matches") { const fourOhFour = { type: "ROUTING_404", url: path, }; // @ts-ignore the event won't match GlobalEvents (0, xstateTree_1.broadcast)(fourOhFour); return; } else if (match.type === "match-error") { console.error("Error matching route for", location.pathname, match.error); return; } else { console.log("[xstate-tree] matched route", match.event); const matchedEvent = match.event; matchedEvent.meta = { ...(meta ?? {}) }; matchedEvent.meta.indexEvent = true; const { params, query } = match.event; const routingEvents = []; let route = match.route; route.preload({ params, query, meta: matchedEvent.meta }); while (route.parent) { routingEvents.push(route.parent.getEvent({ params, query: {}, meta: { ...(meta ?? {}) } })); route = route.parent; } const clonedRoutingEvents = [...routingEvents]; while (routingEvents.length > 0) { const event = routingEvents.pop(); // copy the originalUrl to all parent events event.originalUrl = match.event.originalUrl; // @ts-ignore the event won't match GlobalEvents (0, xstateTree_1.broadcast)(event); } // @ts-ignore the event won't match GlobalEvents (0, xstateTree_1.broadcast)(matchedEvent); return { events: [...clonedRoutingEvents, match.event], matchedRoute: match.route, }; } } exports.handleLocationChange = handleLocationChange;