diff --git a/packages/app/e2e/browser/add-project-flow.spec.ts b/packages/app/e2e/browser/add-project-flow.spec.ts index bce5adcaaf..4f5ac66f71 100644 --- a/packages/app/e2e/browser/add-project-flow.spec.ts +++ b/packages/app/e2e/browser/add-project-flow.spec.ts @@ -5,27 +5,26 @@ import path from "node:path"; import { test, expect } from "../support/fixtures"; import { addProjectFlow, - chooseAddHostFromProjectFlow, - addProjectFlowBack, - addProjectFlowHost, + addProjectFlowHostTrigger, addProjectFlowInput, - addProjectFlowMethod, - chooseAddProjectMethod, - expectAddProjectPage, - expectNewWorkspaceForAddedProject, + addProjectFlowSubmit, + chooseAddHostFromProjectFlow, + chooseAddProjectHost, + chooseAddProjectLocation, + chooseAddProjectTab, expectAddProjectResultVisible, + expectAddProjectTab, + expectNewWorkspaceForAddedProject, navigateAddProjectResults, navigateAndDismissAddProject, - watchAddProjectRenderWarnings, openAddProjectFlow, - openAddProjectHostSelection, + watchAddProjectRenderWarnings, } from "../support/helpers/add-project-flow"; import { gotoAppShell } from "../support/helpers/app"; import { - disconnectAllHostsAndReload, addConnectedHostAndReload, - addConnectedHostsAndReload, addOfflineHostAndReload, + disconnectAllHostsAndReload, waitForConnectedHost, } from "../support/helpers/hosts"; import { @@ -36,6 +35,8 @@ import { expectOpenedProject } from "../support/helpers/project-picker-ui"; import { connectSeedClient } from "../support/helpers/seed-client"; import { getServerId } from "../support/helpers/server-id"; +const MOD = process.platform === "darwin" ? "Meta" : "Control"; + const SECONDARY_HOST_ID = "add-project-flow-secondary"; const SECONDARY_HOST_LABEL = "Secondary Host"; @@ -70,13 +71,14 @@ async function expectProjectHasNoWorkspaces(projectId: string): Promise { } } -test.describe("Add Project command-center flow", () => { +test.describe("Add project sheet", () => { test.describe.configure({ timeout: 180_000 }); - test("Add host replaces the project dialog when no hosts are connected", async ({ page }) => { + test("Add host replaces the project sheet when no hosts are connected", async ({ page }) => { await gotoAppShell(page); await disconnectAllHostsAndReload(page); - await openAddProjectHostSelection(page); + await page.locator('[data-testid="sidebar-add-project"]:visible').click(); + await expect(addProjectFlow(page)).toContainText("No connected hosts"); const originalUrl = page.url(); await chooseAddHostFromProjectFlow(page); await expect(addProjectFlow(page)).toBeHidden(); @@ -86,22 +88,36 @@ test.describe("Add Project command-center flow", () => { await expect(page).toHaveURL(originalUrl); }); - test("method selection shows the daemon's available project sources without search", async ({ + test("opens on Existing, switches tabs with Mod+1/2/3, keeps each draft, and closes on Escape", async ({ page, }) => { + const renderWarnings = watchAddProjectRenderWarnings(page); await gotoAppShell(page); - await openAddProjectFlow(page); - await expect(addProjectFlowMethod(page, "directory-search")).toBeVisible(); - await expect(addProjectFlowMethod(page, "github")).toContainText("Clone from GitHub"); - await expect(addProjectFlowMethod(page, "new-directory")).toContainText("New directory"); - await expect(addProjectFlowInput(page)).toHaveCount(0); - await expect(addProjectFlow(page).getByRole("textbox")).toHaveCount(0); - await expect(page.getByTestId("add-project-flow-page-host")).toHaveCount(0); + await page.keyboard.type("paseo"); + await page.keyboard.press(`${MOD}+2`); + await expectAddProjectTab(page, "clone"); + await expect(addProjectFlowInput(page)).toBeFocused(); + await page.keyboard.type("getpaseo/"); + await page.keyboard.press(`${MOD}+3`); + await expectAddProjectTab(page, "new-folder"); + await expect(addProjectFlowSubmit(page)).toBeDisabled(); + + await page.keyboard.press(`${MOD}+1`); + await expectAddProjectTab(page, "existing"); + await expect(addProjectFlowInput(page)).toHaveValue("paseo"); + await chooseAddProjectTab(page, "clone"); + await expect(addProjectFlowInput(page)).toHaveValue("getpaseo/"); + + await navigateAndDismissAddProject(page); + await expect(addProjectFlow(page)).not.toBeVisible(); + expect(renderWarnings).toEqual([]); }); - test("an offline extra host neither appears nor forces host selection", async ({ page }) => { + test("a single connected host shows no host picker, even with an offline host", async ({ + page, + }) => { await gotoAppShell(page); await addOfflineHostAndReload(page, { serverId: "add-project-flow-offline", @@ -110,8 +126,7 @@ test.describe("Add Project command-center flow", () => { await openAddProjectFlow(page); - await expect(addProjectFlowHost(page, "add-project-flow-offline")).toHaveCount(0); - await expect(addProjectFlowMethod(page, "directory-search")).toBeVisible(); + await expect(addProjectFlowHostTrigger(page)).toHaveCount(0); }); test.describe("with two connected hosts", () => { @@ -125,73 +140,7 @@ test.describe("Add Project command-center flow", () => { await secondaryHost?.close(); }); - test("keyboard selection chooses the second host", async ({ page }) => { - await gotoAppShell(page); - await addConnectedHostAndReload(page, { - serverId: secondaryHost.serverId, - label: SECONDARY_HOST_LABEL, - port: secondaryHost.port, - }); - await waitForConnectedHost(page, { - serverId: SECONDARY_HOST_ID, - endpoint: `localhost:${secondaryHost.port}`, - }); - await openAddProjectHostSelection(page); - - await page.keyboard.press("ArrowDown"); - await page.keyboard.press("Enter"); - - await expectAddProjectPage(page, "method"); - await expect(addProjectFlow(page)).toContainText(SECONDARY_HOST_LABEL); - }); - - test("Escape and Back restore searchable page input before closing at the root", async ({ - page, - }) => { - const renderWarnings = watchAddProjectRenderWarnings(page); - await gotoAppShell(page); - await addConnectedHostAndReload(page, { - serverId: secondaryHost.serverId, - label: SECONDARY_HOST_LABEL, - port: secondaryHost.port, - }); - await waitForConnectedHost(page, { - serverId: SECONDARY_HOST_ID, - endpoint: `localhost:${secondaryHost.port}`, - }); - await openAddProjectHostSelection(page); - - await addProjectFlowInput(page).fill("o"); - await page.keyboard.press("ArrowDown"); - await page.keyboard.press("Enter"); - await expectAddProjectPage(page, "method"); - - await chooseAddProjectMethod(page, "new-directory"); - await expectAddProjectPage(page, "new-directory-parent"); - await page.keyboard.press("Escape"); - - await expectAddProjectPage(page, "method"); - await expect(addProjectFlowInput(page)).toHaveCount(0); - await chooseAddProjectMethod(page, "new-directory"); - await expectAddProjectPage(page, "new-directory-parent"); - await addProjectFlowBack(page).click(); - - await expectAddProjectPage(page, "method"); - await addProjectFlowBack(page).click(); - await expectAddProjectPage(page, "host"); - await expect(addProjectFlowInput(page)).toHaveValue("o"); - await page.keyboard.press("Enter"); - await expectAddProjectPage(page, "method"); - await expect(addProjectFlow(page)).toContainText(SECONDARY_HOST_LABEL); - - await page.keyboard.press("Escape"); - await expectAddProjectPage(page, "host"); - await navigateAndDismissAddProject(page); - await expect(addProjectFlow(page)).not.toBeVisible(); - expect(renderWarnings).toEqual([]); - }); - - test("New directory creates a Project on the selected remote host", async ({ page }) => { + test("New folder creates a Project on the host chosen in the sheet", async ({ page }) => { const parentDirectory = await mkdtemp(path.join(tmpdir(), "paseo-e2e-remote-project-")); const directoryName = `remote-${randomUUID().slice(0, 8)}`; const directoryPath = path.join(parentDirectory, directoryName); @@ -207,18 +156,15 @@ test.describe("Add Project command-center flow", () => { serverId: SECONDARY_HOST_ID, endpoint: `localhost:${secondaryHost.port}`, }); - await openAddProjectHostSelection(page); - await addProjectFlowHost(page, SECONDARY_HOST_ID).click(); - await expectAddProjectPage(page, "method"); + await openAddProjectFlow(page); + await chooseAddProjectTab(page, "new-folder"); + await addProjectFlowInput(page).fill(directoryName); - await expect(addProjectFlowMethod(page, "new-directory")).toContainText( - `Create an empty directory on ${SECONDARY_HOST_LABEL}`, - ); - await chooseAddProjectMethod(page, "new-directory"); - await addProjectFlowInput(page).fill(parentDirectory); - await page.keyboard.press("Enter"); - await expectAddProjectPage(page, "new-directory-name"); - await page.keyboard.type(directoryName); + await chooseAddProjectHost(page, SECONDARY_HOST_ID); + await expect(addProjectFlowHostTrigger(page)).toContainText(SECONDARY_HOST_LABEL); + await expect(addProjectFlowInput(page)).toHaveValue(directoryName); + await chooseAddProjectLocation(page, parentDirectory); + await addProjectFlowInput(page).focus(); await page.keyboard.press("Enter"); const projectId = await expectOpenedProject(page, directoryName); @@ -236,57 +182,35 @@ test.describe("Add Project command-center flow", () => { }); }); - test("filtered hosts keep the keyboard-selected row visible", async ({ page }) => { - const hosts: IsolatedHostDaemon[] = []; + test("a host that disconnects keeps its draft and blocks submit instead of moving it", async ({ + page, + }) => { + const droppingHost = await startIsolatedHostDaemon("add-project-flow-dropping"); try { - for (let index = 1; index <= 3; index += 1) { - hosts.push(await startIsolatedHostDaemon(`scroll-host-${index}`)); - } - await page.setViewportSize({ width: 1280, height: 360 }); await gotoAppShell(page); - await addConnectedHostsAndReload( - page, - hosts.map((host, index) => ({ - serverId: host.serverId, - port: host.port, - label: index < 2 ? `Fleet 0${index + 1}` : "Other host", - })), - { primaryLabel: "Fleet 00" }, + await addConnectedHostAndReload(page, { + serverId: droppingHost.serverId, + label: "Dropping Host", + port: droppingHost.port, + }); + await waitForConnectedHost(page, { + serverId: droppingHost.serverId, + endpoint: `localhost:${droppingHost.port}`, + }); + await openAddProjectFlow(page); + await chooseAddProjectHost(page, droppingHost.serverId); + await addProjectFlowInput(page).fill(homedir()); + + await droppingHost.close(); + await expect(page.getByTestId("add-project-flow-error")).toHaveText( + "Dropping Host is offline", + { timeout: 30_000 }, ); - for (const host of hosts) { - await waitForConnectedHost(page, { - serverId: host.serverId, - endpoint: `localhost:${host.port}`, - }); - } - await openAddProjectHostSelection(page); - await expect( - addProjectFlow(page).getByRole("button").filter({ hasText: "Other host" }), - ).toBeVisible(); - - await addProjectFlowInput(page).fill("Fleet"); - await expect(addProjectFlowHost(page, hosts[2]!.serverId)).toHaveCount(0); - await navigateAddProjectResults(page, "ArrowDown", 2); - await expectAddProjectResultVisible(page, "Fleet 02"); - - // Filtering out the first host moves retained rows to new positions. - await addProjectFlowInput(page).fill("scroll-host"); - await expect(addProjectFlowHost(page, getServerId())).toHaveCount(0); - await expectAddProjectResultVisible(page, "Fleet 01"); - await navigateAddProjectResults(page, "ArrowDown", 2); - await expectAddProjectResultVisible(page, "Other host"); - await navigateAddProjectResults(page, "ArrowDown", 1); - await expectAddProjectResultVisible(page, "Fleet 01"); - - await addProjectFlowInput(page).fill("Fleet"); - await expectAddProjectResultVisible(page, "Fleet 00"); - await navigateAddProjectResults(page, "ArrowDown", 2); - await expectAddProjectResultVisible(page, "Fleet 02"); - await page.keyboard.press("Enter"); - await expectAddProjectPage(page, "method"); - await expect(addProjectFlow(page)).toContainText("Fleet 02"); + await expect(addProjectFlowHostTrigger(page)).toContainText("Dropping Host"); + await expect(addProjectFlowInput(page)).toHaveValue(homedir()); + await expect(addProjectFlowSubmit(page)).toBeDisabled(); } finally { - await Promise.all(hosts.map((host) => host.close())); + await droppingHost.close(); } }); @@ -297,9 +221,6 @@ test.describe("Add Project command-center flow", () => { await gotoAppShell(page); await openAddProjectFlow(page); - await page.keyboard.press("Enter"); - await expectAddProjectPage(page, "directory-search"); - await expect(addProjectFlowInput(page)).toBeFocused(); await page.keyboard.type(projectPickerFixture.fuzzyQuery); await expect(addProjectFlow(page)).toContainText(projectPickerFixture.projectName, { timeout: 30_000, @@ -323,45 +244,32 @@ test.describe("Add Project command-center flow", () => { const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-scroll-")); const rowPath = (index: number) => path.join(parentDirectory, `scroll-probe-${String(index).padStart(2, "0")}`); + const rowName = (index: number) => path.basename(rowPath(index)); let projectId: string | null = null; try { await Promise.all(Array.from({ length: 16 }, (_, index) => mkdir(rowPath(index)))); await gotoAppShell(page); await openAddProjectFlow(page); - await chooseAddProjectMethod(page, "directory-search"); - await addProjectFlowInput(page).fill(path.basename(parentDirectory)); + await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}/scroll-probe`); const results = page.getByTestId("add-project-flow-results"); await expect(results.getByRole("button", { name: /scroll-probe-/ })).toHaveCount(16, { timeout: 30_000, }); - await navigateAddProjectResults(page, "ArrowDown", 12); - await expectAddProjectResultVisible(page, rowPath(11)); + await navigateAddProjectResults(page, "ArrowDown", 11); + await expectAddProjectResultVisible(page, rowName(11)); await navigateAddProjectResults(page, "ArrowUp", 12); - await expectAddProjectResultVisible(page, parentDirectory); - await navigateAddProjectResults(page, "ArrowUp", 1); - await expectAddProjectResultVisible(page, rowPath(15)); + await expectAddProjectResultVisible(page, rowName(15)); await navigateAddProjectResults(page, "ArrowDown", 1); - await expectAddProjectResultVisible(page, parentDirectory); + await expectAddProjectResultVisible(page, rowName(0)); - await navigateAddProjectResults(page, "ArrowDown", 12); - await expectAddProjectResultVisible(page, rowPath(11)); - await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}probe`); - await expect(results.getByRole("button")).toHaveCount(16); - await expectAddProjectResultVisible(page, rowPath(0)); - await navigateAddProjectResults(page, "ArrowDown", 12); - await expectAddProjectResultVisible(page, rowPath(12)); - await addProjectFlowInput(page).fill(path.basename(parentDirectory)); - await expect(results.getByRole("button")).toHaveCount(17); - await expectAddProjectResultVisible(page, parentDirectory); - await navigateAddProjectResults(page, "ArrowDown", 12); - await expectAddProjectResultVisible(page, rowPath(11)); + await navigateAddProjectResults(page, "ArrowDown", 11); await page.keyboard.press("Enter"); - projectId = await expectOpenedProject(page, "scroll-probe-11"); + projectId = await expectOpenedProject(page, rowName(11)); await expectNewWorkspaceForAddedProject(page, { serverId: getServerId(), projectId, - projectName: "scroll-probe-11", + projectName: rowName(11), projectPath: rowPath(11), }); } finally { @@ -370,28 +278,146 @@ test.describe("Add Project command-center flow", () => { } }); - test("a complete repository URL remains selectable without a GitHub search result", async ({ + test("Enter on a focused result adds that folder, not the one picked before", async ({ + page, + }) => { + const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-focus-")); + const firstPath = path.join(parentDirectory, "focus-probe-a"); + const secondPath = path.join(parentDirectory, "focus-probe-b"); + let projectId: string | null = null; + try { + await Promise.all([mkdir(firstPath), mkdir(secondPath)]); + await gotoAppShell(page); + await openAddProjectFlow(page); + await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}/focus-probe`); + const results = page.getByTestId("add-project-flow-results"); + await expect(results.getByRole("button", { name: /focus-probe-/ })).toHaveCount(2, { + timeout: 30_000, + }); + + await results.getByRole("button", { name: /focus-probe-b/ }).focus(); + await page.keyboard.press("Enter"); + projectId = await expectOpenedProject(page, "focus-probe-b"); + await expectNewWorkspaceForAddedProject(page, { + serverId: getServerId(), + projectId, + projectName: "focus-probe-b", + projectPath: secondPath, + }); + } finally { + if (projectId) await removeCreatedProject(secondPath, projectId); + await rm(parentDirectory, { recursive: true, force: true }); + } + }); + + test("Enter while a new search runs does not open a row from the previous search", async ({ + page, + }) => { + const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-stale-")); + try { + await mkdir(path.join(parentDirectory, "stale-probe-a")); + await gotoAppShell(page); + await openAddProjectFlow(page); + const prefix = path.basename(parentDirectory); + await addProjectFlowInput(page).fill(`${prefix}/stale-probe`); + const results = page.getByTestId("add-project-flow-results"); + await expect(results.getByRole("button", { name: /stale-probe-a/ })).toBeVisible({ + timeout: 30_000, + }); + + await addProjectFlowInput(page).fill(`${prefix}/no-such-folder`); + await page.keyboard.press("Enter"); + await expect(addProjectFlow(page).getByText("No matching folders")).toBeVisible({ + timeout: 30_000, + }); + await expect(addProjectFlow(page)).toBeVisible(); + await expect(addProjectFlowSubmit(page)).toBeDisabled(); + } finally { + await rm(parentDirectory, { recursive: true, force: true }); + } + }); + + test("a complete repository URL is cloneable without a GitHub search result", async ({ page, }) => { await gotoAppShell(page); await openAddProjectFlow(page); - await chooseAddProjectMethod(page, "github"); + await chooseAddProjectTab(page, "clone"); const remote = "https://github.invalid/acme/manual.git"; await addProjectFlowInput(page).fill(remote); await expect(addProjectFlow(page).getByText("manual", { exact: true })).toBeVisible(); - await page.keyboard.press("Enter"); - - await expectAddProjectPage(page, "github-location"); - const title = addProjectFlow(page).getByTestId("add-project-flow-title"); - await expect(title.getByText("Choose destination", { exact: true })).toBeVisible(); - await expect(title.getByText("localhost", { exact: true })).toBeVisible(); - await expect(title).not.toContainText("Where should Paseo create"); - await addProjectFlowBack(page).click(); - await expect(addProjectFlowInput(page)).toHaveValue(remote); + await expect(page.getByTestId("add-project-flow-location")).toContainText("/manual"); + await expect(addProjectFlowSubmit(page)).toBeEnabled(); }); - test("New directory validates the name, restores parent and name state, then creates a Project", async ({ + test("Enter activates a focused button instead of the primary action", async ({ page }) => { + await gotoAppShell(page); + await openAddProjectFlow(page); + await chooseAddProjectTab(page, "clone"); + await addProjectFlowInput(page).fill("https://github.invalid/acme/manual.git"); + await expect(addProjectFlowSubmit(page)).toBeEnabled(); + + await addProjectFlow(page).getByRole("button", { name: "Close", exact: true }).focus(); + await page.keyboard.press("Enter"); + await expect(addProjectFlow(page)).toBeHidden(); + }); + + test("a row picked during a search is not replaced by the answer's first row", async ({ + page, + }) => { + const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-dropped-pick-")); + try { + await Promise.all([ + mkdir(path.join(parentDirectory, "previous-probe")), + mkdir(path.join(parentDirectory, "incoming-probe")), + ]); + await gotoAppShell(page); + await openAddProjectFlow(page); + const prefix = path.basename(parentDirectory); + const results = page.getByTestId("add-project-flow-results"); + await addProjectFlowInput(page).fill(`${prefix}/previous-probe`); + await expect(results.getByRole("button", { name: /previous-probe/ })).toBeVisible({ + timeout: 30_000, + }); + + await addProjectFlowInput(page).fill(`${prefix}/incoming-probe`); + await page.keyboard.press("ArrowDown"); + await expect(results.getByRole("button", { name: /incoming-probe/ })).toBeVisible({ + timeout: 30_000, + }); + await expect(addProjectFlowSubmit(page)).toBeDisabled(); + } finally { + await rm(parentDirectory, { recursive: true, force: true }); + } + }); + + test("Enter in Location while a new search runs keeps the current location", async ({ page }) => { + const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-stale-location-")); + try { + await mkdir(path.join(parentDirectory, "stale-probe-a")); + await gotoAppShell(page); + await openAddProjectFlow(page); + await chooseAddProjectTab(page, "new-folder"); + const location = page.getByTestId("add-project-flow-location"); + const locationBefore = await location.textContent(); + await location.click(); + const search = page.getByPlaceholder("Search folders or enter a path").last(); + const prefix = path.basename(parentDirectory); + await search.fill(`${prefix}/stale-probe`); + await expect(page.getByText(/stale-probe-a/).last()).toBeVisible({ timeout: 30_000 }); + + await search.fill(`${prefix}/no-such-folder`); + await page.keyboard.press("Enter"); + await expect(page.getByText("No matching folders")).toBeVisible({ timeout: 30_000 }); + await expect(search).toBeVisible(); + await expect(location).toHaveText(locationBefore ?? ""); + } finally { + await rm(parentDirectory, { recursive: true, force: true }); + } + }); + + test("New folder validates the name, then creates a Project in the chosen location", async ({ page, }) => { const parentDirectory = await mkdtemp(path.join(tmpdir(), "paseo-e2e-new-project-")); @@ -402,27 +428,23 @@ test.describe("Add Project command-center flow", () => { try { await gotoAppShell(page); await openAddProjectFlow(page); - await chooseAddProjectMethod(page, "new-directory"); + await chooseAddProjectTab(page, "new-folder"); + await chooseAddProjectLocation(page, parentDirectory); - await page.keyboard.type(parentDirectory); - await page.keyboard.press("Enter"); - await expectAddProjectPage(page, "new-directory-name"); - await page.keyboard.type("../invalid"); - await page.keyboard.press("Enter"); + await addProjectFlowInput(page).fill("../invalid"); + const nameError = page.getByTestId("add-project-flow-name-field-error"); + await expect(nameError).toHaveText("Use a name without slashes"); + await expect(addProjectFlowSubmit(page)).toBeDisabled(); - const error = page.getByTestId("add-project-flow-error"); - await expect(error).toBeVisible(); - await expect(error).toContainText(/name|separator|directory/i); - await expectAddProjectPage(page, "new-directory-name"); + await addProjectFlowInput(page).fill("C:repo"); + await expect(nameError).toHaveText("Use a name without a drive letter"); + await expect(addProjectFlowSubmit(page)).toBeDisabled(); await addProjectFlowInput(page).fill(directoryName); - await addProjectFlowBack(page).click(); - await expectAddProjectPage(page, "new-directory-parent"); - await expect(addProjectFlowInput(page)).toHaveValue(parentDirectory); - await page.keyboard.press("Enter"); - await expectAddProjectPage(page, "new-directory-name"); - await expect(addProjectFlowInput(page)).toHaveValue(directoryName); - await page.keyboard.press("Enter"); + await expect(nameError).toBeHidden(); + await expect(addProjectFlowSubmit(page)).toBeEnabled(); + await expect(page.getByTestId("add-project-flow-location")).toContainText(directoryName); + await addProjectFlowSubmit(page).click(); projectId = await expectOpenedProject(page, directoryName); await expectNewWorkspaceForAddedProject(page, { @@ -461,10 +483,11 @@ test.describe("Compact Add project context", () => { await gotoAppShell(page); await page.getByRole("button", { name: "Open menu", exact: true }).click(); await openAddProjectFlow(page); - await chooseAddProjectMethod(page, "directory-search"); await addProjectFlowInput(page).fill(projectPickerFixture.fuzzyQuery); - await expect(addProjectFlow(page)).toContainText(projectPickerFixture.projectName); - await page.keyboard.press("Enter"); + await expect( + page.getByRole("button", { name: new RegExp(projectPickerFixture.projectName) }).first(), + ).toBeVisible({ timeout: 30_000 }); + await addProjectFlowSubmit(page).click(); const projectId = await expectOpenedProject(page, projectPickerFixture.projectName); projectPickerFixture.rememberProjectId(projectId); await expectNewWorkspaceForAddedProject(page, { diff --git a/packages/app/e2e/browser/add-project-github.real.spec.ts b/packages/app/e2e/browser/add-project-github.real.spec.ts index 4285f05e7c..bc0037d127 100644 --- a/packages/app/e2e/browser/add-project-github.real.spec.ts +++ b/packages/app/e2e/browser/add-project-github.real.spec.ts @@ -4,10 +4,9 @@ import path from "node:path"; import { expect, test } from "../support/fixtures"; import { addProjectFlow, - addProjectFlowBack, addProjectFlowInput, - chooseAddProjectMethod, - expectAddProjectPage, + chooseAddProjectLocation, + chooseAddProjectTab, expectNewWorkspaceForAddedProject, openAddProjectFlow, } from "../support/helpers/add-project-flow"; @@ -39,28 +38,22 @@ test.describe("Add Project GitHub flow", () => { await gotoAppShell(page); await openAddProjectFlow(page); - await chooseAddProjectMethod(page, "github"); + await chooseAddProjectTab(page, "clone"); await addProjectFlowInput(page).fill("getpaseo/paseo"); await expect(addProjectFlow(page).getByText("getpaseo/paseo", { exact: true })).toBeVisible({ timeout: 30_000, }); - await addProjectFlowInput(page).fill(""); + await addProjectFlowInput(page).fill(repository.fullName); const repositoryRow = addProjectFlow(page).getByText(repository.fullName, { exact: true }); await expect(repositoryRow).toBeVisible({ timeout: 30_000 }); await repositoryRow.click(); - await expectAddProjectPage(page, "github-location"); - - await addProjectFlowInput(page).fill(parentDirectory); - await expect(addProjectFlow(page)).toContainText(checkoutPath, { timeout: 30_000 }); - - await addProjectFlowBack(page).click(); - await expectAddProjectPage(page, "github-search"); - await expect(repositoryRow).toBeVisible(); - await repositoryRow.click(); - await expectAddProjectPage(page, "github-location"); - await expect(addProjectFlowInput(page)).toHaveValue(parentDirectory); + await chooseAddProjectLocation(page, parentDirectory); + await expect(page.getByTestId("add-project-flow-location")).toContainText( + path.join(path.basename(parentDirectory), repository.name), + ); + await addProjectFlowInput(page).focus(); await mkdir(checkoutPath); await page.keyboard.press("Enter"); diff --git a/packages/app/e2e/browser/empty-project-persists.spec.ts b/packages/app/e2e/browser/empty-project-persists.spec.ts index fb2f98841e..5839547509 100644 --- a/packages/app/e2e/browser/empty-project-persists.spec.ts +++ b/packages/app/e2e/browser/empty-project-persists.spec.ts @@ -4,7 +4,7 @@ import { test, expect, type Page } from "../support/fixtures"; import { gotoAppShell } from "../support/helpers/app"; import { addProjectFlowInput, - chooseAddProjectMethod, + addProjectFlowSubmit, openAddProjectFlow, } from "../support/helpers/add-project-flow"; import { expectOpenedProject } from "../support/helpers/project-picker-ui"; @@ -53,7 +53,6 @@ async function removeProjectFromSidebar(page: Page, projectViewKey: string): Pro async function addProjectFromPicker(page: Page, projectPath: string): Promise { await openAddProjectFlow(page); - await chooseAddProjectMethod(page, "directory-search"); const input = addProjectFlowInput(page); await input.fill(projectPath); @@ -85,7 +84,6 @@ test.describe("Project picker search", () => { await gotoAppShell(page); await waitForSidebarProjectListReady(page); await openAddProjectFlow(page); - await chooseAddProjectMethod(page, "directory-search"); const input = addProjectFlowInput(page); await input.fill(projectPickerFixture.fuzzyQuery); @@ -93,6 +91,7 @@ test.describe("Project picker search", () => { const suggestion = page.getByText(projectPickerFixture.projectName, { exact: false }).first(); await expect(suggestion).toBeVisible({ timeout: 30_000 }); await suggestion.click(); + await addProjectFlowSubmit(page).click(); const projectId = await expectOpenedProject(page, projectPickerFixture.projectName); projectPickerFixture.rememberProjectId(projectId); @@ -104,13 +103,11 @@ test.describe("Project picker search", () => { await gotoAppShell(page); await waitForSidebarProjectListReady(page); await openAddProjectFlow(page); - await chooseAddProjectMethod(page, "directory-search"); const input = addProjectFlowInput(page); await input.fill("paseo-loading-state-no-match"); - await expect(page.getByText("Start typing a path", { exact: true })).toHaveCount(0); - await expect(page.getByText("Loading...", { exact: true })).toBeVisible(); + await expect(page.getByText("Searching...", { exact: true })).toBeVisible(); }); }); diff --git a/packages/app/e2e/browser/new-workspace.spec.ts b/packages/app/e2e/browser/new-workspace.spec.ts index 7ee6fe9737..237a5bce97 100644 --- a/packages/app/e2e/browser/new-workspace.spec.ts +++ b/packages/app/e2e/browser/new-workspace.spec.ts @@ -55,7 +55,7 @@ import { import { getServerId } from "../support/helpers/server-id"; import { selectSidebarStatusGrouping } from "../support/helpers/sidebar"; import { getE2EDaemonPort } from "../support/helpers/daemon-port"; -import { chooseAddProjectMethod, expectAddProjectPage } from "../support/helpers/add-project-flow"; +import { expectAddProjectTab } from "../support/helpers/add-project-flow"; import { seedSavedSettingsHosts } from "../support/helpers/settings"; import { expectSidebarWorkspaceSelected, @@ -291,8 +291,7 @@ test.describe("New workspace flow", () => { await expect(addProject).toContainText(/(?:⌘|Ctrl\+)O/); await addProject.click(); - await expectAddProjectPage(page, "method"); - await chooseAddProjectMethod(page, "directory-search"); + await expectAddProjectTab(page, "existing"); } finally { await repo.cleanup(); } diff --git a/packages/app/e2e/browser/projects-settings.spec.ts b/packages/app/e2e/browser/projects-settings.spec.ts index 0732ec6732..0e1b9efe45 100644 --- a/packages/app/e2e/browser/projects-settings.spec.ts +++ b/packages/app/e2e/browser/projects-settings.spec.ts @@ -46,11 +46,7 @@ import { } from "../support/helpers/project-settings"; import { gotoAppShell } from "../support/helpers/app"; import { openCompactSettings } from "../support/helpers/settings"; -import { - addProjectFlowInput, - chooseAddProjectMethod, - openAddProjectFlow, -} from "../support/helpers/add-project-flow"; +import { addProjectFlowInput, openAddProjectFlow } from "../support/helpers/add-project-flow"; import { createTempGitRepo } from "../support/helpers/workspace"; import { buildOpenProjectRoute, @@ -167,7 +163,6 @@ async function readProjectConfigFile(project: ProjectsSettingsProject): Promise< async function addProjectFromSidebar(page: Page, projectPath: string): Promise { await openAddProjectFlow(page); - await chooseAddProjectMethod(page, "directory-search"); const input = addProjectFlowInput(page); await input.fill(projectPath); diff --git a/packages/app/e2e/support/helpers/add-project-flow.ts b/packages/app/e2e/support/helpers/add-project-flow.ts index 1190bf0676..2846e92212 100644 --- a/packages/app/e2e/support/helpers/add-project-flow.ts +++ b/packages/app/e2e/support/helpers/add-project-flow.ts @@ -1,73 +1,61 @@ +import path from "node:path"; import { expect, type Locator, type Page } from "@playwright/test"; -export type AddProjectFlowPage = - | "host" - | "method" - | "directory-search" - | "github-search" - | "github-location" - | "new-directory-parent" - | "new-directory-name"; - -export type AddProjectMethod = "directory-search" | "browse" | "github" | "new-directory"; - -const METHOD_DESTINATIONS: Record, AddProjectFlowPage> = { - "directory-search": "directory-search", - github: "github-search", - "new-directory": "new-directory-parent", -}; +export type AddProjectTab = "existing" | "clone" | "new-folder"; export function addProjectFlow(page: Page): Locator { return page.getByTestId("add-project-flow"); } +/** The current tab's search or name field. */ export function addProjectFlowInput(page: Page): Locator { return page.getByTestId("add-project-flow-input"); } -export function addProjectFlowBack(page: Page): Locator { - return page.getByTestId("add-project-flow-back"); +export function addProjectFlowTab(page: Page, tab: AddProjectTab): Locator { + return page.getByTestId(`add-project-flow-tab-${tab}`); } -export function addProjectFlowHost(page: Page, serverId: string): Locator { - return page.getByTestId(`add-project-flow-host-${serverId}`); +export function addProjectFlowSubmit(page: Page): Locator { + return page.getByTestId("add-project-flow-submit"); } -export function addProjectFlowMethod(page: Page, method: AddProjectMethod): Locator { - return page.getByTestId(`add-project-flow-method-${method}`); +export function addProjectFlowHostTrigger(page: Page): Locator { + return page.getByTestId("add-project-flow-host-trigger"); } -export async function expectAddProjectPage(page: Page, kind: AddProjectFlowPage): Promise { - const currentPage = page.getByTestId(`add-project-flow-page-${kind}`); - await expect(currentPage).toBeVisible({ timeout: 30_000 }); - return currentPage; +export async function expectAddProjectTab(page: Page, tab: AddProjectTab): Promise { + await expect(addProjectFlowTab(page, tab)).toHaveAttribute("aria-selected", "true", { + timeout: 30_000, + }); } -async function openAddProjectFlowSurface( - page: Page, - expectedPage: "host" | "method", -): Promise { +/** Opens Add project from the sidebar; it starts on Existing with the search focused. */ +export async function openAddProjectFlow(page: Page): Promise { await page.locator('[data-testid="sidebar-add-project"]:visible').click(); await expect(addProjectFlow(page)).toBeVisible({ timeout: 30_000 }); - await expectAddProjectPage(page, expectedPage); -} - -export async function openAddProjectFlow(page: Page): Promise { - await openAddProjectFlowSurface(page, "method"); -} - -export async function openAddProjectHostSelection(page: Page): Promise { - await openAddProjectFlowSurface(page, "host"); + await expectAddProjectTab(page, "existing"); await expect(addProjectFlowInput(page)).toBeFocused(); } -export async function chooseAddProjectMethod(page: Page, method: AddProjectMethod): Promise { - const option = addProjectFlowMethod(page, method); - await expect(option).toBeVisible(); - await option.click(); - if (method !== "browse") { - await expectAddProjectPage(page, METHOD_DESTINATIONS[method]); - } +export async function chooseAddProjectTab(page: Page, tab: AddProjectTab): Promise { + await addProjectFlowTab(page, tab).click(); + await expectAddProjectTab(page, tab); +} + +export async function chooseAddProjectHost(page: Page, serverId: string): Promise { + await addProjectFlowHostTrigger(page).click(); + await page.getByTestId(`add-project-flow-host-${serverId}`).click(); +} + +/** Types a parent directory into the Location picker and uses it as typed. */ +export async function chooseAddProjectLocation(page: Page, location: string): Promise { + await page.getByTestId("add-project-flow-location").click(); + await page.getByPlaceholder("Search folders or enter a path").last().fill(location); + await page.getByText("Use this folder", { exact: true }).click(); + await expect(page.getByTestId("add-project-flow-location")).toContainText( + path.basename(location), + ); } export async function expectNewWorkspaceForAddedProject( @@ -114,8 +102,10 @@ export async function expectAddProjectResultVisible(page: Page, text: string): P .toBe(true); } +/** Presses Enter on the focused Add host button, which the sheet's own Enter must not swallow. */ export async function chooseAddHostFromProjectFlow(page: Page): Promise { - await page.getByRole("button", { name: /Add host.*No connected hosts/ }).click(); + await addProjectFlow(page).getByRole("button", { name: "Add host", exact: true }).focus(); + await page.keyboard.press("Enter"); } export async function navigateAndDismissAddProject(page: Page): Promise { diff --git a/packages/app/e2e/support/helpers/onboarding.ts b/packages/app/e2e/support/helpers/onboarding.ts index 745563ac02..0b8d89021b 100644 --- a/packages/app/e2e/support/helpers/onboarding.ts +++ b/packages/app/e2e/support/helpers/onboarding.ts @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { expect, type Locator, type Page } from "@playwright/test"; import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client"; -import { addProjectFlow, addProjectFlowInput, chooseAddProjectMethod } from "./add-project-flow"; +import { addProjectFlow, addProjectFlowInput, expectAddProjectTab } from "./add-project-flow"; import { connectDaemonClient } from "./daemon-client-loader"; import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry"; import { startIsolatedHostDaemon, type IsolatedHostDaemonOptions } from "./isolated-host-daemon"; @@ -122,7 +122,7 @@ export async function skipSetup(page: Page): Promise { export async function addProjectFromSetup(page: Page, projectPath: string): Promise { await setupModal(page).getByRole("button", { name: "Add project", exact: true }).click(); await expect(addProjectFlow(page)).toBeVisible({ timeout: 30_000 }); - await chooseAddProjectMethod(page, "directory-search"); + await expectAddProjectTab(page, "existing"); await addProjectFlowInput(page).fill(projectPath); await page.keyboard.press("Enter"); await expect(addProjectFlow(page)).toHaveCount(0, { timeout: 30_000 }); diff --git a/packages/app/src/add-project-flow/clone-tab.tsx b/packages/app/src/add-project-flow/clone-tab.tsx new file mode 100644 index 0000000000..03563dfbca --- /dev/null +++ b/packages/app/src/add-project-flow/clone-tab.tsx @@ -0,0 +1,204 @@ +import { useMemo } from "react"; +import { View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { GitHubIcon } from "@/components/icons/github-icon"; +import { FormTextInput } from "@/components/ui/form-field"; +import { isWeb } from "@/constants/platform"; +import type { Theme } from "@/styles/theme"; +import { ICON_SIZE } from "@/styles/theme"; +import type { AddProjectActions } from "./use-add-project-actions"; +import type { AddProjectFlowState, AddProjectHost, GithubRepositoryChoice } from "./model"; +import { LocationField } from "./location-field"; +import { + buildManualGithubRepositoryChoices, + checkoutName, + joinDirectoryPath, + MANUAL_CHOICE_PREFIX, +} from "./options"; +import { ResultList, type ResultRow } from "./result-list"; +import { RESULTS_TEST_ID } from "./result-list-id"; +import { useGithubRepositorySearch } from "./searches"; +import { resolveActiveIndex, type AddProjectTabView } from "./tab-view"; + +const ThemedGitHubIcon = withUnistyles(GitHubIcon); +const mutedColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); +const githubIcon = ; + +/** + * The project the query names comes first: the search result that matches it exactly, or else + * the pasted URL or owner/repo as typed. + */ +function buildCloneChoices( + query: string, + found: GithubRepositoryChoice[], +): GithubRepositoryChoice[] { + const normalized = query.trim().toLowerCase(); + const isExact = (repository: GithubRepositoryChoice) => + repository.nameWithOwner.toLowerCase() === normalized || + repository.cloneUrl.toLowerCase() === normalized; + const exact = found.filter(isExact); + if (exact.length === 0) return [...buildManualGithubRepositoryChoices(query), ...found]; + return [...exact, ...found.filter((repository) => !isExact(repository))]; +} + +/** A choice built from the typed URL or owner/repo rather than from a search answer. */ +function isTypedChoice(choice: GithubRepositoryChoice | undefined): boolean { + return choice?.id.startsWith(MANUAL_CHOICE_PREFIX) === true; +} + +function cloneEmptyText(host: AddProjectHost, query: string): string { + if (!host.canSearchGithubRepositories) return "Paste a Git URL or owner/repo"; + return query.trim() ? "No matching projects" : "Search GitHub or paste a Git URL"; +} + +export interface CloneTabView extends AddProjectTabView { + location: string; + destination: string; +} + +const CLONE_UNAVAILABLE = "Update the host to clone projects"; + +export function useCloneTab(input: { + state: AddProjectFlowState; + host: AddProjectHost | null; + defaultLocation: string; + actions: AddProjectActions; +}): CloneTabView { + const { state, host, defaultLocation, actions } = input; + const { query } = state.clone; + const canClone = host?.canCloneGithubRepositories === true; + const search = useGithubRepositorySearch({ + hostId: state.hostId, + query, + enabled: state.tab === "clone" && canClone && host?.canSearchGithubRepositories === true, + }); + + const choices = useMemo( + () => (canClone ? buildCloneChoices(query, search.items) : []), + [canClone, query, search.items], + ); + const rows = useMemo( + () => + choices.map((repository) => ({ + id: repository.id, + title: repository.cloneProtocol + ? `${repository.nameWithOwner} via ${repository.cloneProtocol.toUpperCase()}` + : repository.nameWithOwner, + subtitle: repository.description, + icon: GitHubIcon, + testID: `add-project-flow-repository-${repository.id}`, + })), + [choices], + ); + // While the search for new text runs, the rows on screen answer the old text. None of them is + // picked until the new answer arrives or the user picks one, unless it is the typed URL. + const awaitingRows = + search.pending && state.clone.selectedId === null && !isTypedChoice(choices[0]); + const activeIndex = awaitingRows ? -1 : resolveActiveIndex(rows, state.clone.selectedId); + const repository = choices[activeIndex] ?? null; + const location = state.clone.location ?? defaultLocation; + const destination = repository + ? joinDirectoryPath(location, checkoutName(repository.nameWithOwner)) + : location; + + return useMemo(() => { + const unavailable = host && canClone ? null : CLONE_UNAVAILABLE; + let notice: AddProjectTabView["notice"] = null; + if (!host || unavailable) notice = { kind: "empty", text: CLONE_UNAVAILABLE }; + else if (search.error) notice = { kind: "error", text: search.error }; + else if (search.pending) notice = { kind: "pending", text: "Searching..." }; + else notice = { kind: "empty", text: cloneEmptyText(host, query) }; + return { + rows, + activeIndex, + notice, + unavailable, + location, + destination, + primary: { + label: "Clone project", + submit: repository ? () => actions.clone(repository, location) : null, + }, + }; + }, [ + actions, + activeIndex, + canClone, + destination, + host, + location, + query, + repository, + rows, + search.error, + search.pending, + ]); +} + +export function CloneTab({ + view, + query, + hostId, + recommendedPaths, + disabled, + autoFocus, + onQueryChange, + onSelectRow, + onLocationChange, +}: { + view: CloneTabView; + query: string; + hostId: string | null; + recommendedPaths: string[]; + disabled: boolean; + /** Focus the field on mount; only with a hardware keyboard, so touch keeps the list in view. */ + autoFocus: boolean; + onQueryChange: (query: string) => void; + onSelectRow: (index: number) => void; + onLocationChange: (location: string) => void; +}) { + const editable = !disabled && !view.unavailable; + return ( + + + + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + body: { + flex: 1, + minHeight: 0, + gap: theme.spacing[3], + }, +})); diff --git a/packages/app/src/add-project-flow/existing-tab.tsx b/packages/app/src/add-project-flow/existing-tab.tsx new file mode 100644 index 0000000000..80b324d8bc --- /dev/null +++ b/packages/app/src/add-project-flow/existing-tab.tsx @@ -0,0 +1,166 @@ +import { useMemo } from "react"; +import { View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { Folder, FolderOpen, Search } from "lucide-react-native"; +import { buildProjectPickerOptions } from "@/components/project-picker-options"; +import { Button } from "@/components/ui/button"; +import { FormTextInput } from "@/components/ui/form-field"; +import { isWeb } from "@/constants/platform"; +import { ICON_SIZE, type Theme } from "@/styles/theme"; +import { shortenPath } from "@/utils/shorten-path"; +import type { AddProjectActions } from "./use-add-project-actions"; +import type { AddProjectFlowState, AddProjectHost } from "./model"; +import { pathBaseName } from "./options"; +import { ResultList, type ResultRow } from "./result-list"; +import { RESULTS_TEST_ID } from "./result-list-id"; +import { useDirectorySearch } from "./searches"; +import { resolveActiveIndex, type AddProjectTabView } from "./tab-view"; + +const ThemedSearch = withUnistyles(Search); +const mutedColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); +const searchIcon = ; + +export function useExistingTab(input: { + state: AddProjectFlowState; + host: AddProjectHost | null; + recommendedPaths: string[]; + actions: AddProjectActions; +}): AddProjectTabView { + const { state, host, recommendedPaths, actions } = input; + const { query } = state.existing; + const canAddProject = host?.canAddProject === true; + const search = useDirectorySearch({ + hostId: state.hostId, + query, + // The host answers a blank query with nothing, so only search once there is text. + enabled: state.tab === "existing" && canAddProject && query.trim().length > 0, + }); + + const paths = useMemo( + () => + canAddProject + ? buildProjectPickerOptions({ recommendedPaths, serverPaths: search.items, query }) + : [], + [canAddProject, query, recommendedPaths, search.items], + ); + const rows = useMemo( + () => + paths.map((option) => { + const shortPath = shortenPath(option.path); + return { + id: option.path, + title: option.kind === "path" ? shortPath : pathBaseName(option.path), + subtitle: option.kind === "path" ? "Open this path" : shortPath, + icon: Folder, + testID: `add-project-flow-folder-${encodeURIComponent(option.path)}`, + }; + }), + [paths], + ); + // While the search for new text runs, the rows on screen answer the old text. None of them is + // picked until the new answer arrives or the user picks one, unless it is the typed path. + const awaitingRows = + search.pending && state.existing.selectedId === null && paths[0]?.kind !== "path"; + const activeIndex = awaitingRows ? -1 : resolveActiveIndex(rows, state.existing.selectedId); + const activePath = paths[activeIndex]?.path ?? null; + + return useMemo(() => { + const unavailable = canAddProject ? null : "Update the host to add projects"; + let notice: AddProjectTabView["notice"] = null; + if (unavailable) notice = { kind: "empty", text: unavailable }; + else if (search.error) notice = { kind: "error", text: search.error }; + else if (search.pending) notice = { kind: "pending", text: "Searching..." }; + else notice = { kind: "empty", text: query.trim() ? "No matching folders" : "No folders yet" }; + return { + rows, + activeIndex, + notice, + unavailable, + primary: { + label: "Open project", + submit: activePath ? () => actions.openFolder(activePath) : null, + }, + }; + }, [actions, activeIndex, activePath, canAddProject, query, rows, search.error, search.pending]); +} + +export function ExistingTab({ + view, + query, + canBrowse, + disabled, + autoFocus, + onQueryChange, + onSelectRow, + onBrowse, +}: { + view: AddProjectTabView; + query: string; + canBrowse: boolean; + disabled: boolean; + /** Focus the field on mount; only with a hardware keyboard, so touch keeps the list in view. */ + autoFocus: boolean; + onQueryChange: (query: string) => void; + onSelectRow: (index: number) => void; + onBrowse: () => void; +}) { + const editable = !disabled && !view.unavailable; + return ( + + + + + + {canBrowse ? ( + + ) : null} + + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + body: { + flex: 1, + minHeight: 0, + gap: theme.spacing[3], + }, + searchRow: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, + searchField: { + flex: 1, + minWidth: 0, + }, +})); diff --git a/packages/app/src/add-project-flow/focused-control.ts b/packages/app/src/add-project-flow/focused-control.ts new file mode 100644 index 0000000000..f09a2babac --- /dev/null +++ b/packages/app/src/add-project-flow/focused-control.ts @@ -0,0 +1,4 @@ +/** Native moves no focus to buttons from a hardware keyboard, so Enter always reaches the sheet. */ +export function focusedControlOwnsEnter(): boolean { + return false; +} diff --git a/packages/app/src/add-project-flow/focused-control.web.ts b/packages/app/src/add-project-flow/focused-control.web.ts new file mode 100644 index 0000000000..40e27af56c --- /dev/null +++ b/packages/app/src/add-project-flow/focused-control.web.ts @@ -0,0 +1,16 @@ +import { RESULTS_TEST_ID } from "./result-list-id"; + +const ACTIVATES_ON_ENTER = + 'button, a[href], [role="button"], [role="link"], [role="tab"], [role="combobox"], [role="menuitem"]'; + +/** + * Whether the focused element handles Enter itself, such as the Close button, a tab, or the + * Location field. Result rows are buttons too, but focusing a row picks it, so Enter on a row + * runs the primary action for that row. + */ +export function focusedControlOwnsEnter(): boolean { + const active = document.activeElement; + if (!(active instanceof HTMLElement)) return false; + if (active.closest(`[data-testid="${RESULTS_TEST_ID}"]`)) return false; + return active.matches(ACTIVATES_ON_ENTER); +} diff --git a/packages/app/src/add-project-flow/index.tsx b/packages/app/src/add-project-flow/index.tsx new file mode 100644 index 0000000000..cb83b12722 --- /dev/null +++ b/packages/app/src/add-project-flow/index.tsx @@ -0,0 +1,492 @@ +import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; +import { Text, View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { Folder, FolderPlus, Plus } from "lucide-react-native"; +import { AdaptiveModalSheet, type SheetKeyboard } from "@/components/adaptive-modal-sheet"; +import { HostStatusDot } from "@/components/host-status-dot"; +import { HostPicker } from "@/components/hosts/host-picker"; +import { GitHubIcon } from "@/components/icons/github-icon"; +import { Button } from "@/components/ui/button"; +import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { useAddHost } from "@/hosts/add-host"; +import { useHardwareKeyboardPresent, type KeyboardInputEvent } from "@/keyboard"; +import { Shortcut } from "@/components/ui/shortcut"; +import { FieldTrigger } from "@/screens/new-workspace/form/field-trigger"; +import { + useAddProjectFlowStore, + type AddProjectFlowRequest, +} from "@/stores/add-project-flow-store"; +import { useRecommendedProjectPaths } from "@/stores/session-store-hooks"; +import { formatShortcut } from "@/utils/format-shortcut"; +import { getShortcutOs } from "@/utils/shortcut-platform"; +import { CloneTab, useCloneTab } from "./clone-tab"; +import { ExistingTab, useExistingTab } from "./existing-tab"; +import { focusedControlOwnsEnter } from "./focused-control"; +import { + ADD_PROJECT_KEYS, + addProjectFailure, + applyAvailableAddProjectHosts, + currentAddProjectHost, + selectableAddProjectHosts, + isAddProjectSubmitting, + moveAddProjectActiveIndex, + openAddProjectFlow, + resolveAddProjectKey, + selectAddProjectHost, + selectAddProjectRow, + selectAddProjectTab, + setAddProjectLocation, + setAddProjectQuery, + setNewFolderName, + type AddProjectTab, +} from "./model"; +import { NewFolderTab, useNewFolderTab } from "./new-folder-tab"; +import { defaultProjectLocation } from "./options"; +import type { AddProjectTabView } from "./tab-view"; +import { useAddProjectActions } from "./use-add-project-actions"; +import { useAddProjectHosts } from "./use-add-project-hosts"; + +const SNAP_POINTS = ["90%"]; +// Tall enough for a search field, six result rows, and the location field, so switching tabs +// never resizes the card. +const DESKTOP_HEIGHT = 560; + +// Compact drops the segment icons so the three labels fit a phone's width. +const TABS: { + value: AddProjectTab; + label: string; + key: string; + icon: SegmentedControlOption["icon"]; +}[] = [ + { + value: "existing", + label: "Existing", + key: "1", + icon: ({ color, size }) => , + }, + { + value: "clone", + label: "Clone", + key: "2", + icon: ({ color, size }) => , + }, + { + value: "new-folder", + label: "New folder", + key: "3", + icon: ({ color, size }) => , + }, +]; + +/** `lockedTo` is the tab a running submission belongs to; the others are disabled until it ends. */ +function buildTabOptions( + isMac: boolean, + withIcons: boolean, + lockedTo: AddProjectTab | null, +): SegmentedControlOption[] { + const os = isMac ? "mac" : "non-mac"; + return TABS.map( + (tab): SegmentedControlOption => ({ + value: tab.value, + label: tab.label, + icon: withIcons ? tab.icon : undefined, + tooltip: formatShortcut(["mod", tab.key], os), + testID: `add-project-flow-tab-${tab.value}`, + disabled: lockedTo !== null && tab.value !== lockedTo, + }), + ); +} + +interface AddProjectFlowProps { + request: AddProjectFlowRequest; + onClose: () => void; +} + +/** + * Add project: one sheet with a tab per way to add one. The flow state lives in `./model`; this + * component wires it to the host, the searches, and the keys. + */ +export function AddProjectFlow({ request, onClose }: AddProjectFlowProps) { + const isCompact = useIsCompactFormFactor(); + const isMac = getShortcutOs() === "mac"; + const keyboardPresent = useHardwareKeyboardPresent(); + const availableHosts = useAddProjectHosts(); + const [state, setState] = useState(() => + openAddProjectFlow({ + hosts: availableHosts, + ...(request.preferredHostId ? { preferredHostId: request.preferredHostId } : {}), + }), + ); + useEffect(() => { + setState((current) => applyAvailableAddProjectHosts(current, availableHosts)); + }, [availableHosts]); + + const host = currentAddProjectHost(state); + const submitting = isAddProjectSubmitting(state); + const failure = addProjectFailure(state); + const recommendedPaths = useRecommendedProjectPaths(state.hostId); + const rememberedLocation = useAddProjectFlowStore((store) => + state.hostId ? store.lastLocationByHost[state.hostId] : undefined, + ); + const defaultLocation = defaultProjectLocation({ + remembered: rememberedLocation, + projectPaths: recommendedPaths, + }); + const actions = useAddProjectActions({ hostId: state.hostId, setState, onClose }); + + // An offline host keeps its drafts, but nothing submits until it is back or the user picks + // another host. Gated here, once, so the footer, Enter and the native Go key all agree. + const offline = host?.online === false; + const existing = blockSubmitWhen( + offline, + useExistingTab({ state, host, recommendedPaths, actions }), + ); + const clone = blockSubmitWhen(offline, useCloneTab({ state, host, defaultLocation, actions })); + const newFolder = blockSubmitWhen( + offline, + useNewFolderTab({ state, host, defaultLocation, actions }), + ); + const views: Record = { + existing, + clone, + "new-folder": newFolder, + }; + const view = views[state.tab]; + + const selectTab = useCallback( + (tab: AddProjectTab) => setState((current) => selectAddProjectTab(current, tab)), + [], + ); + const selectHost = useCallback( + (hostId: string) => setState((current) => selectAddProjectHost(current, hostId)), + [], + ); + const changeQuery = useCallback( + (query: string) => setState((current) => setAddProjectQuery(current, query)), + [], + ); + const changeLocation = useCallback( + (location: string) => setState((current) => setAddProjectLocation(current, location)), + [], + ); + const changeName = useCallback( + (name: string) => setState((current) => setNewFolderName(current, name)), + [], + ); + + // The key handler reads the latest view without re-registering the overlay on every keystroke. + const viewRef = useRef(view); + viewRef.current = view; + const hasHostRef = useRef(host !== null); + hasHostRef.current = host !== null; + /** Picks the row at `index` of the current tab's list, remembered by its id. */ + const selectRow = useCallback((index: number) => { + const row = viewRef.current.rows[index]; + if (row) setState((current) => selectAddProjectRow(current, row.id)); + }, []); + const keyboard = useMemo( + () => ({ + keys: ADD_PROJECT_KEYS, + onKeyDown: (event: KeyboardInputEvent) => { + // With no host there is nothing to switch to or submit; Enter belongs to Add host. + if (!hasHostRef.current) return false; + const command = resolveAddProjectKey(event, isMac); + if (!command) return false; + const current = viewRef.current; + if (command.kind === "tab") { + selectTab(command.tab); + return true; + } + if (command.kind === "move") { + if (current.rows.length === 0) return false; + selectRow( + moveAddProjectActiveIndex(current.activeIndex, current.rows.length, command.direction), + ); + return true; + } + if (!current.primary.submit || focusedControlOwnsEnter()) return false; + current.primary.submit(); + return true; + }, + }), + [isMac, selectRow, selectTab], + ); + + const lockedTab = submitting ? state.tab : null; + const tabOptions = useMemo( + () => buildTabOptions(isMac, !isCompact, lockedTab), + [isCompact, isMac, lockedTab], + ); + const selectableHosts = useMemo(() => selectableAddProjectHosts(state), [state]); + const header = useMemo( + () => ({ + title: "Add project", + titleTestID: "add-project-flow-title", + actions: + selectableHosts.length > 1 && state.hostId ? ( + + ) : undefined, + }), + [selectHost, selectableHosts, state.hostId, submitting], + ); + + // On a pointer layout the failure sits left of the button; compact stacks it above a + // full-width button. + const problem = failure ?? (offline && host ? `${host.label} is offline` : null); + const failureLine = problem ? ( + + {problem} + + ) : null; + const footer = host ? ( + <> + {failureLine ?? (isCompact ? null : 0} />)} + + + ) : null; + + let body: ReactNode; + if (!host) { + body = ; + } else if (state.tab === "existing") { + body = ( + + ); + } else if (state.tab === "clone") { + body = ( + + ); + } else { + body = ( + + ); + } + + return ( + + {host ? ( + + ) : null} + {/* Keyed by tab so each tab's input mounts with its own draft and takes focus. */} + + {body} + + + ); +} + +function blockSubmitWhen( + blocked: boolean, + view: TabView, +): TabView { + return blocked ? { ...view, primary: { ...view.primary, submit: null } } : view; +} + +function hostOptionTestID(serverId: string): string { + return `add-project-flow-host-${serverId}`; +} + +function HostPill({ + hosts, + hostId, + onSelect, + disabled, +}: { + hosts: { serverId: string; label: string }[]; + hostId: string; + onSelect: (hostId: string) => void; + disabled: boolean; +}) { + const anchorRef = useRef(null); + const [open, setOpen] = useState(false); + const openPicker = useCallback(() => setOpen(true), []); + const label = hosts.find((host) => host.serverId === hostId)?.label ?? hostId; + const icon = useMemo(() => , [hostId]); + return ( + + + + ); +} + +const MOVE_KEYS = ["↑↓"]; +const TAB_KEYS = ["mod", "1–3"]; + +/** The keys that are not on any control: list movement and tab switching. */ +function KeyHints({ canMove }: { canMove: boolean }) { + const keyboardPresent = useHardwareKeyboardPresent(); + if (!keyboardPresent) return ; + return ( + + {canMove ? ( + + + Move + + ) : null} + + + Switch + + + ); +} + +function NoHosts({ onClose }: { onClose: () => void }) { + const addHost = useAddHost(); + const handleAddHost = useCallback(() => { + // The project sheet must release its window before the add-host sheet opens. + onClose(); + addHost(); + }, [addHost, onClose]); + return ( + + No connected hosts + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + content: { + flex: 1, + minHeight: 0, + }, + tabBody: { + flex: 1, + minHeight: 0, + }, + footerContainerCompact: { + flexDirection: "column", + alignItems: "stretch", + }, + // The message wraps beside the button; the button keeps its width. + failure: { + flexShrink: 1, + minWidth: 0, + color: theme.colors.statusDanger, + fontSize: theme.fontSize.sm, + }, + hints: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[4], + }, + hint: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[1.5], + }, + hintText: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + }, + primary: { + flexShrink: 0, + }, + primaryCompact: { + flexShrink: 0, + alignSelf: "stretch", + }, + noHosts: { + flex: 1, + alignItems: "center", + justifyContent: "center", + gap: theme.spacing[3], + }, + noHostsText: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.base, + }, +})); diff --git a/packages/app/src/add-project-flow/location-field.tsx b/packages/app/src/add-project-flow/location-field.tsx new file mode 100644 index 0000000000..c6eb65efaf --- /dev/null +++ b/packages/app/src/add-project-flow/location-field.tsx @@ -0,0 +1,109 @@ +import { useCallback, useMemo, useRef, useState } from "react"; +import type { View } from "react-native"; +import { withUnistyles } from "react-native-unistyles"; +import { HardDrive } from "lucide-react-native"; +import { buildProjectPickerOptions } from "@/components/project-picker-options"; +import { Combobox, type ComboboxOption } from "@/components/ui/combobox"; +import { FieldTrigger } from "@/screens/new-workspace/form/field-trigger"; +import { ICON_SIZE, type Theme } from "@/styles/theme"; +import { shortenPath } from "@/utils/shorten-path"; +import { buildSuggestedParentDirectories } from "./options"; +import { useDirectorySearch } from "./searches"; + +const ThemedHardDrive = withUnistyles(HardDrive); +const mutedColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); +const locationIcon = ; + +interface LocationFieldProps { + hostId: string | null; + /** The parent directory the project goes into. */ + location: string; + /** Where the project ends up, shown on the field so the user rarely needs to open it. */ + destination: string; + recommendedPaths: string[]; + onChange: (location: string) => void; + disabled: boolean; + testID: string; +} + +/** Picks the parent directory for a new project: recent parents, a folder search, or a typed path. */ +export function LocationField({ + hostId, + location, + destination, + recommendedPaths, + onChange, + disabled, + testID, +}: LocationFieldProps) { + const anchorRef = useRef(null); + const [open, setOpen] = useState(false); + const [query, setQuery] = useState(""); + const search = useDirectorySearch({ hostId, query, enabled: open && query.trim().length > 0 }); + + // The same builder as the Existing tab: a typed path first, then matching suggestions and + // folders the host found. + const pickerOptions = useMemo(() => { + const suggestions = [ + location, + ...buildSuggestedParentDirectories(recommendedPaths).filter((path) => path !== location), + ]; + return buildProjectPickerOptions({ + recommendedPaths: suggestions, + serverPaths: search.items, + query, + }); + }, [location, query, recommendedPaths, search.items]); + const options = useMemo( + () => + pickerOptions.map( + (option): ComboboxOption => ({ + id: option.path, + label: shortenPath(option.path), + description: option.kind === "path" ? "Use this folder" : undefined, + kind: "directory", + }), + ), + [pickerOptions], + ); + // Like the Existing tab: while a new search runs, only a typed path is picked for Enter. + const awaitingOptions = search.pending && pickerOptions[0]?.kind !== "path"; + + const handleOpen = useCallback(() => setOpen(true), []); + const handleOpenChange = useCallback((next: boolean) => { + setOpen(next); + if (!next) setQuery(""); + }, []); + + return ( + <> + + + + ); +} diff --git a/packages/app/src/add-project-flow/model.test.ts b/packages/app/src/add-project-flow/model.test.ts index 63014a3663..7689a609cd 100644 --- a/packages/app/src/add-project-flow/model.test.ts +++ b/packages/app/src/add-project-flow/model.test.ts @@ -1,153 +1,194 @@ import { describe, expect, it } from "vitest"; import { - backAddProjectPage, - chooseAddProjectHost, - currentAddProjectPage, + applyAvailableAddProjectHosts, + selectableAddProjectHosts, + failAddProjectSubmission, moveAddProjectActiveIndex, - moveAddProjectSelection, openAddProjectFlow, - openDirectorySearchPage, - openGithubLocationPage, - openNewDirectoryNamePage, - openNewDirectoryParentPage, - setAddProjectActiveIndex, - setAddProjectPageInput, - setNewDirectoryName, + resolveAddProjectKey, + selectAddProjectHost, + selectAddProjectRow, + selectAddProjectTab, + setAddProjectLocation, + setAddProjectQuery, + setNewFolderName, + startAddProjectSubmission, type AddProjectHost, } from "./model"; import { - addProjectMethodEmptyText, - buildAddProjectMethods, - buildCloneLocationOptions, buildManualGithubRepositoryChoices, + checkoutName, + defaultProjectLocation, + joinDirectoryPath, + parentDirectory, + validateNewFolderName, } from "./options"; +import { resolveActiveIndex } from "./tab-view"; const HOST: AddProjectHost = { serverId: "host-1", label: "Local", + online: true, canAddProject: true, canBrowse: true, canCloneGithubRepositories: true, canSearchGithubRepositories: true, canCreateDirectory: true, }; +const REMOTE: AddProjectHost = { ...HOST, serverId: "host-2", label: "Remote", canBrowse: false }; +const REMOTE_OFFLINE: AddProjectHost = { ...REMOTE, online: false }; -describe("Add Project navigation", () => { - it("skips a single connected host without adding it to history", () => { - const state = openAddProjectFlow({ hosts: [HOST] }); +const KEY = { key: "", ctrlKey: false, metaKey: false, altKey: false, shiftKey: false }; - expect(currentAddProjectPage(state)).toEqual({ - kind: "method", - hostId: "host-1", - activeIndex: 0, - error: null, - isSubmitting: false, - }); - expect(backAddProjectPage(state)).toBeNull(); +describe("Add Project flow", () => { + it("opens on the Existing tab of the preferred host", () => { + const state = openAddProjectFlow({ hosts: [HOST, REMOTE], preferredHostId: "host-2" }); + + expect(state.tab).toBe("existing"); + expect(state.hostId).toBe("host-2"); }); - it("restores page input and selection after Back", () => { - const secondHost = { ...HOST, serverId: "host-2", label: "Remote" }; - let state = openAddProjectFlow({ hosts: [HOST, secondHost] }); - state = setAddProjectPageInput(state, "rem"); - state = setAddProjectActiveIndex(state, 1); - state = chooseAddProjectHost(state, secondHost.serverId); - state = openDirectorySearchPage(state, secondHost.serverId); - - state = backAddProjectPage(state) ?? state; - state = backAddProjectPage(state) ?? state; - - expect(currentAddProjectPage(state)).toEqual({ - kind: "host", - query: "rem", - activeIndex: 1, - error: null, - }); + it("falls back to the first host, and to no host when none is connected", () => { + expect(openAddProjectFlow({ hosts: [HOST, REMOTE] }).hostId).toBe("host-1"); + expect(openAddProjectFlow({ hosts: [] }).hostId).toBeNull(); }); - it("wraps keyboard selection in both directions", () => { + it("keeps each tab's input when switching tabs", () => { + let state = openAddProjectFlow({ hosts: [HOST] }); + state = setAddProjectQuery(state, "paseo"); + state = selectAddProjectTab(state, "clone"); + state = setAddProjectQuery(state, "getpaseo/"); + state = selectAddProjectTab(state, "new-folder"); + state = setNewFolderName(state, "acme-api"); + state = selectAddProjectTab(state, "existing"); + + expect(state.existing.query).toBe("paseo"); + expect(state.clone.query).toBe("getpaseo/"); + expect(state.newFolder.name).toBe("acme-api"); + }); + + it("switching host keeps typed input but drops host-specific locations and selection", () => { + let state = openAddProjectFlow({ hosts: [HOST, REMOTE] }); + state = setAddProjectQuery(state, "paseo"); + state = selectAddProjectRow(state, "/code/paseo"); + state = selectAddProjectTab(state, "new-folder"); + state = setNewFolderName(state, "acme-api"); + state = setAddProjectLocation(state, "~/work"); + + state = selectAddProjectHost(state, "host-2"); + + expect(state.hostId).toBe("host-2"); + expect(state.existing).toEqual({ query: "paseo", selectedId: null }); + expect(state.newFolder).toEqual({ name: "acme-api", location: null }); + }); + + it("locks tab and host while a submission runs, and unlocks with the failure", () => { + let state = openAddProjectFlow({ hosts: [HOST, REMOTE] }); + state = selectAddProjectTab(state, "clone"); + state = startAddProjectSubmission(state); + + expect(selectAddProjectTab(state, "existing").tab).toBe("clone"); + expect(selectAddProjectHost(state, "host-2").hostId).toBe("host-1"); + expect(selectAddProjectRow(state, "acme/app")).toBe(state); + expect(startAddProjectSubmission(state)).toBe(state); + + state = failAddProjectSubmission(state, "Unable to clone project"); + expect(state.submission).toEqual({ + status: "failed", + tab: "clone", + message: "Unable to clone project", + }); + expect(selectAddProjectTab(state, "existing").submission).toEqual({ status: "idle" }); + }); + + it("clears a failure once the user edits the input or picks another row", () => { + let state = openAddProjectFlow({ hosts: [HOST] }); + state = startAddProjectSubmission(state); + state = failAddProjectSubmission(state, "Directory not found"); + + expect(setAddProjectQuery(state, "~/dev").submission).toEqual({ status: "idle" }); + expect(selectAddProjectRow(state, "/code/app").submission).toEqual({ status: "idle" }); + }); + + it("keeps the chosen host and its draft while it is offline, never moving them to another host", () => { + let state = openAddProjectFlow({ hosts: [HOST, REMOTE] }); + state = selectAddProjectHost(state, "host-2"); + state = setAddProjectQuery(state, "/srv/app"); + + const offline = applyAvailableAddProjectHosts(state, [HOST, REMOTE_OFFLINE]); + expect(offline.hostId).toBe("host-2"); + expect(offline.existing.query).toBe("/srv/app"); + expect(selectableAddProjectHosts(offline).map((host) => host.serverId)).toEqual([ + "host-1", + "host-2", + ]); + + const back = applyAvailableAddProjectHosts(offline, [HOST, REMOTE]); + expect(back.hostId).toBe("host-2"); + expect(back.existing.query).toBe("/srv/app"); + expect(selectAddProjectHost(offline, "host-1").hostId).toBe("host-1"); + }); + + it("picks only an online host, and another one when the chosen host is removed", () => { + expect(openAddProjectFlow({ hosts: [REMOTE_OFFLINE, HOST] }).hostId).toBe("host-1"); + expect( + openAddProjectFlow({ hosts: [REMOTE_OFFLINE, HOST], preferredHostId: "host-2" }).hostId, + ).toBe("host-1"); + expect(openAddProjectFlow({ hosts: [REMOTE_OFFLINE] }).hostId).toBeNull(); + expect( + selectAddProjectHost(openAddProjectFlow({ hosts: [HOST, REMOTE_OFFLINE] }), "host-2").hostId, + ).toBe("host-1"); + + const state = selectAddProjectHost(openAddProjectFlow({ hosts: [HOST, REMOTE] }), "host-2"); + expect(applyAvailableAddProjectHosts(state, [HOST]).hostId).toBe("host-1"); + expect(applyAvailableAddProjectHosts(openAddProjectFlow({ hosts: [] }), [REMOTE]).hostId).toBe( + "host-2", + ); + }); + + it("keeps the user's pick across a reorder and never swaps a dropped pick for another row", () => { + const rows = [{ id: "/code/beta" }, { id: "/code/alpha" }]; + expect(resolveActiveIndex(rows, "/code/alpha")).toBe(1); + expect(resolveActiveIndex(rows, null)).toBe(0); + expect(resolveActiveIndex(rows, "/code/gone")).toBe(-1); + expect(resolveActiveIndex([], null)).toBe(-1); + }); + + it("wraps keyboard selection at both ends", () => { expect(moveAddProjectActiveIndex(2, 3, "next")).toBe(0); expect(moveAddProjectActiveIndex(0, 3, "previous")).toBe(2); - expect(moveAddProjectSelection(0, [true, false, true], "next")).toBe(2); + }); +}); + +describe("Add Project keys", () => { + it("maps Mod+1/2/3 to tabs using the platform's modifier", () => { + expect(resolveAddProjectKey({ ...KEY, key: "2", metaKey: true }, true)).toEqual({ + kind: "tab", + tab: "clone", + }); + expect(resolveAddProjectKey({ ...KEY, key: "3", ctrlKey: true }, false)).toEqual({ + kind: "tab", + tab: "new-folder", + }); + expect(resolveAddProjectKey({ ...KEY, key: "1", ctrlKey: true }, true)).toBeNull(); + expect(resolveAddProjectKey({ ...KEY, key: "1" }, true)).toBeNull(); }); - it("restores a directory name after returning to and reselecting its parent", () => { - let state = openAddProjectFlow({ hosts: [HOST] }); - state = openNewDirectoryParentPage(state, HOST.serverId); - state = openNewDirectoryNamePage(state, HOST.serverId, "~/dev"); - state = setNewDirectoryName(state, "command-center"); - state = backAddProjectPage(state) ?? state; - state = openNewDirectoryNamePage(state, HOST.serverId, "~/dev"); - - expect(currentAddProjectPage(state)).toMatchObject({ - kind: "new-directory-name", - parentPath: "~/dev", - name: "command-center", + it("maps arrows and Enter to list commands", () => { + expect(resolveAddProjectKey({ ...KEY, key: "ArrowDown" }, true)).toEqual({ + kind: "move", + direction: "next", }); - }); - - it("restores the GitHub destination query and active parent when reopening a repository", () => { - const repository = { - id: "repo-1", - nameWithOwner: "getpaseo/paseo", - cloneUrl: "git@github.com:getpaseo/paseo.git", - description: null, - visibility: "public", - updatedAt: null, - }; - let state = openAddProjectFlow({ hosts: [HOST] }); - state = openGithubLocationPage(state, HOST.serverId, repository); - state = setAddProjectPageInput(state, "~/dev"); - state = setAddProjectActiveIndex(state, 2); - state = backAddProjectPage(state) ?? state; - state = openGithubLocationPage(state, HOST.serverId, repository); - - expect(currentAddProjectPage(state)).toMatchObject({ - kind: "github-location", - query: "~/dev", - activeIndex: 2, + expect(resolveAddProjectKey({ ...KEY, key: "ArrowUp" }, true)).toEqual({ + kind: "move", + direction: "previous", }); + expect(resolveAddProjectKey({ ...KEY, key: "Enter" }, true)).toEqual({ kind: "submit" }); + expect(resolveAddProjectKey({ ...KEY, key: "Enter", shiftKey: true }, true)).toBeNull(); }); }); describe("Add Project options", () => { - it("hides every mutating method when the host lacks stable project identity", () => { - const outdatedHost = { ...HOST, canAddProject: false }; - - expect(buildAddProjectMethods(outdatedHost)).toEqual([]); - expect(addProjectMethodEmptyText(outdatedHost)).toBe("Update the host to use Add Project."); - }); - - it("keeps host-upgrade methods discoverable while hiding local-only Browse", () => { - expect( - buildAddProjectMethods({ - ...HOST, - canBrowse: false, - canCloneGithubRepositories: false, - canSearchGithubRepositories: false, - canCreateDirectory: false, - }), - ).toEqual([ - { - id: "directory-search", - label: "Search for directory", - description: "Find a directory on Local", - }, - { - id: "github", - label: "Clone from GitHub", - description: "Update this host to clone GitHub repositories", - disabled: true, - }, - { - id: "new-directory", - label: "New directory", - description: "Update this host to create directories", - disabled: true, - }, - ]); - }); - it("offers manual URL and protocol-specific owner/repo clone choices", () => { expect(buildManualGithubRepositoryChoices("git@github.com:getpaseo/paseo.git")).toEqual([ expect.objectContaining({ @@ -163,46 +204,42 @@ describe("Add Project options", () => { expect(buildManualGithubRepositoryChoices("paseo")).toEqual([]); }); - it("shows final clone paths while retaining parent paths as values", () => { - expect( - buildCloneLocationOptions({ - parents: ["~/dev", "~/workspace"], - repositoryName: "paseo", - existingPaths: ["~/workspace/paseo"], - }), - ).toEqual([ - { - id: "~/dev", - path: "~/dev", - displayPath: "~/dev/paseo", - secondaryText: "Parent directory: ~/dev", - disabled: false, - }, - { - id: "~/workspace", - path: "~/workspace", - displayPath: "~/workspace/paseo", - secondaryText: "Already exists", - disabled: true, - }, - ]); + it("defaults the location to a folder that exists", () => { + expect(defaultProjectLocation({ remembered: undefined, projectPaths: [] })).toBe("~"); + expect(defaultProjectLocation({ remembered: undefined, projectPaths: ["/code/app"] })).toBe( + "/code", + ); + expect(defaultProjectLocation({ remembered: "~/work", projectPaths: ["/code/app"] })).toBe( + "~/work", + ); }); - it("shows equivalent absolute-home and tilde destinations only once", () => { - expect( - buildCloneLocationOptions({ - parents: ["/Users/moboudra/dev", "~/dev"], - repositoryName: "dotfiles", - existingPaths: [], - }), - ).toEqual([ - { - id: "/Users/moboudra/dev", - path: "/Users/moboudra/dev", - displayPath: "/Users/moboudra/dev/dotfiles", - secondaryText: "Parent directory: /Users/moboudra/dev", - disabled: false, - }, - ]); + it("keeps a drive or filesystem root when deriving and joining a location", () => { + expect(parentDirectory("C:\\repo")).toBe("C:\\"); + expect(parentDirectory("/repo")).toBe("/"); + expect(parentDirectory("\\\\nas\\work")).toBeNull(); + expect(parentDirectory("\\\\nas\\work\\app")).toBe("\\\\nas\\work"); + expect(defaultProjectLocation({ remembered: undefined, projectPaths: ["\\\\nas\\work"] })).toBe( + "~", + ); + expect(parentDirectory("/code/app")).toBe("/code"); + expect(joinDirectoryPath("C:\\", "new-project")).toBe("C:\\new-project"); + expect(joinDirectoryPath("/", "new-project")).toBe("/new-project"); + expect(defaultProjectLocation({ remembered: undefined, projectPaths: ["C:\\repo"] })).toBe( + "C:\\", + ); + }); + + it("names the checkout the way the host does", () => { + expect(checkoutName("acme/app.git")).toBe("app"); + expect(checkoutName("acme/app")).toBe("app"); + }); + + it("rejects folder names that are empty or leave the location", () => { + expect(validateNewFolderName("")).toBe("Enter a folder name"); + expect(validateNewFolderName("..")).toBe("Enter a folder name"); + expect(validateNewFolderName("../invalid")).toBe("Use a name without slashes"); + expect(validateNewFolderName("C:repo")).toBe("Use a name without a drive letter"); + expect(validateNewFolderName(" acme-api ")).toBeNull(); }); }); diff --git a/packages/app/src/add-project-flow/model.ts b/packages/app/src/add-project-flow/model.ts index 0de21d1520..c7e28da789 100644 --- a/packages/app/src/add-project-flow/model.ts +++ b/packages/app/src/add-project-flow/model.ts @@ -1,6 +1,7 @@ export interface AddProjectHost { serverId: string; label: string; + online: boolean; canAddProject: boolean; canBrowse: boolean; canCloneGithubRepositories: boolean; @@ -17,42 +18,42 @@ export interface GithubRepositoryChoice { updatedAt: string | null; } -interface PageState { - activeIndex: number; - error: string | null; -} +/** The three ways to add a project, in the order the segmented control and Mod+1/2/3 walk them. */ +export const ADD_PROJECT_TABS = ["existing", "clone", "new-folder"] as const; +export type AddProjectTab = (typeof ADD_PROJECT_TABS)[number]; -interface SearchPageState extends PageState { +interface ListDraft { query: string; + /** + * The row the user picked, by id, so it stays picked when a search refresh reorders the rows. + * `null`, or an id no longer listed, means the first row. + */ + selectedId: string | null; } -export type AddProjectPage = - | ({ kind: "host" } & SearchPageState) - | ({ kind: "method"; hostId: string; isSubmitting: boolean } & PageState) - | ({ kind: "directory-search"; hostId: string; isSubmitting: boolean } & SearchPageState) - | ({ kind: "github-search"; hostId: string } & SearchPageState) - | ({ - kind: "github-location"; - hostId: string; - repository: GithubRepositoryChoice; - isSubmitting: boolean; - } & SearchPageState) - | ({ kind: "new-directory-parent"; hostId: string } & SearchPageState) - | { - kind: "new-directory-name"; - hostId: string; - parentPath: string; - name: string; - activeIndex: number; - error: string | null; - isSubmitting: boolean; - }; +/** `location: null` means the default parent directory for the current host. */ +interface CloneDraft extends ListDraft { + location: string | null; +} + +interface NewFolderDraft { + name: string; + location: string | null; +} + +export type AddProjectSubmission = + | { status: "idle" } + | { status: "submitting"; tab: AddProjectTab } + | { status: "failed"; tab: AddProjectTab; message: string }; export interface AddProjectFlowState { hosts: AddProjectHost[]; - pages: AddProjectPage[]; - newDirectoryNameDrafts: Record; - githubLocationDrafts: Record; + hostId: string | null; + tab: AddProjectTab; + existing: ListDraft; + clone: CloneDraft; + newFolder: NewFolderDraft; + submission: AddProjectSubmission; } export interface OpenAddProjectFlowInput { @@ -60,214 +61,144 @@ export interface OpenAddProjectFlowInput { preferredHostId?: string; } -type SearchPageKind = Extract["kind"]; +const IDLE: AddProjectSubmission = { status: "idle" }; -function searchPage(kind: TKind) { - return { kind, query: "", activeIndex: 0, error: null } as const; -} - -function methodPage(hostId: string): AddProjectPage { - return { kind: "method", hostId, activeIndex: 0, error: null, isSubmitting: false }; +function pickHostId(hosts: AddProjectHost[], preferredHostId?: string | null): string | null { + const online = hosts.filter((host) => host.online); + const preferred = preferredHostId + ? online.find((host) => host.serverId === preferredHostId) + : undefined; + return (preferred ?? online[0])?.serverId ?? null; } export function openAddProjectFlow(input: OpenAddProjectFlowInput): AddProjectFlowState { - const preferredHost = input.preferredHostId - ? input.hosts.find((host) => host.serverId === input.preferredHostId) - : null; - const onlyHost = input.hosts.length === 1 ? input.hosts[0] : null; - const initialHost = preferredHost ?? onlyHost; - return { hosts: input.hosts, - pages: initialHost ? [methodPage(initialHost.serverId)] : [searchPage("host")], - newDirectoryNameDrafts: {}, - githubLocationDrafts: {}, + hostId: pickHostId(input.hosts, input.preferredHostId), + tab: "existing", + existing: { query: "", selectedId: null }, + clone: { query: "", selectedId: null, location: null }, + newFolder: { name: "", location: null }, + submission: IDLE, }; } +export function currentAddProjectHost(state: AddProjectFlowState): AddProjectHost | null { + return state.hosts.find((host) => host.serverId === state.hostId) ?? null; +} + +export function isAddProjectSubmitting(state: AddProjectFlowState): boolean { + return state.submission.status === "submitting"; +} + +/** The failure to show on the current tab, if the last submission there failed. */ +export function addProjectFailure(state: AddProjectFlowState): string | null { + const { submission } = state; + return submission.status === "failed" && submission.tab === state.tab ? submission.message : null; +} + +/** The hosts the user can switch to: every online host, plus the current one even while offline. */ +export function selectableAddProjectHosts(state: AddProjectFlowState): AddProjectHost[] { + return state.hosts.filter((host) => host.online || host.serverId === state.hostId); +} + +/** + * The chosen host stays chosen while it is offline, with its drafts, so a disconnect never sends + * them to another host. A host is picked only when none is chosen or the chosen one was removed. + */ export function applyAvailableAddProjectHosts( state: AddProjectFlowState, hosts: AddProjectHost[], - preferredHostId?: string, ): AddProjectFlowState { - const current = currentAddProjectPage(state); - if (state.pages.length !== 1 || current.kind !== "host") { - return { ...state, hosts }; - } - const preferredHost = preferredHostId - ? hosts.find((host) => host.serverId === preferredHostId) - : null; - const onlyHost = hosts.length === 1 ? hosts[0] : null; - const initialHost = preferredHost ?? onlyHost; + const stillListed = hosts.some((host) => host.serverId === state.hostId); + if (stillListed) return { ...state, hosts }; + return withHost({ ...state, hosts }, pickHostId(hosts)); +} + +function withHost(state: AddProjectFlowState, hostId: string | null): AddProjectFlowState { return { ...state, - hosts, - pages: initialHost ? [methodPage(initialHost.serverId)] : state.pages, + hostId, + existing: { ...state.existing, selectedId: null }, + clone: { ...state.clone, selectedId: null, location: null }, + newFolder: { ...state.newFolder, location: null }, + submission: IDLE, }; } -export function currentAddProjectPage(state: AddProjectFlowState): AddProjectPage { - const page = state.pages[state.pages.length - 1]; - if (!page) { - throw new Error("Add Project flow must always contain a page"); +export function selectAddProjectHost( + state: AddProjectFlowState, + hostId: string, +): AddProjectFlowState { + if (isAddProjectSubmitting(state) || hostId === state.hostId) return state; + if (!state.hosts.some((host) => host.serverId === hostId && host.online)) return state; + return withHost(state, hostId); +} + +export function selectAddProjectTab( + state: AddProjectFlowState, + tab: AddProjectTab, +): AddProjectFlowState { + if (isAddProjectSubmitting(state) || tab === state.tab) return state; + return { ...state, tab, submission: IDLE }; +} + +/** Sets the search text of the current list tab. */ +export function setAddProjectQuery(state: AddProjectFlowState, query: string): AddProjectFlowState { + if (state.tab === "existing") { + return { ...state, existing: { query, selectedId: null }, submission: IDLE }; } - return page; -} - -export function updateCurrentAddProjectPage( - state: AddProjectFlowState, - update: (page: AddProjectPage) => AddProjectPage, -): AddProjectFlowState { - const index = state.pages.length - 1; - return { - ...state, - pages: state.pages.map((page, pageIndex) => (pageIndex === index ? update(page) : page)), - }; -} - -export function pushAddProjectPage( - state: AddProjectFlowState, - page: AddProjectPage, -): AddProjectFlowState { - return { ...state, pages: [...state.pages, page] }; -} - -export function backAddProjectPage(state: AddProjectFlowState): AddProjectFlowState | null { - if (state.pages.length === 1) { - return null; + if (state.tab === "clone") { + return { ...state, clone: { ...state.clone, query, selectedId: null }, submission: IDLE }; } - return { ...state, pages: state.pages.slice(0, -1) }; + return state; } -export function chooseAddProjectHost( +export function setNewFolderName(state: AddProjectFlowState, name: string): AddProjectFlowState { + return { ...state, newFolder: { ...state.newFolder, name }, submission: IDLE }; +} + +/** Sets the parent directory of the current tab that creates a folder. */ +export function setAddProjectLocation( state: AddProjectFlowState, - hostId: string, + location: string, ): AddProjectFlowState { - return pushAddProjectPage(state, methodPage(hostId)); + if (state.tab === "clone") { + return { ...state, clone: { ...state.clone, location }, submission: IDLE }; + } + if (state.tab === "new-folder") { + return { ...state, newFolder: { ...state.newFolder, location }, submission: IDLE }; + } + return state; } -export function openDirectorySearchPage( +export function selectAddProjectRow( state: AddProjectFlowState, - hostId: string, + selectedId: string, ): AddProjectFlowState { - return pushAddProjectPage(state, { - ...searchPage("directory-search"), - hostId, - isSubmitting: false, - }); + // The row being added stays put until its submission ends; choosing another clears the + // failure of the last one. + if (isAddProjectSubmitting(state)) return state; + if (state.tab === "existing") { + return { ...state, existing: { ...state.existing, selectedId }, submission: IDLE }; + } + if (state.tab === "clone") { + return { ...state, clone: { ...state.clone, selectedId }, submission: IDLE }; + } + return state; } -export function openGithubSearchPage( +export function startAddProjectSubmission(state: AddProjectFlowState): AddProjectFlowState { + if (isAddProjectSubmitting(state)) return state; + return { ...state, submission: { status: "submitting", tab: state.tab } }; +} + +export function failAddProjectSubmission( state: AddProjectFlowState, - hostId: string, + message: string, ): AddProjectFlowState { - return pushAddProjectPage(state, { ...searchPage("github-search"), hostId }); -} - -export function openGithubLocationPage( - state: AddProjectFlowState, - hostId: string, - repository: GithubRepositoryChoice, -): AddProjectFlowState { - const draft = state.githubLocationDrafts[githubLocationDraftKey(hostId, repository.id)]; - return pushAddProjectPage(state, { - kind: "github-location", - query: draft?.query ?? "", - activeIndex: draft?.activeIndex ?? 0, - error: null, - hostId, - repository, - isSubmitting: false, - }); -} - -export function openNewDirectoryParentPage( - state: AddProjectFlowState, - hostId: string, -): AddProjectFlowState { - return pushAddProjectPage(state, { ...searchPage("new-directory-parent"), hostId }); -} - -export function openNewDirectoryNamePage( - state: AddProjectFlowState, - hostId: string, - parentPath: string, -): AddProjectFlowState { - const draftKey = newDirectoryDraftKey(hostId, parentPath); - return pushAddProjectPage(state, { - kind: "new-directory-name", - hostId, - parentPath, - name: state.newDirectoryNameDrafts[draftKey] ?? "", - activeIndex: 0, - error: null, - isSubmitting: false, - }); -} - -export function setAddProjectPageInput( - state: AddProjectFlowState, - value: string, -): AddProjectFlowState { - const page = currentAddProjectPage(state); - const updated = updateCurrentAddProjectPage(state, (current) => { - if (current.kind === "new-directory-name") { - return { ...current, name: value, activeIndex: 0, error: null }; - } - if (current.kind === "method") return current; - return { ...current, query: value, activeIndex: 0, error: null }; - }); - if (page.kind !== "github-location") return updated; - const draftKey = githubLocationDraftKey(page.hostId, page.repository.id); - return { - ...updated, - githubLocationDrafts: { - ...updated.githubLocationDrafts, - [draftKey]: { query: value, activeIndex: 0 }, - }, - }; -} - -export function setNewDirectoryName( - state: AddProjectFlowState, - value: string, -): AddProjectFlowState { - const page = currentAddProjectPage(state); - if (page.kind !== "new-directory-name") return state; - const draftKey = newDirectoryDraftKey(page.hostId, page.parentPath); - const updated = setAddProjectPageInput(state, value); - return { - ...updated, - newDirectoryNameDrafts: { - ...updated.newDirectoryNameDrafts, - [draftKey]: value, - }, - }; -} - -function newDirectoryDraftKey(hostId: string, parentPath: string): string { - return `${hostId}\u0000${parentPath}`; -} - -function githubLocationDraftKey(hostId: string, repositoryId: string): string { - return `${hostId}\u0000${repositoryId}`; -} - -export function setAddProjectActiveIndex( - state: AddProjectFlowState, - activeIndex: number, -): AddProjectFlowState { - const page = currentAddProjectPage(state); - const updated = updateCurrentAddProjectPage(state, (current) => ({ ...current, activeIndex })); - if (page.kind !== "github-location") return updated; - const draftKey = githubLocationDraftKey(page.hostId, page.repository.id); - return { - ...updated, - githubLocationDrafts: { - ...updated.githubLocationDrafts, - [draftKey]: { query: page.query, activeIndex }, - }, - }; + if (state.submission.status !== "submitting") return state; + return { ...state, submission: { status: "failed", tab: state.submission.tab, message } }; } export function moveAddProjectActiveIndex( @@ -283,16 +214,37 @@ export function moveAddProjectActiveIndex( return next; } -export function moveAddProjectSelection( - activeIndex: number, - selectable: readonly boolean[], - direction: "next" | "previous", -): number { - if (!selectable.some(Boolean)) return 0; - let next = activeIndex; - for (let count = 0; count < selectable.length; count += 1) { - next = moveAddProjectActiveIndex(next, selectable.length, direction); - if (selectable[next]) return next; - } - return activeIndex; +export interface AddProjectKeyInput { + key: string; + metaKey: boolean; + ctrlKey: boolean; + altKey: boolean; + shiftKey: boolean; +} + +export type AddProjectKeyCommand = + | { kind: "tab"; tab: AddProjectTab } + | { kind: "move"; direction: "next" | "previous" } + | { kind: "submit" }; + +/** Keys the sheet claims besides Escape. Digits only act with the platform's Mod key. */ +export const ADD_PROJECT_KEYS = ["Enter", "ArrowUp", "ArrowDown", "1", "2", "3"] as const; + +export function resolveAddProjectKey( + input: AddProjectKeyInput, + isMac: boolean, +): AddProjectKeyCommand | null { + const modOnly = + (isMac ? input.metaKey && !input.ctrlKey : input.ctrlKey && !input.metaKey) && + !input.altKey && + !input.shiftKey; + const plain = !input.metaKey && !input.ctrlKey && !input.altKey && !input.shiftKey; + const tabIndex = ["1", "2", "3"].indexOf(input.key); + const tab = ADD_PROJECT_TABS[tabIndex]; + if (tab && modOnly) return { kind: "tab", tab }; + if (!plain) return null; + if (input.key === "ArrowDown") return { kind: "move", direction: "next" }; + if (input.key === "ArrowUp") return { kind: "move", direction: "previous" }; + if (input.key === "Enter") return { kind: "submit" }; + return null; } diff --git a/packages/app/src/add-project-flow/new-folder-tab.tsx b/packages/app/src/add-project-flow/new-folder-tab.tsx new file mode 100644 index 0000000000..ccdb109e1c --- /dev/null +++ b/packages/app/src/add-project-flow/new-folder-tab.tsx @@ -0,0 +1,114 @@ +import { useMemo } from "react"; +import { View } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { Field, FormTextInput } from "@/components/ui/form-field"; +import { isWeb } from "@/constants/platform"; +import type { AddProjectActions } from "./use-add-project-actions"; +import type { AddProjectFlowState, AddProjectHost } from "./model"; +import { LocationField } from "./location-field"; +import { joinDirectoryPath, validateNewFolderName } from "./options"; +import type { AddProjectTabView } from "./tab-view"; + +export interface NewFolderTabView extends AddProjectTabView { + location: string; + destination: string; + /** Why the typed name cannot be a folder; null while empty or valid. */ + nameError: string | null; +} + +export function useNewFolderTab(input: { + state: AddProjectFlowState; + host: AddProjectHost | null; + defaultLocation: string; + actions: AddProjectActions; +}): NewFolderTabView { + const { state, host, defaultLocation, actions } = input; + const { name } = state.newFolder; + const location = state.newFolder.location ?? defaultLocation; + const trimmed = name.trim(); + const nameError = trimmed ? validateNewFolderName(name) : null; + // Preview and create only a name that can be created, so the field never shows a path that + // escapes the location. + const previewName = trimmed && !nameError ? trimmed : null; + const canCreate = host?.canCreateDirectory === true; + + return useMemo( + () => ({ + rows: [], + activeIndex: 0, + notice: null, + location, + destination: previewName ? joinDirectoryPath(location, previewName) : location, + unavailable: canCreate ? null : "Update the host to create folders", + nameError, + primary: { + label: "Create project", + submit: canCreate && previewName ? () => actions.createFolder(name, location) : null, + }, + }), + [actions, canCreate, location, name, nameError, previewName], + ); +} + +export function NewFolderTab({ + view, + name, + hostId, + recommendedPaths, + disabled, + autoFocus, + onNameChange, + onLocationChange, +}: { + view: NewFolderTabView; + name: string; + hostId: string | null; + recommendedPaths: string[]; + disabled: boolean; + /** Focus the field on mount; only with a hardware keyboard, so touch keeps the list in view. */ + autoFocus: boolean; + onNameChange: (name: string) => void; + onLocationChange: (location: string) => void; +}) { + const editable = !disabled && !view.unavailable; + return ( + + + + + + + ); +} + +const styles = StyleSheet.create((theme) => ({ + body: { + gap: theme.spacing[4], + }, +})); diff --git a/packages/app/src/add-project-flow/options.ts b/packages/app/src/add-project-flow/options.ts index c1d6ce9e4e..4d3098f65b 100644 --- a/packages/app/src/add-project-flow/options.ts +++ b/packages/app/src/add-project-flow/options.ts @@ -3,83 +3,7 @@ import { parseGitHubRemoteUrl, parseGitRemoteLocation, } from "@getpaseo/protocol/git-remote"; -import { shortenPath } from "@/utils/shorten-path"; -import type { AddProjectHost, GithubRepositoryChoice } from "./model"; - -export type AddProjectMethodId = "directory-search" | "browse" | "github" | "new-directory"; - -export interface AddProjectMethodOption { - id: AddProjectMethodId; - label: string; - description: string; - disabled?: boolean; -} - -export interface AddProjectPathOption { - id: string; - path: string; - displayPath: string; - secondaryText: string | null; - disabled: boolean; -} - -export function filterAddProjectHosts(hosts: AddProjectHost[], query: string): AddProjectHost[] { - const normalized = query.trim().toLowerCase(); - if (!normalized) return hosts; - return hosts.filter( - (host) => - host.label.toLowerCase().includes(normalized) || - host.serverId.toLowerCase().includes(normalized), - ); -} - -export function buildAddProjectMethods(host: AddProjectHost): AddProjectMethodOption[] { - if (!host.canAddProject) return []; - const options: AddProjectMethodOption[] = []; - options.push({ - id: "directory-search", - label: "Search for directory", - description: `Find a directory on ${host.label}`, - }); - if (host.canBrowse) { - options.push({ - id: "browse", - label: "Browse", - description: "Choose or create a directory in Finder", - }); - } - options.push({ - id: "github", - label: "Clone from GitHub", - description: githubMethodDescription(host), - disabled: !host.canCloneGithubRepositories, - }); - options.push({ - id: "new-directory", - label: "New directory", - description: host.canCreateDirectory - ? `Create an empty directory on ${host.label}` - : "Update this host to create directories", - disabled: !host.canCreateDirectory, - }); - return options; -} - -export function addProjectMethodEmptyText(host: AddProjectHost | null): string { - return host?.canAddProject === false - ? "Update the host to use Add Project." - : "No matching options"; -} - -function githubMethodDescription(host: AddProjectHost): string { - if (!host.canCloneGithubRepositories) { - return "Update this host to clone GitHub repositories"; - } - if (host.canSearchGithubRepositories) { - return "Search projects available to your GitHub account"; - } - return "Enter a GitHub URL or owner/repo"; -} +import type { GithubRepositoryChoice } from "./model"; export function pathBaseName(path: string): string { const trimmed = path.replace(/[\\/]+$/, ""); @@ -87,6 +11,9 @@ export function pathBaseName(path: string): string { return parts[parts.length - 1] ?? trimmed; } +/** Starts the id of every choice built from what the user typed. */ +export const MANUAL_CHOICE_PREFIX = "manual:"; + export function buildManualGithubRepositoryChoices(query: string): GithubRepositoryChoice[] { const repo = query.trim(); if (!repo) return []; @@ -97,7 +24,7 @@ export function buildManualGithubRepositoryChoices(query: string): GithubReposit const remoteName = location ? pathBaseName(location.path).replace(/\.git$/u, "") : repo; return [ { - id: `manual:${repo}`, + id: `${MANUAL_CHOICE_PREFIX}${repo}`, nameWithOwner: identity?.repo ?? remoteName, cloneUrl: repo, description: "Clone this repository URL", @@ -110,7 +37,7 @@ export function buildManualGithubRepositoryChoices(query: string): GithubReposit if (!shorthand) return []; const nameWithOwner = `${shorthand[1]}/${shorthand[2]}`; return (["https", "ssh"] as const).map((cloneProtocol) => ({ - id: `manual:${cloneProtocol}:${nameWithOwner}`, + id: `${MANUAL_CHOICE_PREFIX}${cloneProtocol}:${nameWithOwner}`, nameWithOwner, cloneUrl: nameWithOwner, cloneProtocol, @@ -119,18 +46,21 @@ export function buildManualGithubRepositoryChoices(query: string): GithubReposit })); } +/** The folder that holds `path`. A root keeps its separator: `C:\repo` gives `C:\`, not `C:`. */ export function parentDirectory(path: string): string | null { const trimmed = path.replace(/[\\/]+$/, ""); + // A share root (\\server\share) has no parent folder; `\\server` alone is not a directory. + if (/^[\\/]{2}[^\\/]+[\\/][^\\/]+$/u.test(trimmed)) return null; const index = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\")); if (index < 0) return null; - if (index === 0) return trimmed.slice(0, 1); - return trimmed.slice(0, index); + const parent = trimmed.slice(0, index); + const isRoot = parent === "" || /^[A-Za-z]:$/u.test(parent); + return isRoot ? trimmed.slice(0, index + 1) : parent; } export function joinDirectoryPath(parent: string, name: string): string { - const trimmedParent = parent.replace(/[\\/]+$/, ""); - const separator = trimmedParent.includes("\\") && !trimmedParent.includes("/") ? "\\" : "/"; - return `${trimmedParent}${separator}${name}`; + const separator = parent.includes("\\") && !parent.includes("/") ? "\\" : "/"; + return `${parent.replace(/[\\/]+$/, "")}${separator}${name}`; } export function buildSuggestedParentDirectories(projectPaths: string[]): string[] { @@ -149,34 +79,31 @@ export function buildSuggestedParentDirectories(projectPaths: string[]): string[ return [...new Set(values)]; } -export function buildCloneLocationOptions(input: { - parents: string[]; - repositoryName: string; - existingPaths: string[]; -}): AddProjectPathOption[] { - const existing = new Set(input.existingPaths.map(pathIdentity)); - const seen = new Set(); - return input.parents.flatMap((parent) => { - const path = joinDirectoryPath(parent, input.repositoryName); - const identity = pathIdentity(path); - if (seen.has(identity)) return []; - seen.add(identity); - const pathExists = existing.has(identity); - return [ - { - id: parent, - path: parent, - displayPath: path, - secondaryText: pathExists ? "Already exists" : `Parent directory: ${parent}`, - disabled: pathExists, - }, - ]; - }); +/** + * Where a new folder or clone goes when the user has not picked a location on this host: the last + * one used, else the parent of a recent project, else home. Only folders known to exist qualify; + * guesses like `~/dev` stay suggestions in the Location picker. + */ +export function defaultProjectLocation(input: { + remembered: string | undefined; + projectPaths: string[]; +}): string { + const projectParent = input.projectPaths + .map(parentDirectory) + .find((parent): parent is string => parent !== null); + return input.remembered ?? projectParent ?? "~"; } -function pathIdentity(path: string): string { - const normalized = shortenPath(path.trim()).replace(/\\/g, "/").replace(/\/+$/u, ""); - return /^[A-Za-z]:\//u.test(normalized) || normalized.startsWith("//") - ? normalized.toLowerCase() - : normalized; +/** The folder a clone of `nameWithOwner` checks out into; the host drops a trailing `.git`. */ +export function checkoutName(nameWithOwner: string): string { + return pathBaseName(nameWithOwner).replace(/\.git$/u, ""); +} + +export function validateNewFolderName(name: string): string | null { + const trimmed = name.trim(); + if (!trimmed || trimmed === "." || trimmed === "..") return "Enter a folder name"; + if (/[\\/]/.test(trimmed)) return "Use a name without slashes"; + // The host rejects a drive prefix on every platform. + if (/^[A-Za-z]:/u.test(trimmed)) return "Use a name without a drive letter"; + return null; } diff --git a/packages/app/src/add-project-flow/result-list-id.ts b/packages/app/src/add-project-flow/result-list-id.ts new file mode 100644 index 0000000000..fde1cc935a --- /dev/null +++ b/packages/app/src/add-project-flow/result-list-id.ts @@ -0,0 +1,2 @@ +/** The result list's test ID, which the web Enter check also uses to recognise a focused row. */ +export const RESULTS_TEST_ID = "add-project-flow-results"; diff --git a/packages/app/src/add-project-flow/result-list.tsx b/packages/app/src/add-project-flow/result-list.tsx new file mode 100644 index 0000000000..dcfb9cb78b --- /dev/null +++ b/packages/app/src/add-project-flow/result-list.tsx @@ -0,0 +1,243 @@ +import { useCallback, useMemo, useRef, type ComponentType, type RefObject } from "react"; +import { Check } from "lucide-react-native"; +import { Text, View, type ScrollView as NativeScrollView } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { LoadingSpinner } from "@/components/ui/loading-spinner"; +import { PressHighlight } from "@/components/ui/press-highlight"; +import { ScrollView } from "@/components/ui/scroll-view"; +import { useRevealActiveItem } from "@/components/ui/scroll-reveal"; +import { Shortcut } from "@/components/ui/shortcut"; +import { useHardwareKeyboardPresent } from "@/keyboard"; +import { settingsStyles } from "@/styles/settings"; +import type { Theme } from "@/styles/theme"; + +type RowIcon = ComponentType<{ size?: number; color?: string }>; + +export interface ResultRow { + id: string; + title: string; + subtitle: string | null; + icon: RowIcon; + testID: string; +} + +/** What the list says when it has no rows to show. */ +export type ResultListNotice = + | { kind: "pending"; text: string } + | { kind: "empty"; text: string } + | { kind: "error"; text: string }; + +interface ResultListProps { + rows: ResultRow[]; + activeIndex: number; + /** Shown in place of the rows when there are none, or above them for an error. */ + notice: ResultListNotice | null; + onSelect: (index: number) => void; + disabled?: boolean; + testID: string; +} + +const ENTER_KEYS = ["Enter"]; +// Fixed line heights make a two-line row the same height on every platform. +const TITLE_LINE_HEIGHT = 18; +const SUBTITLE_LINE_HEIGHT = 16; + +function RowGlyph({ icon: Icon, size, color }: { icon: RowIcon; size: number; color?: string }) { + return ; +} +const MutedRowGlyph = withUnistyles(RowGlyph, (theme: Theme) => ({ + color: theme.colors.foregroundMuted, +})); +const AccentCheck = withUnistyles(Check, (theme: Theme) => ({ color: theme.colors.accent })); +const ThemedSpinner = withUnistyles(LoadingSpinner, (theme: Theme) => ({ + color: theme.colors.foregroundMuted, +})); + +/** Enter commits the active row when there is a keyboard; on touch, a check marks the choice. */ +function ActiveMark() { + const keyboardPresent = useHardwareKeyboardPresent(); + return keyboardPresent ? : ; +} + +function ResultRowView({ + row, + index, + active, + disabled, + activeItemRef, + onActiveLayout, + onSelect, +}: { + row: ResultRow; + index: number; + active: boolean; + disabled: boolean; + activeItemRef: RefObject; + onActiveLayout: () => void; + onSelect: (index: number) => void; +}) { + const handlePress = useCallback(() => onSelect(index), [index, onSelect]); + const style = useMemo( + () => [ + settingsStyles.row, + styles.row, + index > 0 && settingsStyles.rowBorder, + active && styles.rowActive, + ], + [active, index], + ); + const accessibilityState = useMemo(() => ({ selected: active, disabled }), [active, disabled]); + return ( + + + + + + + {row.title} + + {row.subtitle ? ( + + {row.subtitle} + + ) : null} + + {/* Reserved on every row so the active row's mark never shifts its text. */} + {active ? : null} + + ); +} + +/** + * A card of choices with one active row. Arrow keys, taps, and keyboard focus move the active + * row; the sheet's primary action commits it. The list keeps the active row scrolled into view. + */ +export function ResultList({ + rows, + activeIndex, + notice, + onSelect, + disabled = false, + testID, +}: ResultListProps) { + const scrollRef = useRef(null); + const listKey = useMemo(() => rows.map((row) => row.id).join("\u0000"), [rows]); + const { activeItemRef, contentRef, onItemLayout, onViewportLayout, onScroll } = + useRevealActiveItem({ activeIndex, listKey, scrollRef }); + const showNotice = notice && (rows.length === 0 || notice.kind === "error"); + + return ( + + {showNotice ? ( + + {notice.kind === "pending" ? : null} + + {notice.text} + + + ) : null} + {rows.length > 0 ? ( + + + + {rows.map((row, index) => ( + + ))} + + + + ) : null} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + frame: { + flex: 1, + minHeight: 0, + gap: theme.spacing[3], + }, + listCard: { + flexShrink: 1, + minHeight: 0, + }, + // Every row is as tall as a two-line row, so rows without a subtitle do not break the rhythm. + row: { + minHeight: theme.spacing[3] * 2 + TITLE_LINE_HEIGHT + SUBTITLE_LINE_HEIGHT, + paddingVertical: theme.spacing[3], + justifyContent: "flex-start", + gap: theme.spacing[3], + }, + rowActive: { + backgroundColor: theme.colors.surface2, + }, + iconSlot: { + width: 16, + alignItems: "center", + }, + rowText: { + flex: 1, + minWidth: 0, + }, + rowTitle: { + lineHeight: TITLE_LINE_HEIGHT, + }, + rowSubtitle: { + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.sm, + lineHeight: SUBTITLE_LINE_HEIGHT, + }, + trailingSlot: { + minWidth: theme.spacing[6], + alignItems: "flex-end", + }, + noticeCard: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + paddingHorizontal: theme.spacing[4], + paddingVertical: theme.spacing[4], + }, + noticeText: { + flex: 1, + color: theme.colors.foregroundMuted, + fontSize: theme.fontSize.base, + }, + noticeError: { + flex: 1, + color: theme.colors.statusDanger, + fontSize: theme.fontSize.base, + }, +})); diff --git a/packages/app/src/add-project-flow/search-result.test.ts b/packages/app/src/add-project-flow/search-result.test.ts new file mode 100644 index 0000000000..51944de25d --- /dev/null +++ b/packages/app/src/add-project-flow/search-result.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from "vitest"; +import { resolveSearch, type SearchAnswer } from "./search-result"; + +const EMPTY: string[] = []; + +function answer(overrides: Partial> = {}): SearchAnswer { + return { hostId: "host-1", query: "app", items: ["/code/app"], error: null, ...overrides }; +} + +function resolve(overrides: Partial>[0]> = {}) { + return resolveSearch({ + enabled: true, + hostId: "host-1", + query: "app", + debouncedQuery: "app", + data: answer(), + failed: null, + empty: EMPTY, + ...overrides, + }); +} + +describe("resolveSearch", () => { + it("shows the answer for the current query", () => { + expect(resolve()).toEqual({ items: ["/code/app"], pending: false, error: null }); + }); + + it("keeps the last items while the next query is pending", () => { + expect(resolve({ query: "apps", debouncedQuery: "apps" })).toEqual({ + items: ["/code/app"], + pending: true, + error: null, + }); + }); + + it("never shows another host's answer, even for the same query", () => { + expect(resolve({ hostId: "host-2" })).toEqual({ items: [], pending: true, error: null }); + }); + + it("drops the last query's error while the next query is pending", () => { + const failedAnswer = answer({ items: [], error: "Rate limited" }); + expect(resolve({ data: failedAnswer })).toEqual({ + items: [], + pending: false, + error: "Rate limited", + }); + expect(resolve({ data: failedAnswer, query: "apps" })).toEqual({ + items: [], + pending: true, + error: null, + }); + }); + + it("shows a failed request only once the user stops typing", () => { + expect(resolve({ data: undefined, failed: "Unable to search" })).toEqual({ + items: [], + pending: false, + error: "Unable to search", + }); + expect(resolve({ data: undefined, failed: "Unable to search", query: "apps" })).toEqual({ + items: [], + pending: true, + error: null, + }); + }); + + it("is idle when disabled", () => { + expect(resolve({ enabled: false })).toEqual({ items: [], pending: false, error: null }); + }); +}); diff --git a/packages/app/src/add-project-flow/search-result.ts b/packages/app/src/add-project-flow/search-result.ts new file mode 100644 index 0000000000..9707c24029 --- /dev/null +++ b/packages/app/src/add-project-flow/search-result.ts @@ -0,0 +1,47 @@ +/** + * What a search shows while the user types. `items` keep the last results until the current + * query's results arrive, so rows do not flash away on every keystroke. + */ +export interface SearchResult { + items: T[]; + /** Results for the current query have not arrived yet. */ + pending: boolean; + error: string | null; +} + +/** One answer from the host: what it found for `query`, or why it could not search. */ +export interface SearchAnswer { + hostId: string | null; + query: string; + items: T[]; + error: string | null; +} + +/** + * Decides what to show for `query` on `hostId`. An answer from another host never shows. While + * the current query is pending the last items stay, but an old error does not. + */ +export function resolveSearch(input: { + enabled: boolean; + hostId: string | null; + /** What the user typed. */ + query: string; + /** The query the last request was sent for; it trails `query` while the user types. */ + debouncedQuery: string; + /** The latest answer, which may be for an earlier query or another host. */ + data: SearchAnswer | undefined; + /** Why the request for `debouncedQuery` failed, if it did. */ + failed: string | null; + empty: T[]; +}): SearchResult { + const { enabled, hostId, query, debouncedQuery, data, failed, empty } = input; + if (!enabled) return { items: empty, pending: false, error: null }; + if (failed) { + return query === debouncedQuery + ? { items: empty, pending: false, error: failed } + : { items: empty, pending: true, error: null }; + } + const answer = data?.hostId === hostId ? data : undefined; + if (answer?.query === query) return { items: answer.items, pending: false, error: answer.error }; + return { items: answer && !answer.error ? answer.items : empty, pending: true, error: null }; +} diff --git a/packages/app/src/add-project-flow/searches.ts b/packages/app/src/add-project-flow/searches.ts new file mode 100644 index 0000000000..85e04e6035 --- /dev/null +++ b/packages/app/src/add-project-flow/searches.ts @@ -0,0 +1,102 @@ +import { useMemo } from "react"; +import { useFetchQuery } from "@/data/query"; +import { useDebouncedValue } from "@/hooks/use-debounced-value"; +import { useHostRuntimeClient } from "@/runtime/host-runtime"; +import type { GithubRepositoryChoice } from "./model"; +import { resolveSearch, type SearchResult } from "./search-result"; + +export type { SearchResult } from "./search-result"; + +const SEARCH_DEBOUNCE_MS = 250; +const EMPTY_PATHS: string[] = []; +const EMPTY_REPOSITORIES: GithubRepositoryChoice[] = []; + +/** Directories on the host matching `query`, debounced while the user types. */ +export function useDirectorySearch(input: { + hostId: string | null; + query: string; + enabled: boolean; +}): SearchResult { + const { hostId } = input; + const client = useHostRuntimeClient(hostId ?? ""); + const debouncedQuery = useDebouncedValue(input.query, SEARCH_DEBOUNCE_MS); + const enabled = Boolean(client && input.enabled); + const search = useFetchQuery({ + queryKey: ["add-project-flow-directories", hostId, debouncedQuery], + queryFn: async () => { + if (!client) throw new Error("Host is unavailable"); + const payload = await client.getDirectorySuggestions({ + query: debouncedQuery, + includeDirectories: true, + includeFiles: false, + limit: 30, + }); + const items = + payload.entries?.flatMap((entry) => (entry.kind === "directory" ? [entry.path] : [])) ?? []; + return { hostId, query: debouncedQuery, items, error: payload.error ?? null }; + }, + enabled, + dataShape: "list", + retry: false, + staleTimeMs: 15_000, + }); + const failed = search.isError ? "Unable to search folders" : null; + return useMemo( + () => + resolveSearch({ + enabled, + hostId, + query: input.query, + debouncedQuery, + data: search.data, + failed, + empty: EMPTY_PATHS, + }), + [debouncedQuery, enabled, failed, hostId, input.query, search.data], + ); +} + +/** GitHub repositories the host's account can see, matching `query`. */ +export function useGithubRepositorySearch(input: { + hostId: string | null; + query: string; + enabled: boolean; +}): SearchResult { + const { hostId } = input; + const client = useHostRuntimeClient(hostId ?? ""); + const debouncedQuery = useDebouncedValue(input.query, SEARCH_DEBOUNCE_MS); + const enabled = Boolean(client && input.enabled); + const search = useFetchQuery({ + queryKey: ["add-project-flow-github", hostId, debouncedQuery], + queryFn: async () => { + if (!client) throw new Error("Host is unavailable"); + const payload = await client.searchGithubRepositories({ query: debouncedQuery, limit: 30 }); + let error: string | null = payload.error ?? null; + if (!error && payload.available === false) error = "GitHub search is unavailable"; + return { + hostId, + query: debouncedQuery, + items: error ? EMPTY_REPOSITORIES : payload.repositories, + error, + }; + }, + enabled, + dataShape: "list", + retry: false, + staleTimeMs: 15_000, + }); + const failed = search.isError ? "Unable to search GitHub" : null; + return useMemo( + () => + resolveSearch({ + enabled, + hostId, + query: input.query, + debouncedQuery, + data: search.data, + failed, + empty: EMPTY_REPOSITORIES, + }), + [debouncedQuery, enabled, failed, hostId, input.query, search.data], + ); +} diff --git a/packages/app/src/add-project-flow/tab-view.ts b/packages/app/src/add-project-flow/tab-view.ts new file mode 100644 index 0000000000..2f281b5a24 --- /dev/null +++ b/packages/app/src/add-project-flow/tab-view.ts @@ -0,0 +1,29 @@ +import type { ResultListNotice, ResultRow } from "./result-list"; + +/** What the sheet needs from the current tab to drive its keys and its primary button. */ +export interface AddProjectTabView { + /** The rows Up and Down walk; empty for a tab without a list. */ + rows: ResultRow[]; + /** The active row, or -1 when none is: an older search's rows, or a pick the new answer dropped. */ + activeIndex: number; + notice: ResultListNotice | null; + /** Why this host cannot do what the tab offers; the tab's fields are read-only while set. */ + unavailable: string | null; + primary: { + label: string; + /** Absent when there is nothing to commit yet. */ + submit: (() => void) | null; + }; +} + +/** + * Where the user's pick sits in `rows`. Without a pick, the first row is the default. A pick that + * a new answer dropped is not swapped for another row: nothing is active until the user picks again. + */ +export function resolveActiveIndex( + rows: readonly { id: string }[], + selectedId: string | null, +): number { + if (selectedId === null) return rows.length > 0 ? 0 : -1; + return rows.findIndex((row) => row.id === selectedId); +} diff --git a/packages/app/src/add-project-flow/use-add-project-actions.ts b/packages/app/src/add-project-flow/use-add-project-actions.ts new file mode 100644 index 0000000000..d3fd574e60 --- /dev/null +++ b/packages/app/src/add-project-flow/use-add-project-actions.ts @@ -0,0 +1,182 @@ +import { useCallback, useEffect, useRef, type Dispatch, type SetStateAction } from "react"; +import { router } from "expo-router"; +import type { WorkspaceProjectDescriptorPayload } from "@getpaseo/protocol/messages"; +import { pickDirectory } from "@/desktop/pick-directory"; +import { getOpenProjectFailureReason, registerProjectDescriptor } from "@/hooks/open-project"; +import { useCloneGithubProject, useOpenProject } from "@/hooks/use-open-project"; +import { getHostRuntimeStore, useHostRuntimeClient } from "@/runtime/host-runtime"; +import { useAddProjectFlowStore } from "@/stores/add-project-flow-store"; +import { usePanelStore } from "@/stores/panel-store"; +import { useSessionStore } from "@/stores/session-store"; +import { buildNewWorkspaceRoute } from "@/utils/host-routes"; +import { + failAddProjectSubmission, + startAddProjectSubmission, + type AddProjectFlowState, + type GithubRepositoryChoice, +} from "./model"; + +/** A failure found before any work starts, shown the same way as one the host reports. */ +function rejectSubmission(state: AddProjectFlowState, message: string): AddProjectFlowState { + return failAddProjectSubmission(startAddProjectSubmission(state), message); +} + +export interface AddProjectActions { + openFolder: (path: string) => void; + browse: () => void; + clone: (repository: GithubRepositoryChoice, location: string) => void; + /** Expects a name that passed `validateNewFolderName`; the New folder tab only offers those. */ + createFolder: (name: string, location: string) => void; +} + +/** What a submission's work reports: the project to open, or why it failed. */ +type SubmissionOutcome = + | { ok: true; project: WorkspaceProjectDescriptorPayload } + | { ok: false; error: string }; + +/** + * The three ways a project gets added. Each one records its progress and failure in the flow + * state and, on success, closes the flow and opens a new workspace for the project. + */ +export function useAddProjectActions(input: { + hostId: string | null; + setState: Dispatch>; + onClose: () => void; +}): AddProjectActions { + const { hostId, setState, onClose } = input; + const client = useHostRuntimeClient(hostId ?? ""); + const openProject = useOpenProject(hostId); + const cloneGithubProject = useCloneGithubProject(hostId); + const setHasHydratedWorkspaces = useSessionStore((store) => store.setHasHydratedWorkspaces); + const rememberLocation = useAddProjectFlowStore((store) => store.rememberLocation); + // The running submission, if any. It belongs to the open sheet and the host it started on: + // closing the sheet or losing that host abandons it, so a late result neither navigates nor + // blocks the next submission. + const submissionRef = useRef(null); + useEffect( + () => () => { + submissionRef.current = null; + }, + [hostId], + ); + + /** Runs one submission at a time and opens a new workspace for the project it adds. */ + const run = useCallback( + async (serverId: string, work: () => Promise, fallbackError: string) => { + if (submissionRef.current) return; + const submission = Symbol("add-project-submission"); + submissionRef.current = submission; + const isCurrent = () => submissionRef.current === submission; + setState(startAddProjectSubmission); + let outcome: SubmissionOutcome; + try { + outcome = await work(); + } catch (error) { + const message = error instanceof Error && error.message ? error.message : fallbackError; + outcome = { ok: false, error: message }; + } + if (!isCurrent()) return; + submissionRef.current = null; + if (!outcome.ok) { + setState((state) => failAddProjectSubmission(state, outcome.error)); + return; + } + onClose(); + usePanelStore.getState().showMobileAgent(); + router.push( + buildNewWorkspaceRoute({ + serverId, + projectId: outcome.project.projectId, + sourceDirectory: outcome.project.projectRootPath, + displayName: outcome.project.projectDisplayName, + }), + ); + }, + [onClose, setState], + ); + + const openFolder = useCallback( + (path: string) => { + if (!hostId) return; + void run( + hostId, + async () => { + const result = await openProject(path); + if (result.ok) return { ok: true, project: result.project }; + if (getOpenProjectFailureReason(result) === "directory_not_found") { + return { ok: false, error: "Folder not found" }; + } + return { ok: false, error: result.error ?? "Unable to add project" }; + }, + "Unable to add project", + ); + }, + [hostId, openProject, run], + ); + + // The desktop folder dialog is modal to the window, so nothing else can start while it is open. + const browse = useCallback(() => { + if (!hostId || submissionRef.current) return; + void (async () => { + try { + const path = await pickDirectory(); + if (path) openFolder(path); + } catch { + setState((state) => rejectSubmission(state, "Unable to browse for a folder")); + } + })(); + }, [hostId, openFolder, setState]); + + const clone = useCallback( + (repository: GithubRepositoryChoice, location: string) => { + if (!hostId) return; + void run( + hostId, + async () => { + const result = await cloneGithubProject( + repository.cloneUrl, + location, + repository.cloneProtocol, + ); + if (!result.ok) return { ok: false, error: result.error ?? "Unable to clone project" }; + rememberLocation(hostId, location); + return { ok: true, project: result.project }; + }, + "Unable to clone project", + ); + }, + [cloneGithubProject, hostId, rememberLocation, run], + ); + + const createFolder = useCallback( + (name: string, location: string) => { + if (!hostId) return; + void run( + hostId, + async () => { + if (!client) return { ok: false, error: "Unable to create folder" }; + const payload = await client.createProjectDirectory({ + parentPath: location, + name: name.trim(), + }); + if (payload.error || !payload.project) { + return { ok: false, error: payload.error ?? "Unable to create folder" }; + } + registerProjectDescriptor({ + serverId: hostId, + project: payload.project, + upsertProject: (serverId, project) => + getHostRuntimeStore().acceptProjectSnapshot(serverId, project), + setHasHydratedWorkspaces, + }); + rememberLocation(hostId, location); + return { ok: true, project: payload.project }; + }, + "Unable to create folder", + ); + }, + [client, hostId, rememberLocation, run, setHasHydratedWorkspaces], + ); + + return { openFolder, browse, clone, createFolder }; +} diff --git a/packages/app/src/add-project-flow/use-add-project-hosts.ts b/packages/app/src/add-project-flow/use-add-project-hosts.ts new file mode 100644 index 0000000000..bb51e8e7e6 --- /dev/null +++ b/packages/app/src/add-project-flow/use-add-project-hosts.ts @@ -0,0 +1,51 @@ +import { useMemo } from "react"; +import { getIsElectronRuntime } from "@/constants/layout"; +import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon"; +import { useHosts, useHostRuntimeConnectionStatuses } from "@/runtime/host-runtime"; +import { useHostFeatureMap } from "@/runtime/host-features"; +import { orderHostsLocalFirst } from "@/types/host-connection"; +import type { AddProjectHost } from "./model"; + +/** Every host, whether it is online, and what each can do in Add project, the local host first. */ +export function useAddProjectHosts(): AddProjectHost[] { + const hosts = useHosts(); + const hostIds = useMemo(() => hosts.map((host) => host.serverId), [hosts]); + const connectionStatuses = useHostRuntimeConnectionStatuses(hostIds); + const projectAddByHost = useHostFeatureMap(hostIds, "projectAdd"); + // COMPAT(stableProjectIdentity): added in v0.1.109, remove gate after 2027-01-15. + const stableProjectIdentityByHost = useHostFeatureMap(hostIds, "stableProjectIdentity"); + // COMPAT(projectGithubClone): added in v0.1.108, remove gate after 2027-01-15. + const githubCloneByHost = useHostFeatureMap(hostIds, "projectGithubClone"); + // COMPAT(workspaceGithubRepositorySearch): added in v0.1.108, remove gate after 2027-01-15. + const githubSearchByHost = useHostFeatureMap(hostIds, "workspaceGithubRepositorySearch"); + // COMPAT(projectCreateDirectory): added in v0.1.108, remove gate after 2027-01-15. + const createDirectoryByHost = useHostFeatureMap(hostIds, "projectCreateDirectory"); + const localServerId = useLocalDaemonServerId(); + + return useMemo(() => { + return orderHostsLocalFirst(hosts, localServerId).map((host) => { + const canAddProject = + projectAddByHost.get(host.serverId) === true && + stableProjectIdentityByHost.get(host.serverId) === true; + return { + serverId: host.serverId, + label: host.label, + online: connectionStatuses.get(host.serverId) === "online", + canAddProject, + canBrowse: canAddProject && getIsElectronRuntime() && localServerId === host.serverId, + canCloneGithubRepositories: githubCloneByHost.get(host.serverId) === true, + canSearchGithubRepositories: githubSearchByHost.get(host.serverId) === true, + canCreateDirectory: createDirectoryByHost.get(host.serverId) === true, + }; + }); + }, [ + connectionStatuses, + createDirectoryByHost, + githubCloneByHost, + githubSearchByHost, + hosts, + localServerId, + projectAddByHost, + stableProjectIdentityByHost, + ]); +} diff --git a/packages/app/src/components/adaptive-modal-sheet.tsx b/packages/app/src/components/adaptive-modal-sheet.tsx index 193ef7ad31..372c7270c5 100644 --- a/packages/app/src/components/adaptive-modal-sheet.tsx +++ b/packages/app/src/components/adaptive-modal-sheet.tsx @@ -597,6 +597,16 @@ export interface AdaptiveModalSheetProps { contentStyle?: StyleProp; /** Re-establishes caller-owned contexts inside the native or compact sheet portal. */ contextBridge?: ContextBridge | null; + /** + * Keys the body handles while the sheet is the top overlay, such as list navigation. Escape + * always closes the sheet. Return true from `onKeyDown` to claim the key. + */ + keyboard?: SheetKeyboard; +} + +export interface SheetKeyboard { + keys: readonly string[]; + onKeyDown: (event: KeyboardInputEvent) => boolean; } /** @@ -696,6 +706,7 @@ export function AdaptiveModalSheet({ contentStyle, bodyStyle, contextBridge = null, + keyboard, }: AdaptiveModalSheetProps) { const { t } = useTranslation(); const isMobile = useIsCompactFormFactor(); @@ -754,16 +765,21 @@ export function AdaptiveModalSheet({ const handleOverlayKeyDown = useCallback( (event: KeyboardInputEvent) => { - if (event.key !== "Escape") return false; + if (event.key !== "Escape") { + if (!keyboard?.onKeyDown(event)) return false; + event.preventDefault(); + return true; + } event.preventDefault(); event.stopPropagation(); onClose(); return true; }, - [onClose], + [keyboard, onClose], ); + const overlayKeys = useMemo(() => ["Escape", ...(keyboard?.keys ?? [])], [keyboard?.keys]); const setOverlayScope = useOverlayRegistration({ - keys: ["Escape"], + keys: overlayKeys, active: visible, layer: modalLayer, onKeyDown: handleOverlayKeyDown, diff --git a/packages/app/src/components/add-project-flow-host.tsx b/packages/app/src/components/add-project-flow-host.tsx index bf8ad055c4..1d41eb3df5 100644 --- a/packages/app/src/components/add-project-flow-host.tsx +++ b/packages/app/src/components/add-project-flow-host.tsx @@ -1,4 +1,4 @@ -import { AddProjectFlow } from "@/components/add-project-flow"; +import { AddProjectFlow } from "@/add-project-flow"; import { useAddProjectFlowStore } from "@/stores/add-project-flow-store"; export function AddProjectFlowHost() { diff --git a/packages/app/src/components/add-project-flow.tsx b/packages/app/src/components/add-project-flow.tsx deleted file mode 100644 index 038e026c76..0000000000 --- a/packages/app/src/components/add-project-flow.tsx +++ /dev/null @@ -1,1098 +0,0 @@ -import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard"; -import { useAddHost } from "@/hosts/add-host"; -import { Modal } from "@/components/ui/modal"; -import { usePanelStore } from "@/stores/panel-store"; -import { getHostRuntimeStore } from "@/runtime/host-runtime"; -import { router } from "expo-router"; -import type { WorkspaceProjectDescriptorPayload } from "@getpaseo/protocol/messages"; -import { - ArrowLeft, - Folder, - FolderOpen, - FolderPlus, - HardDrive, - Plus, - Search, - Server, -} from "lucide-react-native"; -import { - createElement, - useCallback, - useEffect, - useMemo, - useRef, - useState, - type ComponentType, - type RefObject, -} from "react"; -import { Pressable, ScrollView, Text, View, type PressableStateCallbackType } from "react-native"; -import { - EditingTextInput as TextInput, - type EditingTextInputHandle, -} from "@/components/ui/text-input"; -import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import { GitHubIcon } from "@/components/icons/github-icon"; -import { - applyAvailableAddProjectHosts, - backAddProjectPage, - chooseAddProjectHost, - currentAddProjectPage, - moveAddProjectSelection, - openAddProjectFlow, - openDirectorySearchPage, - openGithubLocationPage, - openGithubSearchPage, - openNewDirectoryNamePage, - openNewDirectoryParentPage, - setAddProjectActiveIndex, - setAddProjectPageInput, - setNewDirectoryName, - updateCurrentAddProjectPage, - type AddProjectFlowState, - type AddProjectHost, - type AddProjectPage, - type GithubRepositoryChoice, -} from "@/add-project-flow/model"; -import { - buildAddProjectMethods, - addProjectMethodEmptyText, - buildCloneLocationOptions, - buildManualGithubRepositoryChoices, - buildSuggestedParentDirectories, - filterAddProjectHosts, - joinDirectoryPath, - pathBaseName, - type AddProjectMethodId, -} from "@/add-project-flow/options"; -import { - buildProjectPickerOptions, - type ProjectPickerOption, -} from "@/components/project-picker-options"; -import { Shortcut } from "@/components/ui/shortcut"; -import { useRevealActiveItem } from "@/components/ui/scroll-reveal"; -import { useHardwareKeyboardPresent } from "@/keyboard"; -import { getIsElectronRuntime } from "@/constants/layout"; -import { isWeb } from "@/constants/platform"; -import { pickDirectory } from "@/desktop/pick-directory"; -import { useFetchQuery } from "@/data/query"; -import { getOpenProjectFailureReason, registerProjectDescriptor } from "@/hooks/open-project"; -import { useIsLocalDaemon, useLocalDaemonServerId } from "@/hooks/use-is-local-daemon"; -import { useCloneGithubProject, useOpenProject } from "@/hooks/use-open-project"; -import { OverlayLayerProvider, useGlobalOverlayLayer } from "@/lib/overlay-root"; -import { - useHosts, - useHostRuntimeClient, - useHostRuntimeConnectionStatuses, -} from "@/runtime/host-runtime"; -import { useHostFeatureMap } from "@/runtime/host-features"; -import { useSessionStore } from "@/stores/session-store"; -import { useRecommendedProjectPaths } from "@/stores/session-store-hooks"; -import type { AddProjectFlowRequest } from "@/stores/add-project-flow-store"; -import type { Theme } from "@/styles/theme"; -import { shortenPath } from "@/utils/shorten-path"; -import { buildNewWorkspaceRoute } from "@/utils/host-routes"; - -interface AddProjectFlowProps { - request: AddProjectFlowRequest; - onClose: () => void; -} - -interface FlowRowOption { - id: string; - title: string; - subtitle: string | null; - icon: ComponentType<{ size?: number; color?: string }>; - disabled?: boolean; - testID: string; - select: () => void; -} - -type GithubLocationPage = Extract; - -interface FlowIconProps { - icon: ComponentType<{ size?: number; color?: string }>; - size?: number; - color?: string; -} - -function FlowIcon({ icon: Icon, size, color }: FlowIconProps) { - return ; -} - -const MutedFlowIcon = withUnistyles(FlowIcon, (theme) => ({ - color: theme.colors.foregroundMuted, -})); -const ThemedArrowLeft = withUnistyles(ArrowLeft); -const ThemedTextInput = withUnistyles(TextInput, (theme) => ({ - placeholderTextColor: theme.colors.foregroundMuted, -})); - -const foregroundColorMapping = (theme: Theme) => ({ color: theme.colors.foreground }); -const foregroundMutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); - -const lastCloneParentByHost = new Map(); -const EMPTY_PATHS: string[] = []; -const NAVIGATION_HINT_KEYS = ["Up", "Down"]; -const SELECT_HINT_KEYS = ["Enter"]; -const ESCAPE_HINT_KEYS = ["Esc"]; - -function FlowBackButton({ onPress }: { onPress: () => void }) { - return ( - - {({ hovered, pressed }) => ( - - )} - - ); -} - -function methodIcon(method: AddProjectMethodId): FlowRowOption["icon"] { - if (method === "github") return GitHubIcon; - if (method === "browse") return FolderOpen; - if (method === "new-directory") return FolderPlus; - return Search; -} - -function directoryOptionSubtitle(option: ProjectPickerOption, shortPath: string): string | null { - if (option.kind === "path") return "Open this path"; - if (shortPath === option.path) return null; - return option.path; -} - -function progressText(page: AddProjectPage): string { - if (page.kind === "github-location") return "Cloning project..."; - if (page.kind === "new-directory-name") return "Creating directory..."; - return "Adding project..."; -} - -function emptyText(page: AddProjectPage, host: AddProjectHost | null): string { - if (page.kind === "host") return "No connected hosts"; - if (page.kind === "github-search") return "Enter a GitHub URL or owner/repo"; - if (page.kind === "method") return addProjectMethodEmptyText(host); - return "No matching options"; -} - -interface QueryErrorInput { - searchesDirectories: boolean; - directoryFailed: boolean; - githubFailed: boolean; - githubAvailable: boolean | null; - githubError: string | null; -} - -function queryErrorText(input: QueryErrorInput): string | null { - if (input.searchesDirectories && input.directoryFailed) return "Unable to search directories"; - if (input.githubFailed) return "Unable to search GitHub repositories"; - if (input.githubError) return input.githubError; - if (input.githubAvailable === false) return input.githubError ?? "GitHub search is unavailable"; - return null; -} - -function pageHostId(page: AddProjectPage): string | null { - return page.kind === "host" ? null : page.hostId; -} - -function pageTitle(page: AddProjectPage): string { - switch (page.kind) { - case "host": - return "Choose host"; - case "method": - return "Add project"; - case "directory-search": - return "Search for directory"; - case "github-search": - return "Clone from GitHub"; - case "github-location": - return "Choose destination"; - case "new-directory-parent": - return "Choose parent directory"; - case "new-directory-name": - return "Name directory"; - } -} - -type AddProjectInputPage = Exclude; - -function pagePlaceholder(page: AddProjectInputPage): string { - switch (page.kind) { - case "host": - return "Search hosts..."; - case "directory-search": - return "Search directories or enter a path..."; - case "github-search": - return "Search or enter a GitHub repository..."; - case "github-location": - case "new-directory-parent": - return "Search parent directories or enter a path..."; - case "new-directory-name": - return "Directory name"; - } -} - -function pageInput(page: AddProjectInputPage): string { - return page.kind === "new-directory-name" ? page.name : page.query; -} - -function pathTestId(path: string): string { - return `add-project-flow-path-${encodeURIComponent(path)}`; -} - -function FlowRow({ - option, - active, - activeItemRef, - onRowLayout, -}: { - option: FlowRowOption; - active: boolean; - activeItemRef: RefObject; - onRowLayout: () => void; -}) { - const accessibilityState = useMemo( - () => ({ disabled: option.disabled === true, selected: active }), - [active, option.disabled], - ); - const rowStyle = useCallback( - ({ hovered = false, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [ - styles.row, - (active || hovered || pressed) && styles.rowActive, - option.disabled && styles.disabled, - ], - [active, option.disabled], - ); - return ( - - - - - - - {option.title} - - {option.subtitle ? ( - - {option.subtitle} - - ) : null} - - - ); -} - -function FlowHint({ keys, action }: { keys: string[]; action: string }) { - const shortcutsAvailable = useHardwareKeyboardPresent(); - if (!shortcutsAvailable) return null; - - return ( - - - {action} - - ); -} - -function setPageStatus( - state: AddProjectFlowState, - kind: AddProjectPage["kind"], - input: { isSubmitting?: boolean; error?: string | null }, -): AddProjectFlowState { - return updateCurrentAddProjectPage(state, (page) => - page.kind === kind ? { ...page, ...input } : page, - ); -} - -// The product flow is intentionally one cohesive page-stack state machine. -// eslint-disable-next-line complexity -export function AddProjectFlow({ request, onClose }: AddProjectFlowProps) { - const addHost = useAddHost(); - const hosts = useHosts(); - const hostIds = useMemo(() => hosts.map((host) => host.serverId), [hosts]); - const connectionStatuses = useHostRuntimeConnectionStatuses(hostIds); - const projectAddByHost = useHostFeatureMap(hostIds, "projectAdd"); - // COMPAT(stableProjectIdentity): added in v0.1.109, remove gate after 2027-01-15. - const stableProjectIdentityByHost = useHostFeatureMap(hostIds, "stableProjectIdentity"); - // COMPAT(projectGithubClone): added in v0.1.108, remove gate after 2027-01-15. - const githubCloneByHost = useHostFeatureMap(hostIds, "projectGithubClone"); - // COMPAT(workspaceGithubRepositorySearch): added in v0.1.108, remove gate after 2027-01-15. - const githubSearchByHost = useHostFeatureMap(hostIds, "workspaceGithubRepositorySearch"); - // COMPAT(projectCreateDirectory): added in v0.1.108, remove gate after 2027-01-15. - const createDirectoryByHost = useHostFeatureMap(hostIds, "projectCreateDirectory"); - const localServerId = useLocalDaemonServerId(); - const availableHosts = useMemo( - () => - hosts.flatMap((host) => { - if (connectionStatuses.get(host.serverId) !== "online") return []; - const canAddProject = - projectAddByHost.get(host.serverId) === true && - stableProjectIdentityByHost.get(host.serverId) === true; - return [ - { - serverId: host.serverId, - label: host.label, - canAddProject, - canBrowse: canAddProject && getIsElectronRuntime() && localServerId === host.serverId, - canCloneGithubRepositories: githubCloneByHost.get(host.serverId) === true, - canSearchGithubRepositories: githubSearchByHost.get(host.serverId) === true, - canCreateDirectory: createDirectoryByHost.get(host.serverId) === true, - }, - ]; - }), - [ - connectionStatuses, - createDirectoryByHost, - githubCloneByHost, - githubSearchByHost, - hosts, - localServerId, - projectAddByHost, - stableProjectIdentityByHost, - ], - ); - const [state, setState] = useState(() => - openAddProjectFlow({ - hosts: availableHosts, - ...(request.preferredHostId ? { preferredHostId: request.preferredHostId } : {}), - }), - ); - const page = currentAddProjectPage(state); - const hostId = pageHostId(page); - const host = hostId ? state.hosts.find((candidate) => candidate.serverId === hostId) : null; - const client = useHostRuntimeClient(hostId ?? ""); - const isLocalDaemon = useIsLocalDaemon(hostId ?? ""); - const recommendedPaths = useRecommendedProjectPaths(hostId); - const openProject = useOpenProject(hostId); - const cloneGithubProject = useCloneGithubProject(hostId); - const upsertProject = useCallback( - ( - targetServerId: string, - project: Parameters["acceptProjectSnapshot"]>[1], - ) => { - getHostRuntimeStore().acceptProjectSnapshot(targetServerId, project); - }, - [], - ); - const setHasHydratedWorkspaces = useSessionStore((store) => store.setHasHydratedWorkspaces); - const inputRef = useRef(null); - const resultsRef = useRef(null); - const submissionInFlightRef = useRef(false); - const browseInFlightRef = useRef(false); - const query = page.kind === "new-directory-name" || page.kind === "method" ? "" : page.query; - const pageInputValueRef = useRef(page.kind === "method" ? "" : pageInput(page)); - pageInputValueRef.current = page.kind === "method" ? "" : pageInput(page); - const [debouncedQuery, setDebouncedQuery] = useState(query); - - useEffect(() => { - setState((current) => - applyAvailableAddProjectHosts(current, availableHosts, request.preferredHostId), - ); - }, [availableHosts, request.preferredHostId]); - - useEffect(() => { - const timer = setTimeout(() => setDebouncedQuery(query), 250); - return () => clearTimeout(timer); - }, [query]); - - useEffect(() => { - inputRef.current?.replaceText(pageInputValueRef.current); - const timer = setTimeout(() => inputRef.current?.focus(), 0); - return () => clearTimeout(timer); - }, [page.kind]); - - const searchesDirectories = - page.kind === "directory-search" || - page.kind === "github-location" || - page.kind === "new-directory-parent"; - const directoryQuery = useFetchQuery({ - queryKey: ["add-project-flow-directories", hostId, debouncedQuery], - queryFn: async () => { - if (!client) return { query: debouncedQuery, paths: [] as string[] }; - const payload = await client.getDirectorySuggestions({ - query: debouncedQuery, - includeDirectories: true, - includeFiles: false, - limit: 30, - }); - return { - query: debouncedQuery, - paths: - payload.entries?.flatMap((entry) => (entry.kind === "directory" ? [entry.path] : [])) ?? - [], - }; - }, - enabled: Boolean(client && searchesDirectories), - dataShape: "value", - retry: false, - staleTimeMs: 15_000, - }); - const githubQuery = useFetchQuery({ - queryKey: ["add-project-flow-github", hostId, debouncedQuery], - queryFn: async () => { - if (!client) throw new Error("Host is unavailable"); - const payload = await client.searchGithubRepositories({ query: debouncedQuery, limit: 30 }); - return { query: debouncedQuery, payload }; - }, - enabled: Boolean(client && page.kind === "github-search" && host?.canSearchGithubRepositories), - dataShape: "value", - retry: false, - staleTimeMs: 15_000, - }); - - const handleBack = useCallback(() => { - const previous = backAddProjectPage(state); - if (previous) setState(previous); - else onClose(); - }, [onClose, state]); - - const openNewWorkspaceForProject = useCallback( - (serverId: string, project: WorkspaceProjectDescriptorPayload) => { - onClose(); - usePanelStore.getState().showMobileAgent(); - router.push( - buildNewWorkspaceRoute({ - serverId, - projectId: project.projectId, - sourceDirectory: project.projectRootPath, - displayName: project.projectDisplayName, - }), - ); - }, - [onClose], - ); - - const openAddedProject = useCallback( - async (path: string, sourceKind: "directory-search" | "method") => { - if (!hostId || submissionInFlightRef.current) return; - submissionInFlightRef.current = true; - setState((current) => - setPageStatus(current, sourceKind, { isSubmitting: true, error: null }), - ); - try { - const result = await openProject(path); - if (result.ok) { - openNewWorkspaceForProject(hostId, result.project); - return; - } - const reason = getOpenProjectFailureReason(result); - const message = - reason === "directory_not_found" ? "Directory not found" : "Unable to add project"; - setState((current) => - setPageStatus(current, sourceKind, { isSubmitting: false, error: message }), - ); - } catch { - setState((current) => - setPageStatus(current, sourceKind, { - isSubmitting: false, - error: "Unable to add project", - }), - ); - } finally { - submissionInFlightRef.current = false; - } - }, - [hostId, openNewWorkspaceForProject, openProject], - ); - - const browse = useCallback(async () => { - if (!hostId || !isLocalDaemon || browseInFlightRef.current) return; - browseInFlightRef.current = true; - try { - const path = await pickDirectory(); - if (path) await openAddedProject(path, "method"); - } catch { - setState((current) => - setPageStatus(current, "method", { error: "Unable to browse for a directory" }), - ); - } finally { - browseInFlightRef.current = false; - } - }, [hostId, isLocalDaemon, openAddedProject]); - - const selectMethod = useCallback( - (method: AddProjectMethodId) => { - if (!hostId) return; - if (method === "directory-search") { - setState((current) => openDirectorySearchPage(current, hostId)); - } else if (method === "browse") { - void browse(); - } else if (method === "github") { - setState((current) => openGithubSearchPage(current, hostId)); - } else { - setState((current) => openNewDirectoryParentPage(current, hostId)); - } - }, - [browse, hostId], - ); - - const directoryPaths = useMemo( - () => (directoryQuery.data?.query === query ? directoryQuery.data.paths : EMPTY_PATHS), - [directoryQuery.data, query], - ); - const pathOptions = useMemo( - () => - buildProjectPickerOptions({ - recommendedPaths, - serverPaths: directoryPaths, - query, - }), - [directoryPaths, query, recommendedPaths], - ); - const cloneRepository = useCallback( - async (locationPage: GithubLocationPage, parentPath: string) => { - if (submissionInFlightRef.current) return; - submissionInFlightRef.current = true; - setState((current) => - setPageStatus(current, "github-location", { isSubmitting: true, error: null }), - ); - try { - const result = await cloneGithubProject( - locationPage.repository.cloneUrl, - parentPath, - locationPage.repository.cloneProtocol, - ); - if (result.ok) { - lastCloneParentByHost.set(locationPage.hostId, parentPath); - openNewWorkspaceForProject(locationPage.hostId, result.project); - return; - } - setState((current) => - setPageStatus(current, "github-location", { - isSubmitting: false, - error: result.error ?? "Unable to clone repository", - }), - ); - } catch (error) { - setState((current) => - setPageStatus(current, "github-location", { - isSubmitting: false, - error: error instanceof Error ? error.message : "Unable to clone repository", - }), - ); - } finally { - submissionInFlightRef.current = false; - } - }, - [cloneGithubProject, openNewWorkspaceForProject], - ); - const rows = useMemo(() => { - if (page.kind === "host") { - const choices = filterAddProjectHosts(state.hosts, page.query).map( - (choice) => ({ - id: choice.serverId, - title: choice.label, - subtitle: choice.serverId, - icon: Server, - testID: `add-project-flow-host-${choice.serverId}`, - select: () => setState((current) => chooseAddProjectHost(current, choice.serverId)), - }), - ); - if (state.hosts.length === 0) { - choices.push({ - id: "add-host", - title: "Add host", - subtitle: "No connected hosts", - icon: Plus, - testID: "add-project-flow-add-host", - select: () => { - // The native project Modal must release its window before the root sheet opens. - onClose(); - addHost(); - }, - }); - } - return choices; - } - if (page.kind === "method") { - if (!host) return []; - return buildAddProjectMethods(host).map((method) => ({ - id: method.id, - title: method.label, - subtitle: method.description, - icon: methodIcon(method.id), - disabled: method.disabled, - testID: `add-project-flow-method-${method.id}`, - select: () => selectMethod(method.id), - })); - } - if (page.kind === "directory-search") { - return pathOptions.map((option) => { - const shortPath = shortenPath(option.path); - return { - id: option.path, - title: shortPath, - subtitle: directoryOptionSubtitle(option, shortPath), - icon: Folder, - testID: pathTestId(option.path), - select: () => void openAddedProject(option.path, "directory-search"), - }; - }); - } - if (page.kind === "github-search") { - const search = githubQuery.data?.query === page.query ? githubQuery.data.payload : null; - const repositories = search?.repositories ?? []; - const normalizedQuery = page.query.trim().toLowerCase(); - const hasExactSearchResult = repositories.some( - (repository) => - repository.nameWithOwner.toLowerCase() === normalizedQuery || - repository.cloneUrl.toLowerCase() === normalizedQuery, - ); - const manualRepositories = hasExactSearchResult - ? [] - : buildManualGithubRepositoryChoices(page.query); - const repositoryChoices: GithubRepositoryChoice[] = [...manualRepositories, ...repositories]; - return repositoryChoices.map((repository) => ({ - id: repository.id, - title: repository.cloneProtocol - ? `${repository.nameWithOwner} via ${repository.cloneProtocol.toUpperCase()}` - : repository.nameWithOwner, - subtitle: repository.description, - icon: GitHubIcon, - testID: `add-project-flow-repository-${repository.id}`, - select: () => - setState((current) => openGithubLocationPage(current, page.hostId, repository)), - })); - } - if (page.kind === "github-location") { - const repositoryName = pathBaseName(page.repository.nameWithOwner); - const lastParent = lastCloneParentByHost.get(page.hostId); - const parents = buildSuggestedParentDirectories(recommendedPaths); - const orderedParents = lastParent - ? [lastParent, ...parents.filter((parent) => parent !== lastParent)] - : parents; - const filteredParents = buildProjectPickerOptions({ - recommendedPaths: orderedParents, - serverPaths: directoryPaths, - query: page.query, - }).map((option) => option.path); - return buildCloneLocationOptions({ - parents: filteredParents, - repositoryName, - existingPaths: [...recommendedPaths, ...directoryPaths], - }).map((option) => ({ - id: option.id, - title: shortenPath(option.displayPath), - subtitle: option.secondaryText, - icon: HardDrive, - disabled: option.disabled, - testID: pathTestId(option.displayPath), - select: () => void cloneRepository(page, option.path), - })); - } - if (page.kind === "new-directory-parent") { - return pathOptions.map((option) => ({ - id: option.path, - title: shortenPath(option.path), - subtitle: option.kind === "path" ? "Use this parent" : option.path, - icon: Folder, - testID: pathTestId(option.path), - select: () => - setState((current) => openNewDirectoryNamePage(current, page.hostId, option.path)), - })); - } - return []; - }, [ - cloneRepository, - directoryPaths, - githubQuery.data, - host, - addHost, - onClose, - openAddedProject, - page, - pathOptions, - recommendedPaths, - selectMethod, - state.hosts, - ]); - - const activeIndex = rows.length === 0 ? 0 : Math.min(page.activeIndex, rows.length - 1); - const rowListKey = useMemo(() => rows.map((row) => row.id).join("\u0000"), [rows]); - const { activeItemRef, contentRef, onItemLayout, onViewportLayout, onScroll } = - useRevealActiveItem({ - activeIndex, - listKey: rowListKey, - scrollRef: resultsRef, - }); - const createDirectory = useCallback(async () => { - if (page.kind !== "new-directory-name" || !client) return; - const name = page.name.trim(); - if (!name || name === "." || name === ".." || /[\\/]/.test(name)) { - setState((current) => - setPageStatus(current, "new-directory-name", { error: "Enter a directory name" }), - ); - return; - } - if (submissionInFlightRef.current) return; - submissionInFlightRef.current = true; - setState((current) => - setPageStatus(current, "new-directory-name", { isSubmitting: true, error: null }), - ); - try { - const payload = await client.createProjectDirectory({ - parentPath: page.parentPath, - name, - }); - if (payload.error || !payload.project) { - setState((current) => - setPageStatus(current, "new-directory-name", { - isSubmitting: false, - error: payload.error ?? "Unable to create directory", - }), - ); - return; - } - registerProjectDescriptor({ - serverId: page.hostId, - project: payload.project, - upsertProject, - setHasHydratedWorkspaces, - }); - openNewWorkspaceForProject(page.hostId, payload.project); - } catch { - setState((current) => - setPageStatus(current, "new-directory-name", { - isSubmitting: false, - error: "Unable to create directory", - }), - ); - } finally { - submissionInFlightRef.current = false; - } - }, [client, openNewWorkspaceForProject, page, setHasHydratedWorkspaces, upsertProject]); - - const submitActive = useCallback(() => { - if (page.kind === "new-directory-name") { - void createDirectory(); - return; - } - const option = rows[activeIndex]; - if (option && !option.disabled) option.select(); - }, [activeIndex, createDirectory, page.kind, rows]); - - const handleKey = useCallback( - (key: string): boolean => { - if (key === "Escape") { - handleBack(); - return true; - } - if (key === "Enter") { - submitActive(); - return true; - } - if (key !== "ArrowDown" && key !== "ArrowUp") return false; - const next = moveAddProjectSelection( - activeIndex, - rows.map((row) => row.disabled !== true), - key === "ArrowDown" ? "next" : "previous", - ); - setState((current) => setAddProjectActiveIndex(current, next)); - return true; - }, - [activeIndex, handleBack, rows, submitActive], - ); - - const modalLayer = useGlobalOverlayLayer("modal", true); - const handleOverlayKeyDown = useCallback( - (event: KeyboardInputEvent) => { - if (!handleKey(event.key)) return false; - event.preventDefault(); - return true; - }, - [handleKey], - ); - const setOverlayScope = useOverlayRegistration({ - keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"], - active: true, - layer: modalLayer, - onKeyDown: handleOverlayKeyDown, - }); - - const handleInputChange = useCallback((value: string) => { - setState((current) => - currentAddProjectPage(current).kind === "new-directory-name" - ? setNewDirectoryName(current, value) - : setAddProjectPageInput(current, value), - ); - }, []); - const isSubmitting = "isSubmitting" in page && page.isSubmitting; - const currentGithubSearch = - page.kind === "github-search" && githubQuery.data?.query === page.query - ? githubQuery.data.payload - : null; - const loading = - (searchesDirectories && (query !== debouncedQuery || directoryQuery.isFetching)) || - (page.kind === "github-search" && - host?.canSearchGithubRepositories === true && - (query !== debouncedQuery || githubQuery.isFetching)); - const queryError = queryErrorText({ - searchesDirectories, - directoryFailed: directoryQuery.isError, - githubFailed: page.kind === "github-search" && githubQuery.isError, - githubAvailable: currentGithubSearch?.available ?? null, - githubError: currentGithubSearch?.error ?? null, - }); - const preview = - page.kind === "new-directory-name" && page.name.trim() - ? joinDirectoryPath(page.parentPath, page.name.trim()) - : null; - - const modal = ( - - - - - - - {state.pages.length > 1 ? : null} - - - {pageTitle(page)} - - {host ? ( - - {host.label} - - ) : null} - - - {page.kind !== "method" ? ( - - ) : null} - - - - {preview ? ( - - {shortenPath(preview)} - - ) : null} - {isSubmitting ? ( - - {progressText(page)} - - ) : null} - {!isSubmitting && page.error ? ( - - {page.error} - - ) : null} - {!isSubmitting && queryError ? ( - - {queryError} - - ) : null} - {!isSubmitting && loading ? ( - - Loading... - - ) : null} - {!isSubmitting && - (!loading || page.kind === "github-search") && - (!queryError || page.kind === "github-search") - ? rows.map((option, index) => ( - - )) - : null} - {!isSubmitting && - !loading && - !queryError && - rows.length === 0 && - page.kind !== "new-directory-name" ? ( - - {emptyText(page, host ?? null)} - - ) : null} - - - - - - 1 ? "Back" : "Close"} /> - - - - - ); - - return createElement(OverlayLayerProvider, { layer: modalLayer }, modal); -} - -const styles = StyleSheet.create((theme) => ({ - overlay: { - flex: 1, - justifyContent: "flex-start", - alignItems: "center", - paddingTop: theme.spacing[12], - }, - backdrop: { - ...StyleSheet.absoluteFill, - backgroundColor: "rgba(0, 0, 0, 0.5)", - }, - panel: { - width: 640, - maxWidth: "92%", - maxHeight: "80%", - borderWidth: 1, - borderColor: theme.colors.border, - borderRadius: theme.borderRadius.lg, - backgroundColor: theme.colors.surface0, - overflow: "hidden", - ...theme.shadow.lg, - }, - header: { - flexShrink: 0, - paddingHorizontal: theme.spacing[4], - paddingTop: theme.spacing[2], - paddingBottom: theme.spacing[3], - borderBottomWidth: 1, - borderBottomColor: theme.colors.border, - gap: theme.spacing[2], - }, - titleRow: { - minHeight: theme.iconSize.lg, - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[2], - }, - backButton: { - width: 18, - height: theme.iconSize.lg, - alignItems: "center", - justifyContent: "center", - flexShrink: 0, - }, - titleGroup: { - flex: 1, - minWidth: 0, - flexDirection: "row", - alignItems: "baseline", - gap: theme.spacing[2], - }, - title: { - minWidth: 0, - flexShrink: 1, - color: theme.colors.foreground, - fontSize: theme.fontSize.sm, - fontWeight: theme.fontWeight.normal, - }, - hostContext: { - minWidth: 0, - flexShrink: 1, - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.sm, - fontWeight: theme.fontWeight.normal, - }, - input: { - color: theme.colors.foreground, - fontSize: theme.fontSize.base, - paddingVertical: theme.spacing[1], - outlineStyle: "none", - } as object, - results: { flexGrow: 0, flexShrink: 1, minHeight: 0 }, - resultsContent: { paddingVertical: theme.spacing[2] }, - row: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[3], - paddingHorizontal: theme.spacing[4], - paddingVertical: theme.spacing[2], - }, - rowActive: { backgroundColor: theme.colors.surface1 }, - disabled: { opacity: theme.opacity[50] }, - iconSlot: { width: 18, alignItems: "center" }, - rowText: { flex: 1, minWidth: 0 }, - rowTitle: { color: theme.colors.foreground, fontSize: theme.fontSize.base }, - rowSubtitle: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.sm, marginTop: 2 }, - preview: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - paddingHorizontal: theme.spacing[4], - paddingVertical: theme.spacing[2], - }, - stateText: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - paddingHorizontal: theme.spacing[4], - paddingVertical: theme.spacing[4], - }, - errorText: { - color: theme.colors.destructive, - fontSize: theme.fontSize.sm, - paddingHorizontal: theme.spacing[4], - paddingVertical: theme.spacing[3], - }, - footer: { - flexShrink: 0, - flexDirection: "row", - gap: theme.spacing[4], - alignItems: "center", - flexWrap: "wrap", - paddingHorizontal: theme.spacing[4], - paddingVertical: theme.spacing[2], - borderTopWidth: 1, - borderTopColor: theme.colors.border, - }, - footerHint: { - flexDirection: "row", - alignItems: "center", - gap: theme.spacing[1.5], - }, - footerKeyText: { - color: theme.colors.foreground, - fontSize: theme.fontSize.sm, - }, - footerAction: { - color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.sm, - }, -})); diff --git a/packages/app/src/components/ui/combobox.tsx b/packages/app/src/components/ui/combobox.tsx index 8d7c024b67..339c8b5285 100644 --- a/packages/app/src/components/ui/combobox.tsx +++ b/packages/app/src/components/ui/combobox.tsx @@ -78,7 +78,7 @@ const FOCUSED_COMBOBOX_ACTION_SELECTOR = '[data-combobox-trailing-action] button, [data-combobox-trailing-action] [role="button"], [data-combobox-footer] button, [data-combobox-footer] [role="button"]'; export type ComboboxOption = ComboboxOptionModel; -export type ComboboxDesktopPlacement = "top-start" | "bottom-start"; +export type ComboboxDesktopPlacement = "top-start" | "bottom-start" | "bottom-end"; export interface ComboboxProps { options: ComboboxOption[]; @@ -94,6 +94,11 @@ export interface ComboboxProps { searchable?: boolean; /** The caller answers the search query itself, so the options are shown as given. */ remoteSearch?: boolean; + /** + * With `remoteSearch`, the options still answer an earlier query. No option is picked until + * the user moves to one, so Enter cannot confirm a row the new query may not match. + */ + remoteSearchPending?: boolean; placeholder?: string; searchPlaceholder?: string; emptyText?: string; @@ -610,6 +615,7 @@ interface DesktopKeyHandlerInput { isOpen: boolean; orderedVisibleOptions: ComboboxOption[]; activeIndex: number; + remoteSearchPending: boolean; setActiveIndex: React.Dispatch>; handleSelect: (id: string) => void; handleClose: () => void; @@ -622,7 +628,9 @@ function handleDesktopArrowKey(input: DesktopKeyHandlerInput, key: "ArrowDown" | function handleDesktopEnterKey(input: DesktopKeyHandlerInput) { if (input.orderedVisibleOptions.length === 0) return; const { activeIndex, orderedVisibleOptions } = input; - const index = activeIndex >= 0 && activeIndex < orderedVisibleOptions.length ? activeIndex : 0; + const picked = activeIndex >= 0 && activeIndex < orderedVisibleOptions.length; + if (!picked && input.remoteSearchPending) return; + const index = picked ? activeIndex : 0; input.handleSelect(orderedVisibleOptions[index].id); } @@ -678,18 +686,21 @@ function useActiveIndexSync( effectiveOptionsPosition: "below-search" | "above-search", normalizedSearch: string, value: string, + remoteSearchPending: boolean, setActiveIndex: React.Dispatch>, ) { useEffect(() => { if (!isOpen) return; if (!IS_WEB && isMobile) return; setActiveIndex( - resolveInitialActiveIndex( - orderedVisibleOptions, - effectiveOptionsPosition, - normalizedSearch, - value, - ), + remoteSearchPending + ? -1 + : resolveInitialActiveIndex( + orderedVisibleOptions, + effectiveOptionsPosition, + normalizedSearch, + value, + ), ); }, [ effectiveOptionsPosition, @@ -698,6 +709,7 @@ function useActiveIndexSync( normalizedSearch, value, orderedVisibleOptions, + remoteSearchPending, setActiveIndex, ]); } @@ -1398,6 +1410,7 @@ export function Combobox({ onSearchQueryChange, searchable = true, remoteSearch, + remoteSearchPending, placeholder, searchPlaceholder, emptyText, @@ -1616,6 +1629,7 @@ export function Combobox({ effectiveOptionsPosition, normalizedSearch, value, + remoteSearchPending === true, setActiveIndex, ); @@ -1663,6 +1677,7 @@ export function Combobox({ isOpen, orderedVisibleOptions, activeIndex, + remoteSearchPending: remoteSearchPending === true, setActiveIndex, handleSelect, handleClose, @@ -1671,7 +1686,7 @@ export function Combobox({ event, ); }, - [activeIndex, handleClose, handleSelect, isOpen, orderedVisibleOptions], + [activeIndex, handleClose, handleSelect, isOpen, orderedVisibleOptions, remoteSearchPending], ); useDismissKeyboardOnOpen(isOpen, isMobile); diff --git a/packages/app/src/components/ui/form-field.tsx b/packages/app/src/components/ui/form-field.tsx index a85d9a2712..f988707d0b 100644 --- a/packages/app/src/components/ui/form-field.tsx +++ b/packages/app/src/components/ui/form-field.tsx @@ -75,6 +75,10 @@ export function Field({ label, children, trailing, hint, error, testID }: FieldP type FormTextInputProps = AdaptiveTextInputProps & { size?: ControlSize; + /** A glyph inside the field before the text, such as a search icon. */ + leading?: ReactNode; + /** The value is rejected; the border and focus ring turn to the danger color. */ + invalid?: boolean; }; type FlatFormTextInputStyle = ViewStyle & TextStyle; @@ -166,7 +170,10 @@ function assignTextInputRef( } export const FormTextInput = forwardRef( - function FormTextInput({ size: sizeProp, style, onFocus, onBlur, editable, ...props }, ref) { + function FormTextInput( + { size: sizeProp, leading, invalid = false, style, onFocus, onBlur, editable, ...props }, + ref, + ) { const [focused, setFocused] = useState(false); const containedSize = useContainedControlSize(); const size = sizeProp ?? containedSize ?? "md"; @@ -202,6 +209,7 @@ export const FormTextInput = forwardRef [ formInputStyles.chrome, chromeSizeStyle, + leading ? formInputStyles.chromeWithLeading : null, resolveControlInteractionStyles( { controlRest: formInputStyles.controlRest, @@ -215,13 +223,15 @@ export const FormTextInput = forwardRef + {leading} { chrome: { backgroundColor: theme.colors.surface2, }, + chromeWithLeading: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, chromeSm: { ...geometry.fieldControlSm, }, @@ -289,6 +304,11 @@ const formInputStyles = StyleSheet.create((theme) => { controlDisabled: { ...geometry.controlDisabled, }, + // Matches the inline error under the field (docs/design.md, Errors). + controlInvalid: { + borderColor: theme.colors.palette.red[300], + outlineColor: theme.colors.palette.red[300], + }, input: { flex: 1, minWidth: 0, diff --git a/packages/app/src/components/ui/segmented-control.tsx b/packages/app/src/components/ui/segmented-control.tsx index e0221d56d1..3cb446ee86 100644 --- a/packages/app/src/components/ui/segmented-control.tsx +++ b/packages/app/src/components/ui/segmented-control.tsx @@ -29,6 +29,8 @@ interface SegmentedControlProps { onValueChange: (value: T) => void; size?: ControlSize; hideLabels?: boolean; + /** Share the container's width equally between the segments, for a control that heads a surface. */ + fill?: boolean; style?: StyleProp; testID?: string; } @@ -54,6 +56,7 @@ export function SegmentedControl({ onValueChange, size: sizeProp, hideLabels = false, + fill = false, style, testID, }: SegmentedControlProps) { @@ -85,6 +88,7 @@ export function SegmentedControl({ isSelected={isSelected} iconSize={iconSize} hideLabels={hideLabels} + fill={fill} segmentSizeStyle={segmentSizeStyle} labelSizeStyle={labelSizeStyle} currentValue={value} @@ -101,6 +105,7 @@ function SegmentItem({ isSelected, iconSize, hideLabels, + fill, segmentSizeStyle, labelSizeStyle, currentValue, @@ -110,6 +115,7 @@ function SegmentItem({ isSelected: boolean; iconSize: number; hideLabels: boolean; + fill: boolean; segmentSizeStyle: StyleProp; labelSizeStyle: StyleProp; currentValue: T | null; @@ -128,12 +134,13 @@ function SegmentItem({ ({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [ styles.segment, segmentSizeStyle, + fill && styles.segmentFill, isSelected && styles.segmentSelected, Boolean(hovered) && !isSelected && styles.segmentHover, pressed && !isSelected && styles.segmentPressed, option.disabled && styles.segmentDisabled, ], - [isSelected, option.disabled, segmentSizeStyle], + [fill, isSelected, option.disabled, segmentSizeStyle], ); const accessibilityState = useMemo( () => ({ selected: isSelected, disabled: option.disabled }), @@ -203,6 +210,12 @@ const styles = StyleSheet.create((theme) => { segmentMd: { ...geometry.segmentedSegmentMd, }, + segmentFill: { + flexGrow: 1, + flexBasis: 0, + flexShrink: 1, + minWidth: 0, + }, segmentSelected: { backgroundColor: theme.colors.surface3, }, diff --git a/packages/app/src/stores/add-project-flow-store.ts b/packages/app/src/stores/add-project-flow-store.ts index 49eabbb908..830bbb36d6 100644 --- a/packages/app/src/stores/add-project-flow-store.ts +++ b/packages/app/src/stores/add-project-flow-store.ts @@ -7,14 +7,18 @@ export interface AddProjectFlowRequest { interface AddProjectFlowStoreState { request: AddProjectFlowRequest | null; + /** The parent directory last used to clone or create a project, per host, for this session. */ + lastLocationByHost: Record; open: (preferredHostId?: string) => void; close: () => void; + rememberLocation: (hostId: string, location: string) => void; } let nextRequestId = 1; export const useAddProjectFlowStore = create((set) => ({ request: null, + lastLocationByHost: {}, open: (preferredHostId) => { set({ request: { @@ -24,4 +28,6 @@ export const useAddProjectFlowStore = create((set) => }); }, close: () => set({ request: null }), + rememberLocation: (hostId, location) => + set((state) => ({ lastLocationByHost: { ...state.lastLocationByHost, [hostId]: location } })), }));