diff --git a/src/App.svelte b/src/App.svelte index ec40ddc2c..6ec3b2520 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -72,7 +72,7 @@ {:else if $activeRouteStore.resource === "session"} {:else if $activeRouteStore.resource === "projects"} - + {:else if $activeRouteStore.resource === "booting"} {:else if $activeRouteStore.resource === "loadError"} diff --git a/src/components/Markdown.svelte b/src/components/Markdown.svelte index cb56d26d3..e4919b9d0 100644 --- a/src/components/Markdown.svelte +++ b/src/components/Markdown.svelte @@ -16,7 +16,7 @@ import { updateProjectRoute } from "@app/views/projects/router"; export let content: string; - export let hash: string | null = null; + export let hash: string | undefined = undefined; export let path: string = "/"; export let rawPath: string | undefined = undefined; diff --git a/src/lib/router.ts b/src/lib/router.ts index e666ca8cb..91d60379d 100644 --- a/src/lib/router.ts +++ b/src/lib/router.ts @@ -18,6 +18,8 @@ export const activeRouteStore = writable({ resource: "booting", }); +let currentUrl: URL | undefined; + export function useDefaultNavigation(event: MouseEvent) { return ( event.button !== 0 || @@ -31,21 +33,28 @@ export function useDefaultNavigation(event: MouseEvent) { export const base = import.meta.env.VITE_HASH_ROUTING ? "./" : "/"; export async function loadFromLocation(): Promise { - const { pathname, search, hash } = window.location; + let { pathname, hash } = window.location; - if ( - import.meta.env.VITE_HASH_ROUTING && - pathname === "/" && - hash && - !hash.startsWith("#/") - ) { - // We land here if the user clicked an link with only a hash reference. - // Instead of going to the root page we stop routing here and have the - // browser take care of things. - return; + if (import.meta.env.VITE_HASH_ROUTING) { + if (pathname === "/" && hash && !hash.startsWith("#/")) { + // We land here if the user clicked an link with only a hash reference. + // Instead of going to the root page we stop routing here and have the + // browser take care of things. + return; + } + [pathname, hash] = hash.substring(1).split("#"); + } else { + if ( + currentUrl && + currentUrl.pathname === pathname && + currentUrl.search === window.location.search + ) { + return; + } } - const url = pathname + search + hash; + const relativeUrl = pathname + window.location.search + (hash || ""); + const url = new URL(relativeUrl, window.origin); let route = pathToRoute(url); if (route) { @@ -56,7 +65,7 @@ export async function loadFromLocation(): Promise { route.params.hash ) { if (route.params.hash.match(/^L\d+$/)) { - route = createProjectRoute(activeRoute, { line: route.params.hash }); + route = createProjectRoute(activeRoute, {}); } else { route = createProjectRoute(activeRoute, { hash: route.params.hash }); } @@ -64,7 +73,7 @@ export async function loadFromLocation(): Promise { await replace(route); } else { - await replace({ resource: "notFound", params: { url } }); + await replace({ resource: "notFound", params: { url: relativeUrl } }); } } @@ -77,6 +86,16 @@ async function navigate( newRoute: Route, ): Promise { isLoading.set(true); + const path = import.meta.env.VITE_HASH_ROUTING + ? "#" + routeToPath(newRoute) + : routeToPath(newRoute); + + if (action === "push") { + window.history.pushState(newRoute, DOCUMENT_TITLE, path); + } else if (action === "replace") { + window.history.replaceState(newRoute, DOCUMENT_TITLE, path); + } + currentUrl = new URL(window.location.href); const loadedRoute = await loadExecutor.run(async () => { return loadRoute(newRoute); @@ -89,16 +108,6 @@ async function navigate( activeRouteStore.set(loadedRoute); isLoading.set(false); - - const path = import.meta.env.VITE_HASH_ROUTING - ? "#" + routeToPath(newRoute) - : routeToPath(newRoute); - - if (action === "push") { - window.history.pushState(newRoute, DOCUMENT_TITLE, path); - } else if (action === "replace") { - window.history.replaceState(newRoute, DOCUMENT_TITLE, path); - } } export async function push(newRoute: Route): Promise { @@ -109,51 +118,8 @@ export async function replace(newRoute: Route): Promise { await navigate("replace", newRoute); } -// We need a SHA1 commit in some places, so we return early if the revision is -// a SHA and else we look into branches. -export function getOid( - revision: string, - branches?: Record, -): string | undefined { - if (isOid(revision)) return revision; - - if (branches) { - const oid = branches[revision]; - if (oid) return oid; - } - return undefined; -} - -// Check whether the input is a SHA1 commit. -export function isOid(input: string): boolean { - return /^[a-fA-F0-9]{40}$/.test(input); -} - -export function parseRevisionToOid( - revision: string | undefined, - defaultBranch: string, - branches: Record, -): string { - if (revision) { - const oid = getOid(revision, branches); - if (!oid) { - throw new Error(`Revision ${revision} not found`); - } - return oid; - } - return branches[defaultBranch]; -} - -function pathToRoute(path: string): Route | null { - // This matches e.g. an empty string - if (!path) { - return null; - } - - const url = new URL(path, window.origin); - const segments = import.meta.env.VITE_HASH_ROUTING - ? url.hash.substring(2).split("#")[0].split("/") // Try to remove any additional hashes at the end of the URL. - : url.pathname.substring(1).split("/"); +function pathToRoute(url: URL): Route | null { + const segments = url.pathname.substring(1).split("/"); const resource = segments.shift(); switch (resource) { @@ -258,9 +224,7 @@ export function routeToPath(route: Route) { if (route.params.search) { suffix += `?${route.params.search}`; } - if (route.params.line) { - suffix += `#${route.params.line}`; - } else if (route.params.hash) { + if (route.params.hash) { suffix += `#${route.params.hash}`; } @@ -301,4 +265,4 @@ export function routeToPath(route: Route) { } } -export const testExports = { pathToRoute, isOid, routeToPath }; +export const testExports = { pathToRoute, routeToPath }; diff --git a/src/lib/router/definitions.ts b/src/lib/router/definitions.ts index 9f2e73964..19c1058eb 100644 --- a/src/lib/router/definitions.ts +++ b/src/lib/router/definitions.ts @@ -1,8 +1,12 @@ import type { HomeRoute, HomeLoadedRoute } from "@app/views/home/router"; -import type { ProjectRoute } from "@app/views/projects/router"; +import type { + ProjectLoadedRoute, + ProjectRoute, +} from "@app/views/projects/router"; import type { SeedsLoadedRoute, SeedsRoute } from "@app/views/seeds/router"; import { loadHomeRoute } from "@app/views/home/router"; +import { loadProjectRoute } from "@app/views/projects/router"; import { loadSeedRoute } from "@app/views/seeds/router"; interface BootingRoute { @@ -42,7 +46,7 @@ export type LoadedRoute = | HomeLoadedRoute | LoadError | NotFoundRoute - | ProjectRoute + | ProjectLoadedRoute | SeedsLoadedRoute | SessionRoute; @@ -51,6 +55,8 @@ export async function loadRoute(route: Route): Promise { return await loadSeedRoute(route.params); } else if (route.resource === "home") { return await loadHomeRoute(); + } else if (route.resource === "projects") { + return await loadProjectRoute(route.params); } else { return route; } diff --git a/src/views/projects/Blob.svelte b/src/views/projects/Blob.svelte index 0916d9226..eacdfc9e9 100644 --- a/src/views/projects/Blob.svelte +++ b/src/views/projects/Blob.svelte @@ -1,26 +1,24 @@ -{#await projectPromise} -
-
- -
-
-{:then { project, peers, branches }} - {@const commit = router.parseRevisionToOid( - revision, - project.defaultBranch, - branches, - )} -
- - {#await getRoot(branches, project.defaultBranch, revision)} - - {:then { tree }} -
+ +
+ + +
+ {#if view.resource === "tree" || view.resource === "history" || view.resource === "commits"} + + + {#if view.resource === "tree"} + + {:else if view.resource === "history"} + + {:else if view.resource === "commits"} + {#await api.project.getCommitBySha(id, view.params.selectedCommit)} + + {:then fetchedCommit} + + {:catch e} +
+ +
+ {/await} + {/if} + {:else if view.resource === "issues" && view.params?.view.resource === "new"} + {#if $httpdStore.state === "authenticated"} + - - {#if activeRoute.params.view.resource === "tree" || activeRoute.params.view.resource === "history" || activeRoute.params.view.resource === "commits"} - - {/if} - - {#if activeRoute.params.view.resource === "tree"} - - {:else if activeRoute.params.view.resource === "history"} - - {:else if activeRoute.params.view.resource === "commits"} - {#await api.project.getCommitBySha(id, commit)} - - {:then fetchedCommit} - - {:catch e} -
- -
- {/await} - {:else if activeRoute.params.view.resource === "issues" && activeRoute.params.view.params?.view.resource === "new"} - {#if $httpdStore.state === "authenticated"} - - {:else} -
- -
- {/if} - {:else if activeRoute.params.view.resource === "issues"} - - {:else if activeRoute.params.view.resource === "issue"} - {#await api.project.getIssueById(project.id, activeRoute.params.view.params.issue)} - - {:then issue} - - {:catch e} -
- -
- {/await} - {:else if activeRoute.params.view.resource === "patches"} - - {:else if activeRoute.params.view.resource === "patch"} - {#await api.project.getPatchById(project.id, activeRoute.params.view.params.patch)} - - {:then patch} - {@const latestRevision = patch.revisions[patch.revisions.length - 1]} - - {:catch e} -
- -
- {/await} - {:else} - {unreachable(activeRoute.params.view)} - {/if} + {:else} +
+ +
+ {/if} + {:else if view.resource === "issues"} + + {:else if view.resource === "issue"} + {#await api.project.getIssueById(id, view.params.issue)} + + {:then issue} + {:catch e}
- {#if peer} - - - {formatNodeId(peer)} - - - - Couldn't load remote source tree. - - {e.message} - - - {:else} - - - Couldn't load source tree. - {e.message} - - - {/if} +
{/await} -
-{:catch} -
- -
-{/await} + {:else if view.resource === "patches"} + + {:else if view.resource === "patch"} + {#await api.project.getPatchById(id, view.params.patch)} + + {:then patch} + {@const latestRevision = patch.revisions[patch.revisions.length - 1]} + + {:catch e} +
+ +
+ {/await} + {:else} + {unreachable(view)} + {/if} +
diff --git a/src/views/projects/router.ts b/src/views/projects/router.ts index 134e45156..8a8bea624 100644 --- a/src/views/projects/router.ts +++ b/src/views/projects/router.ts @@ -1,17 +1,26 @@ +import type { LoadError } from "@app/lib/router/definitions"; +import type { Project, Remote, Tree } from "@httpd-client"; + import { get } from "svelte/store"; +import { HttpdClient } from "@httpd-client"; import { activeRouteStore, push, replace, routeToPath } from "@app/lib/router"; +import { extractBaseUrl } from "@app/lib/utils"; export interface ProjectRoute { resource: "projects"; params: ProjectsParams; } +export interface ProjectLoadedRoute { + resource: "projects"; + params: ProjectLoadedParams; +} + export interface ProjectsParams { id: string; hash?: string; hostnamePort: string; - line?: string; path?: string; peer?: string; revision?: string; @@ -37,6 +46,211 @@ export interface ProjectsParams { | { resource: "patch"; params: { patch: string; revision?: string } }; } +export interface ProjectLoadedParams { + hostnamePort: string; + id: string; + project: Project; + view: ProjectLoadedView; + + hash?: string; + path?: string; + peer?: string; + revision?: string; + search?: string; +} + +interface LoadedSourceBrowsingParams { + loadedBranches: Record; + loadedPeers: Remote[]; + loadedTree: Tree; + selectedCommit: string; +} + +export type ProjectLoadedView = + | { + resource: "tree"; + params: LoadedSourceBrowsingParams; + } + | { + resource: "commits"; + params: LoadedSourceBrowsingParams; + } + | { + resource: "history"; + params: LoadedSourceBrowsingParams; + } + | { resource: "issue"; params: { issue: string } } + | { + resource: "issues"; + params?: { + view: { resource: "new" }; + }; + } + | { + resource: "patches"; + params?: { + view: { resource: "new" }; + }; + } + | { resource: "patch"; params: { patch: string; revision?: string } }; + +// We need a SHA1 commit in some places, so we return early if the revision is +// a SHA and else we look into branches. +function getOid( + revision: string, + branches?: Record, +): string | undefined { + if (isOid(revision)) return revision; + + if (branches) { + const oid = branches[revision]; + if (oid) return oid; + } + return undefined; +} + +// Check whether the input is a SHA1 commit. +export function isOid(input: string): boolean { + return /^[a-fA-F0-9]{40}$/.test(input); +} + +export function parseRevisionToOid( + revision: string | undefined, + defaultBranch: string, + branches: Record, +): string { + if (revision) { + const oid = getOid(revision, branches); + if (!oid) { + throw new Error(`Revision ${revision} not found`); + } + return oid; + } + return branches[defaultBranch]; +} + +export async function loadProjectRoute( + params: ProjectsParams, +): Promise { + const baseUrl = extractBaseUrl(params.hostnamePort); + const api = new HttpdClient(baseUrl); + try { + if ( + params.view.resource === "tree" || + params.view.resource === "history" || + params.view.resource === "commits" + ) { + const projectPromise = api.project.getById(params.id); + const peersPromise = api.project.getAllRemotes(params.id); + const branchesPromise = (async () => { + if (params.peer) { + try { + return (await api.project.getRemoteByPeer(params.id, params.peer)) + .heads; + } catch { + return {}; + } + } + })(); + + const [project, peers, maybeBranches] = await Promise.all([ + projectPromise, + peersPromise, + branchesPromise, + ]); + + let branches: Record; + if (maybeBranches) { + branches = maybeBranches; + } else { + branches = project.head + ? { [project.defaultBranch]: project.head } + : {}; + } + + if (params.route) { + const { revision, path } = detectRevision(params.route, branches); + params.revision = revision; + params.path = path; + // TODO Do not mutate `params`. Contruct a new `loadedParams` object + // instead. + delete params.route; + } + + const commit = parseRevisionToOid( + params.revision, + project.defaultBranch, + branches, + ); + const tree = await api.project.getTree(params.id, commit); + return { + resource: "projects", + params: { + ...params, + project, + view: { + resource: params.view.resource, + params: { + loadedBranches: branches, + loadedPeers: peers, + loadedTree: tree, + selectedCommit: commit, + }, + }, + }, + }; + } else { + const project = await api.project.getById(params.id); + return { + resource: "projects", + params: { + ...params, + view: params.view, + project, + }, + }; + } + } catch (error: any) { + return { + resource: "loadError", + params: { + title: params.id, + errorMessage: "Not able to load this project.", + stackTrace: error.stack, + }, + }; + } +} + +// Detects branch names and commit IDs at the start of `input` and extract it. +function detectRevision( + input: string, + branches: Record, +): { path: string; revision?: string } { + const commitPath = [input.slice(0, 40), input.slice(41)]; + const branch = Object.entries(branches).find(([branchName]) => + input.startsWith(branchName), + ); + + if (branch) { + const [revision, path] = [ + input.slice(0, branch[0].length), + input.slice(branch[0].length + 1), + ]; + return { + revision, + path: path || "/", + }; + } else if (isOid(commitPath[0])) { + return { + revision: commitPath[0], + path: commitPath[1] || "/", + }; + } else { + return { path: input }; + } +} + function sanitizeQueryString(queryString: string): string { return queryString.startsWith("?") ? queryString.substring(1) : queryString; } @@ -49,7 +263,6 @@ export function createProjectRoute( resource: "projects", params: { ...activeRoute.params, - line: undefined, hash: undefined, search: undefined, ...projectRouteParams, @@ -105,7 +318,6 @@ export function resolveProjectRoute( } if (!content || content === "tree") { - const line = url.href.match(/#L\d+$/)?.pop(); const hash = url.href.match(/#{1}[^#.]+$/)?.pop(); return { view: { resource: "tree" }, @@ -115,7 +327,6 @@ export function resolveProjectRoute( path: undefined, revision: undefined, search: undefined, - line: line?.substring(1), hash: hash?.substring(1), route: segments.join("/"), }; @@ -202,3 +413,5 @@ export function resolveProjectRoute( return null; } + +export const testExports = { isOid }; diff --git a/tests/e2e/historyRouter.spec.ts b/tests/e2e/historyRouter.spec.ts index 1871f0f0e..0035e60c3 100644 --- a/tests/e2e/historyRouter.spec.ts +++ b/tests/e2e/historyRouter.spec.ts @@ -58,6 +58,9 @@ test.describe("project page navigation", () => { const projectTreeURL = `${sourceBrowsingUrl}/tree/${aliceMainHead}`; await page.goto(projectTreeURL); + await page + .getByRole("progressbar", { name: "Page loading" }) + .waitFor({ state: "hidden" }); await expect(page).toHaveURL(projectTreeURL); await page.locator('role=link[name="6 commits"]').click(); diff --git a/tests/e2e/project/patches.spec.ts b/tests/e2e/project/patches.spec.ts index 80109d6b1..ba2fa6db4 100644 --- a/tests/e2e/project/patches.spec.ts +++ b/tests/e2e/project/patches.spec.ts @@ -80,6 +80,9 @@ test("navigate through revision diffs", async ({ page }) => { await secondRevision .locator("role=link[name='Compare 0dc373d..5b35def']") .click(); + await expect( + page.getByRole("link", { name: "Diff 0dc373..5b35de" }), + ).toBeVisible(); await page.goBack(); } // First revision diff --git a/tests/support/router.ts b/tests/support/router.ts index a1eaf85a4..3d54c784c 100644 --- a/tests/support/router.ts +++ b/tests/support/router.ts @@ -17,13 +17,13 @@ export const expectBackAndForwardNavigationWorks = async ( await page.goBack(); await page - .locator("role=progressbar[name='Page loading']") + .getByRole("progressbar", { name: "Page loading" }) .waitFor({ state: "hidden" }); await expect(page).toHaveURL(beforeURL); await page.goForward(); await page - .locator("role=progressbar[name='Page loading']") + .getByRole("progressbar", { name: "Page loading" }) .waitFor({ state: "hidden" }); await expect(page).toHaveURL(currentURL); }; diff --git a/tests/unit/projectRouter.test.ts b/tests/unit/projectRouter.test.ts new file mode 100644 index 000000000..de6b24c9a --- /dev/null +++ b/tests/unit/projectRouter.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, test } from "vitest"; +import { testExports } from "@app/views/projects/router"; + +// Defining the window.origin value, since vitest doesn't provide one. +window.origin = "http://localhost:3000"; + +describe("isOid", () => { + test.each([ + { oid: "a64ae9c6d572e0ad906faa9a4a7a8d43f113278c", expected: true }, + { oid: "a64ae9c", expected: false }, + ])("isOid $oid => $expected", ({ oid, expected }) => { + expect(testExports.isOid(oid)).toEqual(expected); + }); +}); diff --git a/tests/unit/router.test.ts b/tests/unit/router.test.ts index 0926e6ad4..5c0167b54 100644 --- a/tests/unit/router.test.ts +++ b/tests/unit/router.test.ts @@ -4,15 +4,6 @@ import { testExports } from "@app/lib/router"; // Defining the window.origin value, since vitest doesn't provide one. window.origin = "http://localhost:3000"; -describe("isOid", () => { - test.each([ - { oid: "a64ae9c6d572e0ad906faa9a4a7a8d43f113278c", expected: true }, - { oid: "a64ae9c", expected: false }, - ])("isOid $oid => $expected", ({ oid, expected }) => { - expect(testExports.isOid(oid)).toEqual(expected); - }); -}); - describe("routeToPath", () => { test.each([ { input: { resource: "home" }, output: "/", description: "Home Route" }, @@ -42,16 +33,25 @@ describe("routeToPath", () => { }); describe("pathToRoute", () => { + const dummyUrl = "https://localhost"; test.each([ - { input: "", output: null, description: "Empty not found Route" }, { - input: "/foo/baz/bar", + input: new URL("/foo/baz/bar", dummyUrl), output: null, description: "Non existant not found route", }, - { input: "/", output: { resource: "home" }, description: "Home Route" }, { - input: "/seeds/willow.radicle.garden", + input: new URL("", dummyUrl), + output: { resource: "home" }, + description: "Home Route", + }, + { + input: new URL("/", dummyUrl), + output: { resource: "home" }, + description: "Home Route", + }, + { + input: new URL("/seeds/willow.radicle.garden", dummyUrl), output: { resource: "seeds", params: { hostnamePort: "willow.radicle.garden", projectPageIndex: 0 }, @@ -59,7 +59,10 @@ describe("pathToRoute", () => { description: "Seed View Route", }, { - input: "/seeds/willow.radicle.garden/rad:zKtT7DmF9H34KkvcKj9PHW19WzjT/", + input: new URL( + "/seeds/willow.radicle.garden/rad:zKtT7DmF9H34KkvcKj9PHW19WzjT/", + dummyUrl, + ), output: { resource: "projects", params: { @@ -73,13 +76,18 @@ describe("pathToRoute", () => { description: "Seed Project Route w trailing slash", }, { - input: + input: new URL( "/seeds/willow.radicle.garden/rad:zKtT7DmF9H34KkvcKj9PHW19WzjT/nope", + dummyUrl, + ), output: null, description: "Seed Project Route w undefined suffix", }, { - input: "/seeds/willow.radicle.garden/rad:zKtT7DmF9H34KkvcKj9PHW19WzjT", + input: new URL( + "/seeds/willow.radicle.garden/rad:zKtT7DmF9H34KkvcKj9PHW19WzjT", + dummyUrl, + ), output: { resource: "projects", params: {