Added caching for calculating related paths

This commit is contained in:
Matt Aitken
2022-03-11 16:59:33 +00:00
parent c077eb80ea
commit 26ef6c12f0
2 changed files with 37 additions and 6 deletions
+2 -6
View File
@@ -8,11 +8,12 @@ import { useMemo } from "react";
import { useJson } from "~/hooks/useJson";
import { getRelatedPathsAtPath } from "~/utilities/relatedValues";
import { useJsonColumnViewState } from "~/hooks/useJsonColumnView";
import { useRelatedPaths } from "~/hooks/useRelatedPaths";
export function InfoPanel() {
const selectedInfo = useSelectedInfo();
const [json] = useJson();
const { selectedNodeId } = useJsonColumnViewState();
const relatedPaths = useRelatedPaths();
if (!selectedInfo) {
return <></>;
@@ -21,11 +22,6 @@ export function InfoPanel() {
const isSelectedLeafNode =
selectedInfo.name !== "object" && selectedInfo.name !== "array";
const relatedPaths = useMemo(() => {
if (!selectedNodeId) return [];
return getRelatedPathsAtPath(selectedNodeId, json);
}, [selectedNodeId, json]);
return (
<>
<div className="h-inspectorHeight p-4 bg-white border-l-[1px] border-slate-300 overflow-y-auto no-scrollbar transition dark:bg-slate-800 dark:border-slate-600">
+35
View File
@@ -0,0 +1,35 @@
import { useMemo, useRef } from "react";
import { getRelatedPathsAtPath } from "~/utilities/relatedValues";
import { useJson } from "./useJson";
import { useJsonColumnViewState } from "./useJsonColumnView";
export function useRelatedPaths(): string[] {
const cache = useRef<RelatedPathCache>({});
const { selectedNodeId } = useJsonColumnViewState();
const [json] = useJson();
return useMemo(() => {
if (!selectedNodeId) return [];
//check cache
const cachedPaths = cache.current[selectedNodeId];
if (cachedPaths) {
return cachedPaths;
}
//fetch result
let paths = getRelatedPathsAtPath(selectedNodeId, json);
//cache
for (let index = 0; index < paths.length; index++) {
const path = paths[index];
cache.current[path] = paths;
}
return paths;
}, [selectedNodeId, json]);
}
type RelatedPathCache = {
[index: string]: Array<string>;
};