mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 02:47:34 +00:00
Merge pull request #497 from nwparker/cloud/rr-c1-submit-validation
fix(cloud): RR-c1 submit-time validation for Orca Cloud on a folder (Neil)
This commit is contained in:
@@ -36,11 +36,8 @@ export function NewWorkspaceComposerFooter({
|
||||
}: NewWorkspaceComposerFooterProps): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
// RR-c1: why Create waits (a folder project on Orca Cloud), on hover and for screen readers.
|
||||
// RR-c1: set only after a Create stopped for it; the button stays enabled and points at the error.
|
||||
const needsRepo = Boolean(cloudStart?.needsGitHubRepo)
|
||||
const needsRepoReason = t(
|
||||
'components.newWorkspace.cloudOnly.needsRepository',
|
||||
'Orca Cloud needs a GitHub repository.'
|
||||
)
|
||||
return (
|
||||
<>
|
||||
{createError ? (
|
||||
@@ -77,7 +74,7 @@ export function NewWorkspaceComposerFooter({
|
||||
</span>
|
||||
</button>
|
||||
) : null}
|
||||
<span className="ml-auto shrink-0" title={needsRepo ? needsRepoReason : undefined}>
|
||||
<span className="ml-auto shrink-0">
|
||||
<Button
|
||||
onClick={() => void onCreate()}
|
||||
disabled={createDisabled}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { OrcaCloudNeedsRepoLine } from './run-on/OrcaCloudNeedsRepoLine'
|
||||
import { ORCA_CLOUD_NEEDS_REPO_ID } from './run-on/cloud-start-view'
|
||||
import { OrcaCloudWallLine } from './run-on/OrcaCloudWallLine'
|
||||
import React from 'react'
|
||||
import { FolderPlus, LoaderCircle, PlugZap } from 'lucide-react'
|
||||
@@ -104,6 +105,8 @@ export function NewWorkspaceComposerProjectSection({
|
||||
const t = useTranslate()
|
||||
// RR-c1: "Choose repository" opens the Project picker at its GitHub repositories.
|
||||
const [repoPickerSignal, setRepoPickerSignal] = React.useState(0)
|
||||
// RR-c1: each stopped Create moves focus to Project (quietly), where the error is.
|
||||
const needsRepo = cloudStart?.needsGitHubRepo ?? null
|
||||
return (
|
||||
<fieldset disabled={disabled} className="space-y-1">
|
||||
{/* One row, two equal columns: Project | Run on. Picking a target never changes the rows
|
||||
@@ -166,17 +169,20 @@ export function NewWorkspaceComposerProjectSection({
|
||||
t('auto.components.NewWorkspaceComposerCard.dccd26d4e4', 'Choose project')
|
||||
}
|
||||
triggerClassName="h-9 w-full border-input text-sm focus-visible:border-focus-ring focus-visible:ring-1 focus-visible:ring-focus-ring"
|
||||
invalid={Boolean(projectError)}
|
||||
describedBy={projectDescriptionId}
|
||||
invalid={Boolean(projectError) || Boolean(needsRepo)}
|
||||
describedBy={
|
||||
!projectError && needsRepo ? ORCA_CLOUD_NEEDS_REPO_ID : projectDescriptionId
|
||||
}
|
||||
openSignal={repoPickerSignal}
|
||||
focusSignal={needsRepo?.attempt ?? 0}
|
||||
/>
|
||||
{projectError ? (
|
||||
<p id={projectDescriptionId} className="text-[11px] text-destructive">
|
||||
{projectError}
|
||||
</p>
|
||||
) : cloudStart?.needsGitHubRepo ? (
|
||||
) : needsRepo ? (
|
||||
<OrcaCloudNeedsRepoLine
|
||||
hasRepos={cloudStart.needsGitHubRepo.hasRepos}
|
||||
hasRepos={needsRepo.hasRepos}
|
||||
onChooseRepository={() => setRepoPickerSignal((signal) => signal + 1)}
|
||||
onAddRepository={onAddProject}
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ImeInput } from '@/lib/text-input/ime/ime-text-field'
|
||||
import React, { useCallback, useMemo, useRef, useState } from 'react'
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { ChevronDown, FolderPlus, Github } from 'lucide-react'
|
||||
import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover'
|
||||
import { cn } from '@/lib/utils'
|
||||
@@ -46,6 +46,11 @@ type ProjectComboboxProps = {
|
||||
onShowMoreCloudRepos?: (() => void) | null
|
||||
/** Bumped to open the list at its cloud-only section ("Choose a GitHub repository"). */
|
||||
openSignal?: number
|
||||
/**
|
||||
* Bumped to move focus here quietly (RR-c1: a stopped Create points at the field's error): no
|
||||
* path tooltip on that focus, since the error is already speaking. Hover and Tab still show it.
|
||||
*/
|
||||
focusSignal?: number
|
||||
}
|
||||
|
||||
const ADD_PROJECT_KEY = 'add-project'
|
||||
@@ -67,10 +72,12 @@ export default function ProjectCombobox({
|
||||
onCloudRepoSelected,
|
||||
onMoreCloudAccess,
|
||||
onShowMoreCloudRepos = null,
|
||||
openSignal = 0
|
||||
openSignal = 0,
|
||||
focusSignal = 0
|
||||
}: ProjectComboboxProps): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const [tooltipOpen, setTooltipOpen] = useState(false)
|
||||
const quietFocus = useRef(false)
|
||||
const contentRef = useRef<HTMLDivElement>(null)
|
||||
const recentIds = useRecentProjectIds()
|
||||
// Derive keys from the displayed sections: folder grouping changes raw rank order, so keyboard selection must follow what users see.
|
||||
@@ -117,6 +124,13 @@ export default function ProjectCombobox({
|
||||
() => sectionProjectOptions(matches, query, recentIds),
|
||||
[matches, query, recentIds]
|
||||
)
|
||||
// RR-c1: a stopped Create focuses the field without its path tooltip.
|
||||
useEffect(() => {
|
||||
if (focusSignal > 0) {
|
||||
quietFocus.current = true
|
||||
inputRef.current?.focus()
|
||||
}
|
||||
}, [focusSignal, inputRef])
|
||||
// "Choose a GitHub repository": open with the first cloud-only row armed (scrolled into view).
|
||||
useOpenOnSignal(openSignal, () => {
|
||||
inputRef.current?.focus()
|
||||
@@ -185,18 +199,27 @@ export default function ProjectCombobox({
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={handleOpenChange}>
|
||||
<Tooltip open={tooltipOpen && committed && !open} onOpenChange={setTooltipOpen}>
|
||||
<Tooltip
|
||||
open={tooltipOpen && committed && !open}
|
||||
onOpenChange={(next) => (next && quietFocus.current ? undefined : setTooltipOpen(next))}
|
||||
>
|
||||
<PopoverAnchor asChild>
|
||||
<TooltipTrigger asChild>
|
||||
<div
|
||||
data-project-combobox-root="true"
|
||||
// A pointer on the field ends the quiet focus: hover shows the tooltip again.
|
||||
onPointerEnter={() => {
|
||||
quietFocus.current = false
|
||||
}}
|
||||
onClick={() => {
|
||||
inputRef.current?.focus()
|
||||
setOpen(true)
|
||||
}}
|
||||
className={cn(
|
||||
COMBOBOX_FIELD_SHELL,
|
||||
invalid && 'border-destructive ring-destructive/20 dark:ring-destructive/40',
|
||||
// Invalid stays red while focused, so the field and its error read as one.
|
||||
invalid &&
|
||||
'border-destructive ring-destructive/20 focus-within:border-destructive focus-within:ring-destructive/40 dark:ring-destructive/40',
|
||||
triggerClassName
|
||||
)}
|
||||
>
|
||||
@@ -226,6 +249,7 @@ export default function ProjectCombobox({
|
||||
setOpen(true)
|
||||
}}
|
||||
onBlur={(event) => {
|
||||
quietFocus.current = false
|
||||
const next = event.relatedTarget
|
||||
// A parent dialog's trap can refocus this field as a nested dialog mounts; Radix misses focus that leaves before the list mounts.
|
||||
if (
|
||||
|
||||
@@ -4,8 +4,8 @@ import { useTranslate } from '@/i18n/use-translate'
|
||||
import { ORCA_CLOUD_NEEDS_REPO_ID } from './cloud-start-view'
|
||||
|
||||
/**
|
||||
* RR-c1 (design-squad): Orca Cloud is selected but the project is a plain folder. Nothing switches
|
||||
* on its own; this line says why Create waits and offers the one way forward: choose a GitHub
|
||||
* RR-c1 (Neil): Project's error after Create was pressed with Orca Cloud on a plain folder. Nothing
|
||||
* switches on its own; it says why Create stopped and offers the one way forward: choose a GitHub
|
||||
* repository (the Project picker opens at them), or add one when there are none.
|
||||
*/
|
||||
export function OrcaCloudNeedsRepoLine({
|
||||
@@ -21,11 +21,11 @@ export function OrcaCloudNeedsRepoLine({
|
||||
return (
|
||||
<div
|
||||
id={ORCA_CLOUD_NEEDS_REPO_ID}
|
||||
role="status"
|
||||
role="alert"
|
||||
className="flex flex-col items-start text-[11px]"
|
||||
data-orca-cloud-needs-repo
|
||||
>
|
||||
<p className="text-muted-foreground">
|
||||
<p className="text-destructive">
|
||||
{t(
|
||||
'components.newWorkspace.cloudOnly.needsRepository',
|
||||
'Orca Cloud needs a GitHub repository.'
|
||||
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
// RR-c1 (Neil): submit-time validation, end to end in the composer's Project row and footer:
|
||||
// silent while picking, an error under Project after Create, and gone once a GitHub repo is picked.
|
||||
import { useState } from 'react'
|
||||
import { defineFixture } from '../../../component-fixtures/component-fixture'
|
||||
import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options'
|
||||
import { NewWorkspaceComposerProjectSection } from '../NewWorkspaceComposerProjectSection'
|
||||
import { NewWorkspaceComposerFooter } from '../NewWorkspaceComposerFooter'
|
||||
import type { EphemeralVmRecipeOption } from '../run-target-options'
|
||||
import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id'
|
||||
import { useNeedsRepoSubmitGuard } from './use-needs-repo-submit-guard'
|
||||
|
||||
const projects: NewWorkspaceProjectOption[] = [
|
||||
{
|
||||
kind: 'project-group',
|
||||
id: 'folder',
|
||||
projectGroupId: 'folder',
|
||||
displayName: 'Design workspace',
|
||||
badgeColor: 'var(--muted-foreground)',
|
||||
detail: '/Users/alice/Projects/design',
|
||||
parentPath: '/Users/alice/Projects/design',
|
||||
connectionId: null
|
||||
},
|
||||
{
|
||||
kind: 'project',
|
||||
id: 'hello',
|
||||
projectId: 'hello',
|
||||
displayName: 'Hello-World',
|
||||
badgeColor: 'var(--muted-foreground)',
|
||||
detail: 'octocat/Hello-World'
|
||||
}
|
||||
]
|
||||
const orcaCloud: EphemeralVmRecipeOption = {
|
||||
id: ORCA_CLOUD_RECIPE_ID,
|
||||
name: 'Orca Cloud',
|
||||
description: 'Hosted by Orca. Sleeps when idle and keeps your files.',
|
||||
provider: 'orca-cloud',
|
||||
create: 'orca-cloud create'
|
||||
}
|
||||
const NEEDS_REPO = { hasRepos: true }
|
||||
|
||||
function Composer(): React.JSX.Element {
|
||||
const [project, setProject] = useState('folder')
|
||||
const [created, setCreated] = useState(false)
|
||||
const needsRepo = project === 'folder' ? NEEDS_REPO : null
|
||||
const guard = useNeedsRepoSubmitGuard(needsRepo, () => setCreated(true))
|
||||
const cloudStart = {
|
||||
onSelectOrcaCloud: () => {},
|
||||
onUserPick: () => {},
|
||||
folderProject: project === 'folder',
|
||||
needsGitHubRepo: guard.shown
|
||||
}
|
||||
return (
|
||||
<div className="w-[520px] space-y-4 rounded-xl border border-border bg-background p-4">
|
||||
<h1 className="text-base font-semibold">Create workspace</h1>
|
||||
<NewWorkspaceComposerProjectSection
|
||||
projectError={null}
|
||||
selectedRepoConnectionId={null}
|
||||
selectedRepoRequiresConnection={false}
|
||||
selectedRepoConnectInProgress={false}
|
||||
projectOptions={projects}
|
||||
selectedProjectId={project}
|
||||
onProjectChange={setProject}
|
||||
projectDescriptionId="fixture-project-description"
|
||||
onAddProject={() => {}}
|
||||
focusNameInput={() => {}}
|
||||
shouldShowRunTargetPicker
|
||||
projectHostSetupOptions={[]}
|
||||
selectedProjectHostSetupId={null}
|
||||
handleProjectHostSetupChange={() => {}}
|
||||
ephemeralVmRecipes={[orcaCloud]}
|
||||
selectedEphemeralVmRecipeId={ORCA_CLOUD_RECIPE_ID}
|
||||
onEphemeralVmRecipeChange={() => {}}
|
||||
orcaCloudAccess={{ state: 'entitled', remainingSeconds: 41 * 3600 }}
|
||||
handleAddSshHost={() => {}}
|
||||
handleAddRemoteServer={() => {}}
|
||||
handleConnectRunTargetHost={async () => {}}
|
||||
handleSetLocation={() => {}}
|
||||
onConnectSelectedRepo={async () => {}}
|
||||
sshStatusLabel="Connected"
|
||||
connectButtonLabel="Connect"
|
||||
selectedProjectName={project === 'folder' ? 'Design workspace' : 'Hello-World'}
|
||||
cloudStart={cloudStart}
|
||||
/>
|
||||
<NewWorkspaceComposerFooter
|
||||
onCreate={guard.onPrimary}
|
||||
createError={null}
|
||||
createDisabled={false}
|
||||
creating={created}
|
||||
primaryActionLabel="Create workspace"
|
||||
submitShortcutModifierLabel="⌘"
|
||||
cloudStart={cloudStart}
|
||||
/>
|
||||
{/* Fixture-only: switches the project the way the Project picker does. */}
|
||||
<button type="button" hidden data-fixture-pick-github onClick={() => setProject('hello')} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
const clickCreate = (frame: HTMLElement): void =>
|
||||
[...frame.querySelectorAll<HTMLButtonElement>('button')]
|
||||
.find((button) => button.textContent?.includes('Create workspace'))
|
||||
?.click()
|
||||
|
||||
const base = {
|
||||
width: 560,
|
||||
setup: () => {
|
||||
window.api.agentApiKeys = undefined
|
||||
window.api.cloudSecrets = undefined
|
||||
},
|
||||
render: () => <Composer />
|
||||
}
|
||||
|
||||
/** Orca Cloud on a plain folder, before Create: Create enabled, no message. */
|
||||
export const beforeSubmit = defineFixture(base)
|
||||
/** Create pressed: nothing submitted; the error under Project, focus on the Project field. */
|
||||
export const afterFailedSubmit = defineFixture({
|
||||
...base,
|
||||
interact: async (frame) => {
|
||||
clickCreate(frame)
|
||||
await wait(200)
|
||||
}
|
||||
})
|
||||
/** A GitHub repository picked after the error: the error clears, and Create is ready. */
|
||||
export const fixed = defineFixture({
|
||||
...base,
|
||||
interact: async (frame) => {
|
||||
clickCreate(frame)
|
||||
await wait(150)
|
||||
frame.querySelector<HTMLButtonElement>('[data-fixture-pick-github]')?.click()
|
||||
await wait(200)
|
||||
}
|
||||
})
|
||||
@@ -14,10 +14,12 @@ export type CloudStartView = {
|
||||
/** JA-21b (flagged): Orca Cloud is selected and a billing wall applies; Create waits for the fix. */
|
||||
wall?: OrcaCloudWallNotice | null
|
||||
/**
|
||||
* RR-c1: Orca Cloud is selected but the project is a plain folder. Both selections stay; one line
|
||||
* under Project says so and Create waits for a GitHub repository. `hasRepos`: any to choose from.
|
||||
* RR-c1: Orca Cloud is selected but the project is a plain folder. Both selections stay and Create
|
||||
* stays enabled; Create (button or ⌘↵) then stops before submitting and this error shows under
|
||||
* Project. `hasRepos`: any to choose from. `attempt` counts those stopped Creates (focus moves to
|
||||
* Project on each); absent until the first.
|
||||
*/
|
||||
needsGitHubRepo?: { hasRepos: boolean } | null
|
||||
needsGitHubRepo?: { hasRepos: boolean; attempt?: number } | null
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, render } from '@testing-library/react'
|
||||
import { act, cleanup, render, renderHook } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { NewWorkspaceComposerFooter } from '../NewWorkspaceComposerFooter'
|
||||
import {
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
orcaCloudNeedsGitHubRepo,
|
||||
type CloudStartView
|
||||
} from './cloud-start-view'
|
||||
import { useNeedsRepoSubmitGuard } from './use-needs-repo-submit-guard'
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
@@ -57,31 +58,58 @@ describe('Orca Cloud on a plain-folder project (RR-c1)', () => {
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('Create is disabled and says why, so it never fails after a click', () => {
|
||||
it('Create stays enabled and silent until pressed; then it points at the error', () => {
|
||||
const onCreate = vi.fn()
|
||||
const cloudStart: CloudStartView = {
|
||||
onSelectOrcaCloud: () => {},
|
||||
onUserPick: () => {},
|
||||
needsGitHubRepo: { hasRepos: true }
|
||||
}
|
||||
const { getByRole } = render(
|
||||
const footer = (needsGitHubRepo: CloudStartView['needsGitHubRepo']) => (
|
||||
<NewWorkspaceComposerFooter
|
||||
onCreate={onCreate}
|
||||
createError={null}
|
||||
createDisabled
|
||||
createDisabled={false}
|
||||
creating={false}
|
||||
primaryActionLabel="Create workspace"
|
||||
submitShortcutModifierLabel="⌘"
|
||||
cloudStart={cloudStart}
|
||||
cloudStart={{ onSelectOrcaCloud: () => {}, onUserPick: () => {}, needsGitHubRepo }}
|
||||
/>
|
||||
)
|
||||
const { getByRole, rerender } = render(footer(null))
|
||||
const button = getByRole('button', { name: /Create workspace/ })
|
||||
expect(button).toHaveProperty('disabled', true)
|
||||
expect(button).toHaveProperty('disabled', false)
|
||||
expect(button.getAttribute('aria-describedby')).toBeNull()
|
||||
rerender(footer({ hasRepos: true, attempt: 1 }))
|
||||
expect(button).toHaveProperty('disabled', false)
|
||||
expect(button.getAttribute('aria-describedby')).toBe(ORCA_CLOUD_NEEDS_REPO_ID)
|
||||
expect(button.parentElement?.getAttribute('title')).toBe(
|
||||
'Orca Cloud needs a GitHub repository.'
|
||||
})
|
||||
})
|
||||
|
||||
describe('RR-c1 submit-time validation (useNeedsRepoSubmitGuard)', () => {
|
||||
it('before Create: no error; Create (button or ⌘↵, one handler) never submits; the error shows', () => {
|
||||
const submit = vi.fn()
|
||||
const { result } = renderHook(() => useNeedsRepoSubmitGuard({ hasRepos: true }, submit))
|
||||
expect(result.current.shown).toBeNull()
|
||||
act(() => result.current.onPrimary())
|
||||
expect(submit).not.toHaveBeenCalled()
|
||||
expect(result.current.shown).toEqual({ hasRepos: true, attempt: 1 })
|
||||
// Each stopped Create counts, so focus moves to Project each time.
|
||||
act(() => result.current.onPrimary())
|
||||
expect(result.current.shown?.attempt).toBe(2)
|
||||
})
|
||||
|
||||
it('clears once a GitHub repository is picked or Run on leaves Orca Cloud, then submits', () => {
|
||||
const submit = vi.fn()
|
||||
const needs = { hasRepos: false }
|
||||
const initialProps: { needsRepo: { hasRepos: boolean } | null } = { needsRepo: needs }
|
||||
const { result, rerender } = renderHook(
|
||||
({ needsRepo }) => useNeedsRepoSubmitGuard(needsRepo, submit),
|
||||
{ initialProps }
|
||||
)
|
||||
button.click()
|
||||
expect(onCreate).not.toHaveBeenCalled()
|
||||
act(() => result.current.onPrimary())
|
||||
expect(result.current.shown).not.toBeNull()
|
||||
rerender({ needsRepo: null })
|
||||
expect(result.current.shown).toBeNull()
|
||||
act(() => result.current.onPrimary())
|
||||
expect(submit).toHaveBeenCalledTimes(1)
|
||||
// Back on a folder: silent again until the next Create.
|
||||
rerender({ needsRepo: needs })
|
||||
expect(result.current.shown).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// The composer modal's side of Orca Cloud: feeds the composer state into useCloudStartComposer and
|
||||
// returns what the primary button and ⌘↵ do.
|
||||
import { useCallback, useEffect, type MutableRefObject } from 'react'
|
||||
import { useCallback, useEffect, useMemo, type MutableRefObject } from 'react'
|
||||
import { useNeedsRepoSubmitGuard } from './use-needs-repo-submit-guard'
|
||||
import type { ComposerModalData } from '../composer-modal-data'
|
||||
import type { NewWorkspaceComposerCardProps } from '../new-workspace-composer-card-props'
|
||||
import { useCloudStartComposer } from './use-cloud-start-composer'
|
||||
@@ -68,13 +69,18 @@ export function useComposerCloudStart({
|
||||
useEffect(() => {
|
||||
recordCreatedRef.current = cloudStart.recordCreated
|
||||
}, [cloudStart.recordCreated, recordCreatedRef])
|
||||
// RR-c1 (Neil): Create stays enabled; one that needs a GitHub repository stops and says so.
|
||||
const needsRepo = cloudStart.view?.needsGitHubRepo ?? null
|
||||
const guard = useNeedsRepoSubmitGuard(needsRepo, cloudStart.onPrimary ?? runCreate)
|
||||
const view = useMemo(
|
||||
() => cloudStart.view && { ...cloudStart.view, needsGitHubRepo: guard.shown },
|
||||
[cloudStart.view, guard.shown]
|
||||
)
|
||||
return {
|
||||
cloudStart,
|
||||
cloudStart: { ...cloudStart, view },
|
||||
// Local and Orca Cloud share one button: same label, same rules for when it's enabled.
|
||||
// JA-21b: a billing wall on the selected Orca Cloud holds Create until it's fixed.
|
||||
// RR-c1: a folder project on Orca Cloud waits for a GitHub repository; Create never fails after.
|
||||
primaryCreateDisabled:
|
||||
createDisabled || Boolean(cloudStart.view?.wall) || Boolean(cloudStart.view?.needsGitHubRepo),
|
||||
onPrimary: cloudStart.onPrimary ?? runCreate
|
||||
primaryCreateDisabled: createDisabled || Boolean(cloudStart.view?.wall),
|
||||
onPrimary: guard.onPrimary
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// RR-c1 (Neil): submit-time validation for Orca Cloud on a plain-folder project. Nothing shows while
|
||||
// options are picked; Create (button or ⌘↵) stops before submitting and the error appears under
|
||||
// Project. It clears once a GitHub repository is picked or Run on leaves Orca Cloud.
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
|
||||
export function useNeedsRepoSubmitGuard<T extends object>(
|
||||
/** Non-null while Orca Cloud is on a folder with no GitHub repository picked. */
|
||||
needsRepo: T | null,
|
||||
submit: () => void
|
||||
): {
|
||||
onPrimary: () => void
|
||||
/** The error to show (with how many Creates it stopped), or null: never before a Create. */
|
||||
shown: (T & { attempt: number }) | null
|
||||
} {
|
||||
const active = needsRepo !== null
|
||||
const [stopped, setStopped] = useState({ attempt: 0, active })
|
||||
// Resolved (or back again): start over in the same render, so a stale error never shows.
|
||||
if (stopped.active !== active) {
|
||||
setStopped({ attempt: 0, active })
|
||||
}
|
||||
const attempt = stopped.active === active ? stopped.attempt : 0
|
||||
const onPrimary = useCallback(() => {
|
||||
if (needsRepo) {
|
||||
// Never submitted: a create can't fail on the server for this.
|
||||
setStopped((current) => ({ attempt: current.attempt + 1, active: true }))
|
||||
return
|
||||
}
|
||||
submit()
|
||||
}, [needsRepo, submit])
|
||||
const shown = useMemo(
|
||||
() => (needsRepo && attempt > 0 ? { ...needsRepo, attempt } : null),
|
||||
[needsRepo, attempt]
|
||||
)
|
||||
return { onPrimary, shown }
|
||||
}
|
||||
Reference in New Issue
Block a user