MCPcopy Create free account
hub / github.com/triggerdotdev/jsonhero-web / calculateStablePath

Function calculateStablePath

app/utilities/jsonColumnView.ts:148–205  ·  view source on GitHub ↗
(
  previousPathString: string,
  selectionPathString: string,
  json: unknown
)

Source from the content-addressed store, hash-verified

146//Given the previous path and where the selection is, we calculate the new path
147//This allows us to keep the deepest item possible still visible whilst navigating around
148export function calculateStablePath(
149 previousPathString: string,
150 selectionPathString: string,
151 json: unknown
152): string {
153 const previousPath = new JSONHeroPath(previousPathString);
154 const selectionPath = new JSONHeroPath(selectionPathString);
155
156 //if we are selecting at the right edge then the selection determines the path
157 if (selectionPath.components.length >= previousPath.components.length) {
158 return selectionPathString;
159 }
160
161 //if the selection is the same as the path from the start up to selection end then we leave the path as is
162 const previousPathWithSelectionLength = new JSONHeroPath(
163 previousPath.components.slice(0, selectionPath.components.length)
164 );
165 if (selectionPathString === previousPathWithSelectionLength.toString()) {
166 return previousPathString;
167 }
168
169 //from the start we add the selection components until they don't match the previous path (this should be until the last one)
170 let newComponents: PathComponent[] = [];
171 for (let index = 0; index < selectionPath.components.length; index++) {
172 const selectionComponent = selectionPath.components[index];
173 const previousComponent = previousPath.components[index];
174
175 //if they're different we need to bail and try build an alternative path
176 if (selectionComponent.toString() !== previousComponent.toString()) {
177 break;
178 }
179
180 newComponents.push(selectionComponent);
181 }
182
183 //we substitute all the remaining elements from the selection into the previousPath
184 const remainingSelectionComponents = selectionPath.components.slice(
185 newComponents.length
186 );
187 const remainingPreviousPathComponents = previousPath.components.slice(
188 selectionPath.components.length
189 );
190 const updatedPathComponents = [
191 ...newComponents,
192 ...remainingSelectionComponents,
193 ...remainingPreviousPathComponents,
194 ];
195 const updatedPath = new JSONHeroPath(updatedPathComponents);
196
197 const jsonAtUpdatedPath = updatedPath.first(json);
198
199 //not a match then we return the selection path
200 if (!jsonAtUpdatedPath) {
201 return selectionPathString;
202 } else {
203 return updatedPath.toString();
204 }
205}

Callers 1

JsonColumnViewProviderFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected