AK-21/Graphite-Industrial-Intelligence
0
1import mitt from "mitt";2import { useSyncExternalStore } from "./react-deps.js";3 4/**5 * In-memory location that supports navigation6 */7 8export const memoryLocation = ({9 path = "/",10 searchPath = "",11 state = null,12 static: staticLocation,13 record,14} = {}) => {15 let initialPath = path;16 const initialState = state;17 if (searchPath) {18 // join with & if path contains search query, and ? otherwise19 initialPath += path.split("?")[1] ? "&" : "?";20 initialPath += searchPath;21 }22 23 let [currentPath, currentSearch = ""] = initialPath.split("?");24 let currentState = initialState;25 const history = [initialPath];26 const emitter = mitt();27 28 const navigateImplementation = (path, { replace = false, state } = {}) => {29 if (record) {30 if (replace) {31 history.splice(history.length - 1, 1, path);32 } else {33 history.push(path);34 }35 }36 37 [currentPath, currentSearch = ""] = path.split("?");38 if (state !== undefined) currentState = state;39 emitter.emit("navigate", path);40 };41 42 const navigate = !staticLocation ? navigateImplementation : () => null;43 44 const subscribe = (cb) => {45 emitter.on("navigate", cb);46 return () => emitter.off("navigate", cb);47 };48 49 const useMemoryLocation = () => [50 useSyncExternalStore(subscribe, () => currentPath),51 navigate,52 ];53 54 const useMemoryQuery = () =>55 useSyncExternalStore(subscribe, () => currentSearch);56 57 // Attach searchHook to the location hook for auto-inheritance in Router58 useMemoryLocation.searchHook = useMemoryQuery;59 60 function reset() {61 // clean history array with mutation to preserve link62 history.splice(0, history.length);63 navigateImplementation(initialPath, { state: initialState });64 }65 66 const memoryLocationResult = {67 hook: useMemoryLocation,68 searchHook: useMemoryQuery,69 navigate,70 history: record ? history : undefined,71 reset: record ? reset : undefined,72 };73 74 Object.defineProperty(memoryLocationResult, "state", {75 enumerable: true,76 get: () => currentState,77 });78 79 return memoryLocationResult;80};81 