Remember Path when switching to commits or file search

The path gets remembered by a query parameter.
Using React state to remember the current path has two downsides.
First you would need to wrap the components in a context and store the current state there.
Second the remembered state gets lost by refreshing the state.
By using a query parameter those two downside get avoided.

Committed-by: Thomas Zerr<thomas.zerr@cloudogu.com>
Co-authored-by: Thomas Zerr<thomas.zerr@cloudogu.com>
Pushed-by: Thomas Zerr<thomas.zerr@cloudogu.com>
This commit is contained in:
Thomas Zerr
2024-03-06 12:10:56 +01:00
parent a8d250c13f
commit 1a6e202384
8 changed files with 142 additions and 26 deletions

View File

@@ -24,7 +24,9 @@
import {
concat,
createPrevSourcePathQuery,
getNamespaceAndPageFromMatch,
getPrevSourcePathFromLocation,
getQueryStringFromLocation,
getValueStringFromLocationByKey,
withEndingSlash,
@@ -143,3 +145,32 @@ describe("tests for getValueStringFromLocationByKey", () => {
expect(getValueStringFromLocationByKey(location, "namespace")).toBeUndefined();
});
});
describe("tests for getPrevSourcePathFromLocation", () => {
it("should return the value string", () => {
const location = { search: "?prevSourcePath=src%2Fsub%25%2Ffile%26%252F.abc" };
expect(getPrevSourcePathFromLocation(location)).toBe("src/sub%/file&%2F.abc");
});
it("should return undefined, because query parameter is missing", () => {
const location = { search: "?q=abc" };
expect(getPrevSourcePathFromLocation(location)).toBeUndefined();
});
it("should return undefined, because query parameter is missing", () => {
const location = { search: "?q=abc" };
expect(getPrevSourcePathFromLocation(location)).toBeUndefined();
});
});
describe("tests for createPrevSourcePathQuery", () => {
it("should return empty string if file path is empty", () => {
const encodedPath = createPrevSourcePathQuery("");
expect(encodedPath).toBe("");
});
it("should return the encoded path as query parameter", () => {
const encodedPath = createPrevSourcePathQuery("src/sub%/file&%2F.abc");
expect(encodedPath).toBe("prevSourcePath=src%2Fsub%25%2Ffile%26%252F.abc");
});
});

View File

@@ -125,3 +125,18 @@ export function escapeUrlForRoute(url: string) {
export function unescapeUrlForRoute(url: string) {
return url.replace(/\\/g, "");
}
const prevSourcePathQueryName = "prevSourcePath";
export function getPrevSourcePathFromLocation(location: { search?: string }): string | undefined {
if (location.search) {
const prevSourcePath = queryString.parse(location.search)[prevSourcePathQueryName];
if (prevSourcePath && !Array.isArray(prevSourcePath)) {
return prevSourcePath;
}
}
}
export const createPrevSourcePathQuery = (filePath: string) => {
return filePath ? `${prevSourcePathQueryName}=${encodeURIComponent(filePath)}` : "";
};