mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat(frontend): mobile-friendly config editor with find bar and unsaved-changes guard (#326)
* feat(frontend): mobile-friendly config editor with find bar and unsaved-changes guard * refactor: remove retry-clone flow and share destructive-confirm dialog Backend drops POST /:id/retry-clone and the supporting retryCloneRepo service and claimRepoForRetry query; failed clones now delete the repo row rather than lingering in error state. Frontend extracts ConfirmDestructiveDialog shared by Delete/Discard/UnsavedChanges dialogs, memoizes CodeEditor rows, fixes scroll jump while typing away from the active match, and aligns the responsive breakpoint to 768px.
This commit is contained in:
1 parent
f8e361c0b8
commit
a73ac19bbc
29 files changed
+2032
-356
No files matched your search
@@ -0,0 +1,125 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor, fireEvent } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { AgentsMdEditor } from './AgentsMdEditor'
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
getAgentsMd: vi.fn().mockResolvedValue({ content: '# Rules\n\nline two\nline three\n' }),
|
||||
updateAgentsMd: vi.fn().mockResolvedValue(undefined),
|
||||
getDefaultAgentsMd: vi.fn().mockResolvedValue({ content: '# Default' }),
|
||||
},
|
||||
}))
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
describe('AgentsMdEditor', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('loads the current AGENTS.md into the editor', async () => {
|
||||
render(<AgentsMdEditor />, { wrapper: createWrapper() })
|
||||
await waitFor(() =>
|
||||
expect(screen.getByLabelText('AGENTS.md content')).toHaveValue('# Rules\n\nline two\nline three\n'),
|
||||
)
|
||||
})
|
||||
|
||||
it('renders a line number gutter', async () => {
|
||||
render(<AgentsMdEditor />, { wrapper: createWrapper() })
|
||||
await waitFor(() => expect(screen.getByLabelText('AGENTS.md content')).toBeInTheDocument())
|
||||
const numbers = Array.from(document.body.querySelectorAll('[data-line-number]'))
|
||||
expect(numbers.map((n) => n.textContent?.trim())).toEqual(['1', '2', '3', '4', '5'])
|
||||
})
|
||||
|
||||
it('finds matches in the content', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<AgentsMdEditor />, { wrapper: createWrapper() })
|
||||
await waitFor(() => expect(screen.getByLabelText('AGENTS.md content')).toBeInTheDocument())
|
||||
const findInput = screen.getByLabelText('Find in content')
|
||||
await user.type(findInput, 'line')
|
||||
expect(screen.getByTestId('find-match-count')).toHaveTextContent('1 of 2')
|
||||
const marks = document.body.querySelectorAll('mark')
|
||||
expect(marks.length).toBe(2)
|
||||
})
|
||||
|
||||
it('keeps Save disabled until the content changes', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<AgentsMdEditor />, { wrapper: createWrapper() })
|
||||
const saveButton = await screen.findByRole('button', { name: 'Save' })
|
||||
expect(saveButton).toBeDisabled()
|
||||
const textarea = screen.getByLabelText('AGENTS.md content') as HTMLTextAreaElement
|
||||
await user.type(textarea, '!')
|
||||
expect(saveButton).toBeEnabled()
|
||||
})
|
||||
|
||||
it('saves the edited content', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { settingsApi } = await import('@/api/settings')
|
||||
render(<AgentsMdEditor />, { wrapper: createWrapper() })
|
||||
const textarea = (await screen.findByLabelText('AGENTS.md content')) as HTMLTextAreaElement
|
||||
const edited = '# Rules\n\nline two\nline three\n# new section\n'
|
||||
fireEvent.change(textarea, { target: { value: edited } })
|
||||
const saveButton = screen.getByRole('button', { name: 'Save' })
|
||||
await user.click(saveButton)
|
||||
await waitFor(() => expect(settingsApi.updateAgentsMd).toHaveBeenCalled())
|
||||
expect(settingsApi.updateAgentsMd).toHaveBeenCalledWith(edited)
|
||||
})
|
||||
|
||||
it('uses a 16px editor font on mobile', async () => {
|
||||
render(<AgentsMdEditor />, { wrapper: createWrapper() })
|
||||
const textarea = await screen.findByLabelText('AGENTS.md content')
|
||||
expect(textarea.className).toContain('text-[16px]')
|
||||
expect(textarea.className).toContain('min-[769px]:text-sm')
|
||||
expect(textarea.className).not.toContain('text-xs')
|
||||
})
|
||||
|
||||
it('locks the editor while a save is pending and preserves submitted content', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { settingsApi } = await import('@/api/settings')
|
||||
let resolveSave: () => void = () => {}
|
||||
;(settingsApi.updateAgentsMd as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
new Promise<void>((resolve) => {
|
||||
resolveSave = resolve
|
||||
}),
|
||||
)
|
||||
render(<AgentsMdEditor />, { wrapper: createWrapper() })
|
||||
const textarea = (await screen.findByLabelText('AGENTS.md content')) as HTMLTextAreaElement
|
||||
const edited = '# Rules\n\nline two\nline three\nedit\n'
|
||||
fireEvent.change(textarea, { target: { value: edited } })
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() => expect(textarea).toBeDisabled())
|
||||
try {
|
||||
await user.type(textarea, 'lost edit')
|
||||
} catch {
|
||||
// user-event refuses to type into a disabled element; expected
|
||||
}
|
||||
expect(textarea).toHaveValue(edited)
|
||||
resolveSave()
|
||||
await waitFor(() => expect(textarea).not.toBeDisabled())
|
||||
expect(textarea).toHaveValue(edited)
|
||||
})
|
||||
|
||||
it('preserves a post-save edit when a deferred refetch arrives with the saved value', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { settingsApi } = await import('@/api/settings')
|
||||
;(settingsApi.getAgentsMd as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ content: 'A' })
|
||||
.mockResolvedValueOnce({ content: 'B' })
|
||||
render(<AgentsMdEditor />, { wrapper: createWrapper() })
|
||||
const textarea = (await screen.findByLabelText('AGENTS.md content')) as HTMLTextAreaElement
|
||||
await waitFor(() => expect(textarea).toHaveValue('A'))
|
||||
fireEvent.change(textarea, { target: { value: 'B' } })
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() => expect(settingsApi.updateAgentsMd).toHaveBeenCalledWith('B'))
|
||||
fireEvent.change(textarea, { target: { value: 'A' } })
|
||||
await waitFor(() => expect(settingsApi.getAgentsMd).toHaveBeenCalledTimes(2))
|
||||
expect(textarea).toHaveValue('A')
|
||||
})
|
||||
})
|
||||
@@ -1,15 +1,22 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { Loader2, Save, RotateCcw } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { CodeEditor } from '@/components/ui/code-editor'
|
||||
import { EditorFindBar } from '@/components/ui/editor-find-bar'
|
||||
import { useFindInText } from '@/lib/useFindInText'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
export function AgentsMdEditor() {
|
||||
const queryClient = useQueryClient()
|
||||
const [content, setContent] = useState('')
|
||||
const [hasChanges, setHasChanges] = useState(false)
|
||||
const [savedContent, setSavedContent] = useState('')
|
||||
const hasChanges = content !== savedContent
|
||||
const hasChangesRef = useRef(false)
|
||||
hasChangesRef.current = hasChanges
|
||||
const savedContentRef = useRef('')
|
||||
savedContentRef.current = savedContent
|
||||
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ['agents-md'],
|
||||
@@ -17,18 +24,19 @@ export function AgentsMdEditor() {
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (data?.content !== undefined) {
|
||||
setContent(data.content)
|
||||
setHasChanges(false)
|
||||
}
|
||||
if (data?.content === undefined) return
|
||||
if (hasChangesRef.current) return
|
||||
if (data.content === savedContentRef.current) return
|
||||
setContent(data.content)
|
||||
setSavedContent(data.content)
|
||||
}, [data?.content])
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (newContent: string) => settingsApi.updateAgentsMd(newContent),
|
||||
onSuccess: () => {
|
||||
onSuccess: (_data, newContent) => {
|
||||
setSavedContent(newContent)
|
||||
queryClient.invalidateQueries({ queryKey: ['agents-md'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
setHasChanges(false)
|
||||
showToast.success('AGENTS.md saved and server restarted')
|
||||
},
|
||||
onError: () => {
|
||||
@@ -45,7 +53,7 @@ export function AgentsMdEditor() {
|
||||
onSuccess: (defaultContent) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['agents-md'] })
|
||||
setContent(defaultContent)
|
||||
setHasChanges(false)
|
||||
setSavedContent(defaultContent)
|
||||
showToast.success('AGENTS.md reset to default and server restarted')
|
||||
},
|
||||
onError: () => {
|
||||
@@ -53,10 +61,7 @@ export function AgentsMdEditor() {
|
||||
},
|
||||
})
|
||||
|
||||
const handleContentChange = (value: string) => {
|
||||
setContent(value)
|
||||
setHasChanges(value !== data?.content)
|
||||
}
|
||||
const isSaving = updateMutation.isPending || resetToDefaultMutation.isPending
|
||||
|
||||
const handleSave = () => {
|
||||
updateMutation.mutate(content)
|
||||
@@ -66,6 +71,8 @@ export function AgentsMdEditor() {
|
||||
resetToDefaultMutation.mutate()
|
||||
}
|
||||
|
||||
const { query, setQuery, matches, currentMatchIndex, hasMatches, next, prev } = useFindInText(content)
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
@@ -84,18 +91,19 @@ export function AgentsMdEditor() {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
|
||||
<div className="sticky top-0 z-10 flex flex-col gap-3 bg-background py-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Global instructions for AI agents. This file is merged with repository-specific AGENTS.md files.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2 flex-shrink-0">
|
||||
<div className="flex flex-shrink-0 gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleResetToDefault}
|
||||
disabled={updateMutation.isPending || resetToDefaultMutation.isPending}
|
||||
disabled={isSaving}
|
||||
className="flex-1 sm:flex-none"
|
||||
>
|
||||
{resetToDefaultMutation.isPending ? (
|
||||
<Loader2 className="h-4 w-4 mr-1 animate-spin" />
|
||||
@@ -107,7 +115,8 @@ export function AgentsMdEditor() {
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSave}
|
||||
disabled={!hasChanges || updateMutation.isPending || resetToDefaultMutation.isPending}
|
||||
disabled={!hasChanges || isSaving}
|
||||
className="flex-1 sm:flex-none"
|
||||
>
|
||||
{updateMutation.isPending ? (
|
||||
<Loader2 className="h-4 w-4 mr-1 animate-spin" />
|
||||
@@ -118,14 +127,31 @@ export function AgentsMdEditor() {
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Textarea
|
||||
value={content}
|
||||
onChange={(e) => handleContentChange(e.target.value)}
|
||||
className="font-mono text-xs sm:text-sm min-h-[300px] resize-y"
|
||||
placeholder="# Agent Instructions Add global instructions for AI agents here..."
|
||||
|
||||
<EditorFindBar
|
||||
query={query}
|
||||
onQueryChange={setQuery}
|
||||
matchCount={matches.length}
|
||||
currentMatch={hasMatches ? currentMatchIndex + 1 : 0}
|
||||
onPrev={prev}
|
||||
onNext={next}
|
||||
inputName="agents-md-find"
|
||||
placeholder="Find in AGENTS.md..."
|
||||
className="rounded-t-md border-x border-t"
|
||||
/>
|
||||
|
||||
|
||||
<div className="h-[55vh] min-h-[300px] overflow-hidden rounded-b-md border border-input">
|
||||
<CodeEditor
|
||||
ariaLabel="AGENTS.md content"
|
||||
value={content}
|
||||
onChange={setContent}
|
||||
highlights={matches}
|
||||
activeHighlightIndex={currentMatchIndex}
|
||||
disabled={isSaving}
|
||||
placeholder="# Agent Instructions Add global instructions for AI agents here..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{hasChanges && (
|
||||
<p className="text-xs text-amber-500">You have unsaved changes</p>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen, waitFor, fireEvent } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { OpenCodeConfigEditor } from './OpenCodeConfigEditor'
|
||||
import type { OpenCodeConfig } from '@/api/types/settings'
|
||||
|
||||
const RAW = `{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"theme": "system",
|
||||
"model": "anthropic/claude-sonnet-4"
|
||||
}`
|
||||
|
||||
const config: OpenCodeConfig = {
|
||||
id: 1,
|
||||
name: 'default',
|
||||
content: {},
|
||||
rawContent: RAW,
|
||||
isValid: true,
|
||||
isDefault: true,
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
}
|
||||
|
||||
function setContent(textarea: HTMLTextAreaElement, value: string) {
|
||||
fireEvent.change(textarea, { target: { value } })
|
||||
}
|
||||
|
||||
describe('OpenCodeConfigEditor', () => {
|
||||
const renderEditor = (
|
||||
overrides: Partial<React.ComponentProps<typeof OpenCodeConfigEditor>> = {},
|
||||
) => {
|
||||
const onUpdate = vi.fn().mockResolvedValue(undefined)
|
||||
const onClose = vi.fn()
|
||||
const result = render(
|
||||
<OpenCodeConfigEditor
|
||||
config={config}
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
onUpdate={onUpdate}
|
||||
{...overrides}
|
||||
/>,
|
||||
)
|
||||
return { ...result, onUpdate, onClose }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 375 })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 })
|
||||
})
|
||||
|
||||
it('loads rawContent verbatim into the editor', () => {
|
||||
renderEditor()
|
||||
expect(screen.getByLabelText('Config content')).toHaveValue(RAW)
|
||||
})
|
||||
|
||||
it('renders a line number gutter', () => {
|
||||
renderEditor()
|
||||
const numbers = Array.from(document.body.querySelectorAll('[data-line-number]'))
|
||||
expect(numbers.map((n) => n.textContent?.trim())).toEqual(['1', '2', '3', '4', '5'])
|
||||
})
|
||||
|
||||
it('does not autofocus the editor on a mobile viewport', () => {
|
||||
renderEditor()
|
||||
expect(screen.getByLabelText('Config content')).not.toHaveFocus()
|
||||
})
|
||||
|
||||
it('does not autofocus the find input on a mobile viewport', () => {
|
||||
renderEditor()
|
||||
expect(screen.getByLabelText('Find in content')).not.toHaveFocus()
|
||||
})
|
||||
|
||||
it('autofocuses the editor on a desktop viewport', () => {
|
||||
Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1280 })
|
||||
renderEditor()
|
||||
expect(screen.getByLabelText('Config content')).toHaveFocus()
|
||||
expect(screen.getByLabelText('Find in content')).not.toHaveFocus()
|
||||
})
|
||||
|
||||
it('keeps the footer actions inside the layout flow', () => {
|
||||
renderEditor()
|
||||
const updateBtn = screen.getByRole('button', { name: 'Update' })
|
||||
const footer = updateBtn.closest('[data-editor-footer]')
|
||||
expect(footer).toBeInTheDocument()
|
||||
let ancestor: Element | null = footer
|
||||
while (ancestor && ancestor !== document.body) {
|
||||
expect(ancestor.className || '').not.toMatch(/\babsolute\b/)
|
||||
ancestor = ancestor.parentElement
|
||||
}
|
||||
})
|
||||
|
||||
it('surfaces a JSONC syntax error with the offending line', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEditor()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
setContent(textarea, '{\n "a" 1\n}')
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Invalid JSON\/JSONC/)).toBeInTheDocument()
|
||||
})
|
||||
expect(screen.getByRole('button', { name: /Go to line 2/ })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('jumps to the syntax error line when the error line button is pressed', async () => {
|
||||
const { onUpdate } = renderEditor()
|
||||
const user = userEvent.setup()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
setContent(textarea, '{\n "a" 1\n}')
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
const goButton = await screen.findByRole('button', { name: /Go to line 2/ })
|
||||
await user.click(goButton)
|
||||
const activeLine = document.body.querySelector('[data-active-line]')
|
||||
const row = activeLine?.closest('[data-line]')
|
||||
expect(row).toHaveAttribute('data-line', '2')
|
||||
expect(onUpdate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('recenters the syntax error line on repeated clicks', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEditor()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
setContent(textarea, '{\n "a" 1\n}')
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
const goButton = await screen.findByRole('button', { name: /Go to line 2/ })
|
||||
let scrollTopSets = 0
|
||||
Object.defineProperty(textarea, 'scrollTop', {
|
||||
configurable: true,
|
||||
get: () => 0,
|
||||
set: () => {
|
||||
scrollTopSets += 1
|
||||
},
|
||||
})
|
||||
await user.click(goButton)
|
||||
await user.click(goButton)
|
||||
expect(scrollTopSets).toBeGreaterThanOrEqual(2)
|
||||
})
|
||||
|
||||
it('lists schema validation issues as line jumps', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEditor()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
setContent(textarea, '{\n "theme": 42\n}')
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
const issueButton = await screen.findByRole('button', { name: /theme/i })
|
||||
expect(issueButton).toBeInTheDocument()
|
||||
await user.click(issueButton)
|
||||
const activeLine = document.body.querySelector('[data-active-line]')
|
||||
const row = activeLine?.closest('[data-line]')
|
||||
expect(row).toHaveAttribute('data-line', '2')
|
||||
})
|
||||
|
||||
it('does not call onUpdate when local validation fails', async () => {
|
||||
const { onUpdate } = renderEditor()
|
||||
const user = userEvent.setup()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
setContent(textarea, '{\n "theme": 42\n}')
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Configuration validation failed/)).toBeInTheDocument()
|
||||
})
|
||||
expect(onUpdate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('saves the raw text including comments', async () => {
|
||||
const { onUpdate, onClose } = renderEditor()
|
||||
const user = userEvent.setup()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
const next = '{\n // keep me\n "theme": "system"\n}'
|
||||
setContent(textarea, next)
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
await waitFor(() => {
|
||||
expect(onUpdate).toHaveBeenCalledWith(next)
|
||||
})
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('clears errors as soon as the content changes', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEditor()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
setContent(textarea, '{\n "a" 1\n}')
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Invalid JSON\/JSONC/)).toBeInTheDocument()
|
||||
})
|
||||
setContent(textarea, '{\n "a" 1\n} ')
|
||||
expect(screen.queryByText(/Invalid JSON\/JSONC/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders find matches and reports the counter', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEditor()
|
||||
const findInput = screen.getByLabelText('Find in content')
|
||||
await user.type(findInput, 'theme')
|
||||
const counter = await screen.findByTestId('find-match-count')
|
||||
expect(counter).toHaveTextContent('1 of 1')
|
||||
expect(document.body.querySelectorAll('mark').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('does not prompt when closing without edits', async () => {
|
||||
const { onClose } = renderEditor()
|
||||
const user = userEvent.setup()
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
expect(screen.queryByText('Unsaved Changes')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('prompts before discarding edits', async () => {
|
||||
const { onClose } = renderEditor()
|
||||
const user = userEvent.setup()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
setContent(textarea, RAW + ' ')
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(screen.getByText('Unsaved Changes')).toBeInTheDocument()
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps editing when the prompt is dismissed', async () => {
|
||||
const { onClose } = renderEditor()
|
||||
const user = userEvent.setup()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
setContent(textarea, RAW + ' ')
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Keep Editing' }))
|
||||
expect(screen.queryByText('Unsaved Changes')).not.toBeInTheDocument()
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
expect(textarea).toHaveValue(RAW + ' ')
|
||||
})
|
||||
|
||||
it('discards edits when confirmed', async () => {
|
||||
const { onClose } = renderEditor()
|
||||
const user = userEvent.setup()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
setContent(textarea, RAW + ' ')
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Discard' }))
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('prompts on Escape when there are edits', async () => {
|
||||
const { onClose } = renderEditor()
|
||||
const user = userEvent.setup()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
await user.click(textarea)
|
||||
setContent(textarea, RAW + ' ')
|
||||
await user.keyboard('{Escape}')
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Unsaved Changes')).toBeInTheDocument()
|
||||
})
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows a spinner and blocks re-submission while saving', async () => {
|
||||
let resolveSave: () => void = () => {}
|
||||
const onUpdate = vi.fn(
|
||||
() => new Promise<void>((resolve) => {
|
||||
resolveSave = resolve
|
||||
}),
|
||||
)
|
||||
const onClose = vi.fn()
|
||||
render(
|
||||
<OpenCodeConfigEditor
|
||||
config={config}
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
onUpdate={onUpdate}
|
||||
/>,
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
const updateBtn = screen.getByRole('button', { name: 'Update' })
|
||||
await user.click(updateBtn)
|
||||
await waitFor(() => expect(updateBtn).toBeDisabled())
|
||||
await user.click(updateBtn)
|
||||
resolveSave()
|
||||
await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1))
|
||||
expect(onUpdate).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('re-enables Update after a failed save', async () => {
|
||||
const onUpdate = vi.fn().mockRejectedValue(new Error('boom'))
|
||||
const onClose = vi.fn()
|
||||
render(
|
||||
<OpenCodeConfigEditor
|
||||
config={config}
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
onUpdate={onUpdate}
|
||||
/>,
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
const updateBtn = screen.getByRole('button', { name: 'Update' })
|
||||
await user.click(updateBtn)
|
||||
await waitFor(() => expect(screen.getByText('boom')).toBeInTheDocument())
|
||||
await waitFor(() => expect(updateBtn).not.toBeDisabled())
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('locks the editor against edits while a save is pending', async () => {
|
||||
let resolveSave: () => void = () => {}
|
||||
const onUpdate = vi.fn(
|
||||
() => new Promise<void>((resolve) => {
|
||||
resolveSave = resolve
|
||||
}),
|
||||
)
|
||||
const onClose = vi.fn()
|
||||
render(
|
||||
<OpenCodeConfigEditor
|
||||
config={config}
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
onUpdate={onUpdate}
|
||||
/>,
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
expect(textarea).not.toBeDisabled()
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
await waitFor(() => expect(textarea).toBeDisabled())
|
||||
try {
|
||||
await user.type(textarea, ' extra')
|
||||
} catch {
|
||||
// user-event refuses to type into a disabled element; expected
|
||||
}
|
||||
expect(textarea).toHaveValue(RAW)
|
||||
resolveSave()
|
||||
await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1))
|
||||
expect(onUpdate).toHaveBeenCalledTimes(1)
|
||||
expect(onUpdate).toHaveBeenCalledWith(RAW)
|
||||
})
|
||||
|
||||
it('resolves a validation issue under a dotted provider key to its line', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEditor()
|
||||
const textarea = screen.getByLabelText('Config content') as HTMLTextAreaElement
|
||||
const dotted = '{\n "provider": {\n "api.example.com": {\n "key": 123\n }\n }\n}'
|
||||
setContent(textarea, dotted)
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
const issueButton = await screen.findByRole('button', { name: /api\.example\.com/i })
|
||||
expect(issueButton).toBeInTheDocument()
|
||||
await user.click(issueButton)
|
||||
const activeLine = document.body.querySelector('[data-active-line]')
|
||||
const row = activeLine?.closest('[data-line]')
|
||||
expect(row).toHaveAttribute('data-line', '4')
|
||||
})
|
||||
})
|
||||
@@ -1,18 +1,21 @@
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Loader2, Search, ChevronUp, ChevronDown } from 'lucide-react'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogFooter, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { CodeEditor } from '@/components/ui/code-editor'
|
||||
import { EditorFindBar } from '@/components/ui/editor-find-bar'
|
||||
import { UnsavedChangesDialog } from '@/components/ui/unsaved-changes-dialog'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useFindInText } from '@/lib/useFindInText'
|
||||
import type { OpenCodeConfig } from '@/api/types/settings'
|
||||
import { parseJsonc } from '@/lib/jsonc'
|
||||
import { parseJsonc, parseJsoncErrorLine, resolveJsoncIssueLine } from '@/lib/jsonc'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared'
|
||||
import type { OpenCodeConfig } from '@/api/types/settings'
|
||||
|
||||
type ValidationIssue = {
|
||||
path: string
|
||||
message: string
|
||||
line: number | null
|
||||
}
|
||||
|
||||
interface OpenCodeConfigEditorProps {
|
||||
@@ -20,7 +23,6 @@ interface OpenCodeConfigEditorProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onUpdate: (content: string) => Promise<void>
|
||||
isUpdating: boolean
|
||||
}
|
||||
|
||||
export function OpenCodeConfigEditor({
|
||||
@@ -28,102 +30,78 @@ export function OpenCodeConfigEditor({
|
||||
isOpen,
|
||||
onClose,
|
||||
onUpdate,
|
||||
isUpdating
|
||||
}: OpenCodeConfigEditorProps) {
|
||||
const [editConfigContent, setEditConfigContent] = useState('')
|
||||
const [initialContent, setInitialContent] = useState('')
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const [isDiscardPromptOpen, setIsDiscardPromptOpen] = useState(false)
|
||||
const [editError, setEditError] = useState('')
|
||||
const [editErrorLine, setEditErrorLine] = useState<number | null>(null)
|
||||
const [validationIssues, setValidationIssues] = useState<ValidationIssue[]>([])
|
||||
const [removedFields, setRemovedFields] = useState<string[]>([])
|
||||
const [isTextareaFocused, setIsTextareaFocused] = useState(false)
|
||||
const editTextareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
const backdropRef = useRef<HTMLDivElement>(null)
|
||||
const [activeLine, setActiveLine] = useState<number | null>(null)
|
||||
const [revealNonce, setRevealNonce] = useState(0)
|
||||
const isMobile = useMobile()
|
||||
const isDirty = editConfigContent !== initialContent
|
||||
const { query, setQuery, matches, currentMatchIndex, hasMatches, next, prev } = useFindInText(editConfigContent)
|
||||
|
||||
useEffect(() => {
|
||||
if (config && isOpen) {
|
||||
setEditConfigContent(config.rawContent || JSON.stringify(config.content, null, 2))
|
||||
setEditError('')
|
||||
setEditErrorLine(null)
|
||||
setValidationIssues([])
|
||||
setRemovedFields([])
|
||||
}
|
||||
}, [config, isOpen])
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen && editTextareaRef.current) {
|
||||
editTextareaRef.current.focus()
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
useEffect(() => {
|
||||
const textarea = editTextareaRef.current
|
||||
if (!textarea || matches.length === 0) return
|
||||
const match = matches[currentMatchIndex]
|
||||
if (match) {
|
||||
const textBefore = editConfigContent.substring(0, match.startIndex)
|
||||
const lineNumber = textBefore.split('\n').length
|
||||
const lineHeight = textarea.scrollHeight / textarea.value.split('\n').length
|
||||
textarea.scrollTop = lineHeight * (lineNumber - 1) - textarea.clientHeight / 2 + lineHeight / 2
|
||||
syncBackdropScroll()
|
||||
}
|
||||
}, [currentMatchIndex, matches, editConfigContent])
|
||||
|
||||
const syncBackdropScroll = () => {
|
||||
const textarea = editTextareaRef.current
|
||||
const backdrop = backdropRef.current
|
||||
if (textarea && backdrop) {
|
||||
backdrop.scrollTop = textarea.scrollTop
|
||||
backdrop.scrollLeft = textarea.scrollLeft
|
||||
}
|
||||
}
|
||||
|
||||
const handleFindKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
if (e.shiftKey) prev()
|
||||
else next()
|
||||
}
|
||||
}
|
||||
|
||||
const renderHighlightedContent = (focused: boolean) => {
|
||||
if (matches.length === 0 || focused) {
|
||||
return editConfigContent
|
||||
}
|
||||
const segments: React.ReactNode[] = []
|
||||
let lastIndex = 0
|
||||
matches.forEach((match, index) => {
|
||||
if (match.startIndex > lastIndex) {
|
||||
segments.push(editConfigContent.substring(lastIndex, match.startIndex))
|
||||
}
|
||||
const isCurrent = index === currentMatchIndex
|
||||
segments.push(
|
||||
<mark
|
||||
key={index}
|
||||
className={isCurrent ? 'bg-orange-400 text-black rounded-sm' : 'bg-yellow-300/60 text-black rounded-sm'}
|
||||
>
|
||||
{editConfigContent.substring(match.startIndex, match.endIndex)}
|
||||
</mark>
|
||||
)
|
||||
lastIndex = match.endIndex
|
||||
})
|
||||
if (lastIndex < editConfigContent.length) {
|
||||
segments.push(editConfigContent.substring(lastIndex))
|
||||
}
|
||||
return segments
|
||||
}
|
||||
const revealLine = useCallback((line: number | null) => {
|
||||
setActiveLine(line)
|
||||
setRevealNonce((n) => n + 1)
|
||||
}, [])
|
||||
|
||||
const resetErrors = () => {
|
||||
setEditError('')
|
||||
setEditErrorLine(null)
|
||||
setValidationIssues([])
|
||||
setRemovedFields([])
|
||||
setActiveLine(null)
|
||||
}
|
||||
|
||||
const getIssueText = (issue: ValidationIssue) => {
|
||||
return `${issue.path}: ${issue.message}`
|
||||
useEffect(() => {
|
||||
if (config && isOpen) {
|
||||
const next = config.rawContent || JSON.stringify(config.content, null, 2)
|
||||
setEditConfigContent(next)
|
||||
setInitialContent(next)
|
||||
resetErrors()
|
||||
setIsSaving(false)
|
||||
setIsDiscardPromptOpen(false)
|
||||
}
|
||||
}, [config, isOpen])
|
||||
|
||||
const requestClose = () => {
|
||||
if (isSaving) return
|
||||
if (isDirty) {
|
||||
setIsDiscardPromptOpen(true)
|
||||
return
|
||||
}
|
||||
onClose()
|
||||
}
|
||||
|
||||
const discardAndClose = () => {
|
||||
setIsDiscardPromptOpen(false)
|
||||
onClose()
|
||||
}
|
||||
|
||||
const getIssueText = (issue: ValidationIssue) => `${issue.path}: ${issue.message}`
|
||||
|
||||
const resolveIssues = (
|
||||
issues: Array<{ path: PropertyKey[] | string; message: string }>,
|
||||
): ValidationIssue[] =>
|
||||
issues.map((issue) => {
|
||||
const path = issue.path
|
||||
const isStructured = Array.isArray(path)
|
||||
const displaySegments = isStructured
|
||||
? path.map(String)
|
||||
: String(path).split('.').filter((segment) => segment.length > 0)
|
||||
const displayPath = displaySegments.length > 0 ? displaySegments.join('.') : 'root'
|
||||
return {
|
||||
path: displayPath,
|
||||
message: issue.message,
|
||||
line: resolveJsoncIssueLine(editConfigContent, path),
|
||||
}
|
||||
})
|
||||
|
||||
const updateConfig = async () => {
|
||||
if (!config) return
|
||||
|
||||
@@ -132,171 +110,155 @@ export function OpenCodeConfigEditor({
|
||||
const parsedConfig = parseJsonc<Record<string, unknown>>(editConfigContent)
|
||||
const validationResult = OpenCodeConfigSchema.safeParse(parsedConfig)
|
||||
if (!validationResult.success) {
|
||||
const issues = validationResult.error.issues.map((issue) => ({
|
||||
path: issue.path.length > 0 ? issue.path.map(String).join('.') : 'root',
|
||||
message: issue.message,
|
||||
}))
|
||||
const issues = resolveIssues(validationResult.error.issues)
|
||||
setValidationIssues(issues)
|
||||
setEditError(`Configuration validation failed: ${issues.map(getIssueText).join('; ')}`)
|
||||
return
|
||||
}
|
||||
|
||||
setIsSaving(true)
|
||||
await onUpdate(editConfigContent)
|
||||
onClose()
|
||||
} catch (error) {
|
||||
if (error instanceof SyntaxError) {
|
||||
const lineMatch = error.message.match(/line\s+(\d+)/i)
|
||||
const line = lineMatch ? parseInt(lineMatch[1]) : null
|
||||
const line = parseJsoncErrorLine(error)
|
||||
setEditErrorLine(line)
|
||||
if (line && editTextareaRef.current) {
|
||||
highlightErrorLine(editTextareaRef.current, line)
|
||||
}
|
||||
revealLine(line)
|
||||
setEditError(`Invalid JSON/JSONC: ${error.message}`)
|
||||
} else if (error instanceof FetchError) {
|
||||
setValidationIssues(error.validationIssues || [])
|
||||
setRemovedFields(error.removedFields || [])
|
||||
const issues = resolveIssues(error.validationIssues ?? [])
|
||||
setValidationIssues(issues)
|
||||
setRemovedFields(error.removedFields ?? [])
|
||||
setEditError(error.detail || error.message)
|
||||
} else if (error instanceof Error) {
|
||||
setEditError(error.message)
|
||||
} else {
|
||||
setEditError('Failed to save configuration')
|
||||
}
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const highlightErrorLine = (textarea: HTMLTextAreaElement, line: number) => {
|
||||
const lines = textarea.value.split('\n')
|
||||
if (line > lines.length) return
|
||||
|
||||
let charIndex = 0
|
||||
for (let i = 0; i < line - 1; i++) {
|
||||
charIndex += lines[i].length + 1
|
||||
}
|
||||
|
||||
textarea.focus()
|
||||
textarea.setSelectionRange(charIndex, charIndex + lines[line - 1].length)
|
||||
|
||||
// Scroll to make the error line visible
|
||||
const lineHeight = textarea.scrollHeight / lines.length
|
||||
const targetPosition = lineHeight * (line - 1)
|
||||
textarea.scrollTop = targetPosition - textarea.clientHeight / 2 + lineHeight / 2
|
||||
}
|
||||
|
||||
if (!config) return null
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent mobileFullscreen className="gap-0 flex flex-col p-0 md:p-6 w-full min-w-0 sm:max-w-4xl max-h-[90vh] sm:max-h-[85vh]">
|
||||
<DialogHeader className="p-4 sm:p-6 border-b flex flex-row items-center justify-between space-y-0">
|
||||
<DialogTitle className="text-lg sm:text-xl font-semibold">
|
||||
{`Edit Config: ${config.name}`}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<>
|
||||
<Dialog open={isOpen} onOpenChange={(open) => { if (!open) requestClose() }}>
|
||||
<DialogContent
|
||||
mobileFullscreen
|
||||
keyboardAware
|
||||
onOpenAutoFocus={(event) => {
|
||||
if (isMobile) event.preventDefault()
|
||||
}}
|
||||
className="flex w-full min-w-0 flex-col gap-0 p-0 sm:max-h-[85vh] sm:max-w-4xl sm:p-6"
|
||||
>
|
||||
<DialogHeader className="flex shrink-0 flex-row items-center justify-between space-y-0 border-b p-4 sm:p-6">
|
||||
<DialogTitle className="text-lg font-semibold sm:text-xl">
|
||||
{`Edit Config: ${config.name}`}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex items-center gap-2 px-4 py-2 border-b bg-muted/30">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={handleFindKeyDown}
|
||||
placeholder="Find in config..."
|
||||
className="pl-9 h-9 text-[16px] sm:text-xs md:text-sm"
|
||||
autoComplete="off"
|
||||
name="config-find"
|
||||
/>
|
||||
</div>
|
||||
{query && (
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
{hasMatches
|
||||
? `${currentMatchIndex + 1} of ${matches.length}`
|
||||
: '0 matches'}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
onClick={prev}
|
||||
disabled={!hasMatches}
|
||||
className="p-1 rounded hover:bg-accent disabled:opacity-30 disabled:cursor-not-allowed"
|
||||
title="Previous match"
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={next}
|
||||
disabled={!hasMatches}
|
||||
className="p-1 rounded hover:bg-accent disabled:opacity-30 disabled:cursor-not-allowed"
|
||||
title="Next match"
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
<EditorFindBar
|
||||
query={query}
|
||||
onQueryChange={setQuery}
|
||||
matchCount={matches.length}
|
||||
currentMatch={hasMatches ? currentMatchIndex + 1 : 0}
|
||||
onPrev={prev}
|
||||
onNext={next}
|
||||
inputName="config-find"
|
||||
placeholder="Find in config..."
|
||||
/>
|
||||
|
||||
<div className="flex-1 p-0 sm:p-4 overflow-hidden relative w-full">
|
||||
<div className="relative h-full w-full">
|
||||
<div
|
||||
ref={backdropRef}
|
||||
aria-hidden="true"
|
||||
className={`pointer-events-none absolute inset-0 overflow-hidden whitespace-pre-wrap break-words font-mono text-[16px] sm:text-xs md:text-sm px-3 py-2 border border-transparent rounded-none sm:rounded-md ${hasMatches && !isTextareaFocused ? 'text-foreground' : 'text-transparent'}`}
|
||||
>
|
||||
{renderHighlightedContent(isTextareaFocused)}
|
||||
</div>
|
||||
<Textarea
|
||||
<div className="min-h-0 flex-1 overflow-hidden sm:p-4">
|
||||
<CodeEditor
|
||||
id="edit-config-content"
|
||||
ref={editTextareaRef}
|
||||
ariaLabel="Config content"
|
||||
value={editConfigContent}
|
||||
onChange={(e) => {
|
||||
setEditConfigContent(e.target.value)
|
||||
onChange={(next) => {
|
||||
setEditConfigContent(next)
|
||||
resetErrors()
|
||||
}}
|
||||
onScroll={syncBackdropScroll}
|
||||
onFocus={() => setIsTextareaFocused(true)}
|
||||
onBlur={() => setIsTextareaFocused(false)}
|
||||
spellCheck={false}
|
||||
className={`relative bg-transparent font-mono text-[16px] sm:text-xs md:text-sm resize-none h-full w-full rounded-none sm:rounded-md ${hasMatches && !isTextareaFocused ? 'text-transparent caret-foreground' : ''} ${editErrorLine ? 'error-highlight' : ''}`}
|
||||
highlights={matches}
|
||||
activeHighlightIndex={currentMatchIndex}
|
||||
activeLine={activeLine}
|
||||
revealNonce={revealNonce}
|
||||
autoFocus={!isMobile}
|
||||
disabled={isSaving}
|
||||
className="sm:rounded-md sm:border sm:border-input"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{editError && (
|
||||
<div className="absolute bottom-0 left-0 right-0 bg-background/95 border-t p-2 sm:p-3 space-y-2">
|
||||
<p className="text-xs sm:text-sm text-red-500 break-words">
|
||||
<div className="max-h-40 shrink-0 space-y-2 overflow-y-auto border-t bg-background p-3">
|
||||
<p className="break-words text-xs text-red-500 sm:text-sm">
|
||||
{editError}
|
||||
{editErrorLine && (
|
||||
<span className="ml-2 text-xs">(Line {editErrorLine})</span>
|
||||
{editErrorLine != null && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => revealLine(editErrorLine)}
|
||||
className="ml-2 h-10 rounded px-2 text-xs underline underline-offset-2 md:h-8"
|
||||
>
|
||||
Go to line {editErrorLine}
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
{validationIssues.length > 0 && (
|
||||
<ul className="max-h-28 overflow-auto space-y-1 text-xs sm:text-sm text-red-500 list-disc pl-4">
|
||||
<ul className="max-h-28 space-y-1 pl-4 text-xs text-red-500 list-disc sm:text-sm">
|
||||
{validationIssues.map((issue) => (
|
||||
<li key={getIssueText(issue)}>{getIssueText(issue)}</li>
|
||||
<li key={getIssueText(issue)}>
|
||||
{issue.line != null ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => revealLine(issue.line)}
|
||||
className="min-h-10 w-full text-left underline underline-offset-2 md:min-h-0"
|
||||
>
|
||||
{getIssueText(issue)}{' '}
|
||||
<span className="text-muted-foreground">(line {issue.line})</span>
|
||||
</button>
|
||||
) : (
|
||||
getIssueText(issue)
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{removedFields.length > 0 && (
|
||||
<p className="text-xs sm:text-sm text-amber-600 break-words">
|
||||
<p className="break-words text-xs text-amber-600 sm:text-sm">
|
||||
Removed invalid fields: {removedFields.join(', ')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="p-3 sm:p-4 border-t gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onClose}
|
||||
className="flex-1 sm:flex-none"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={updateConfig}
|
||||
disabled={isUpdating || !editConfigContent.trim()}
|
||||
className="flex-1 sm:flex-none"
|
||||
>
|
||||
{isUpdating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
Update
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<DialogFooter data-editor-footer className="shrink-0 gap-2 border-t p-3 pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:p-4 sm:pb-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={requestClose}
|
||||
disabled={isSaving}
|
||||
className="flex-1 sm:flex-none"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={updateConfig}
|
||||
disabled={isSaving || !editConfigContent.trim()}
|
||||
className="flex-1 sm:flex-none"
|
||||
>
|
||||
{isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Update
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<UnsavedChangesDialog
|
||||
open={isDiscardPromptOpen}
|
||||
onOpenChange={(open) => !open && setIsDiscardPromptOpen(false)}
|
||||
onDiscard={discardAndClose}
|
||||
onKeepEditing={() => setIsDiscardPromptOpen(false)}
|
||||
itemName={config.name}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { render, screen, waitFor, fireEvent } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { OpenCodeConfigManager } from './OpenCodeConfigManager'
|
||||
@@ -176,4 +176,46 @@ describe('OpenCodeConfigManager', () => {
|
||||
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('anchors the AGENTS.md card to the settings dialog scrollport', async () => {
|
||||
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
|
||||
const header = await screen.findByRole('button', { name: /Global Agent Instructions/i })
|
||||
const card = header.parentElement
|
||||
expect(card?.className).toContain('overflow-clip')
|
||||
expect(card?.className).not.toContain('overflow-hidden')
|
||||
})
|
||||
|
||||
it('keeps the editor mounted while the post-save config refresh is in flight', async () => {
|
||||
const configWithRaw: OpenCodeConfig = {
|
||||
...defaultConfig,
|
||||
rawContent: '{\n "theme": "system"\n}',
|
||||
}
|
||||
mockGetOpenCodeConfigs.mockResolvedValueOnce({ configs: [configWithRaw] })
|
||||
let resolveRefresh!: () => void
|
||||
mockGetOpenCodeConfigs.mockReturnValueOnce(
|
||||
new Promise<{ configs: OpenCodeConfig[] }>((resolve) => {
|
||||
resolveRefresh = () => resolve({ configs: [configWithRaw] })
|
||||
}),
|
||||
)
|
||||
mockUpdateOpenCodeConfig.mockResolvedValue(configWithRaw)
|
||||
|
||||
const user = userEvent.setup()
|
||||
const { container } = renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
|
||||
|
||||
await screen.findByText('GPT-4o')
|
||||
const editIcon = container.querySelector('.lucide-square-pen') as SVGElement
|
||||
const editButton = editIcon.closest('button') as HTMLButtonElement
|
||||
await user.click(editButton)
|
||||
|
||||
const textarea = await screen.findByLabelText('Config content') as HTMLTextAreaElement
|
||||
fireEvent.change(textarea, { target: { value: configWithRaw.rawContent! + ' ' } })
|
||||
await user.click(screen.getByRole('button', { name: 'Update' }))
|
||||
|
||||
await waitFor(() => expect(mockUpdateOpenCodeConfig).toHaveBeenCalledTimes(1))
|
||||
expect(screen.getByText('Edit Config: default')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Update' })).toBeDisabled()
|
||||
|
||||
resolveRefresh()
|
||||
await waitFor(() => expect(screen.queryByText('Edit Config: default')).not.toBeInTheDocument())
|
||||
})
|
||||
})
|
||||
@@ -154,15 +154,15 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
return getApiErrorMessage(error, 'Failed to import existing OpenCode host data')
|
||||
}
|
||||
|
||||
const fetchConfigs = async () => {
|
||||
const fetchConfigs = async (silent = false) => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
if (!silent) setIsLoading(true)
|
||||
const data = await settingsApi.getOpenCodeConfigs()
|
||||
setConfigs(data.configs)
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch configs:', error)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
if (!silent) setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -677,7 +677,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
showToast.loading('Saving configuration...', { id: 'edit-config' })
|
||||
try {
|
||||
const result = await settingsApi.updateOpenCodeConfig(editingConfig.name, { content: rawContent })
|
||||
await fetchConfigs()
|
||||
await fetchConfigs(true)
|
||||
const successMsg = result.restartRequired
|
||||
? 'Configuration saved. Restart the server to apply changes.'
|
||||
: 'Configuration saved'
|
||||
@@ -688,13 +688,12 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
throw error
|
||||
}
|
||||
}}
|
||||
isUpdating={isUpdating}
|
||||
/>
|
||||
|
||||
{/* Global AGENTS.md Section */}
|
||||
<div className="mt-8 space-y-6">
|
||||
<div className="border-t border-border pt-6">
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0 mb-6">
|
||||
<div className="bg-card border border-border rounded-lg overflow-clip min-w-0 mb-6">
|
||||
<button
|
||||
ref={agentsMdRef}
|
||||
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.agentsMd ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { SettingsDialog } from './SettingsDialog'
|
||||
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
|
||||
|
||||
vi.mock('@/components/settings/GeneralSettings', () => ({
|
||||
GeneralSettings: () => <div data-testid="general-settings">General Settings Content</div>,
|
||||
@@ -119,4 +120,37 @@ describe('SettingsDialog', () => {
|
||||
expect(screen.getAllByText('OpenCode').length).toBeGreaterThanOrEqual(1)
|
||||
expect(screen.getAllByText('Providers').length).toBeGreaterThanOrEqual(1)
|
||||
})
|
||||
|
||||
it('keeps Settings open when Escape fires inside a nested dialog', () => {
|
||||
function TestWrapper() {
|
||||
const location = useLocation()
|
||||
const settingsOpen = new URLSearchParams(location.search).get('settings') === 'open'
|
||||
return (
|
||||
<>
|
||||
{settingsOpen && <span data-testid="settings-open" />}
|
||||
<SettingsDialog />
|
||||
<Dialog open>
|
||||
<DialogContent data-testid="nested-dialog">
|
||||
<DialogTitle className="sr-only">Nested</DialogTitle>
|
||||
<textarea data-testid="nested-input" />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/?settings=open']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('settings-open')).toBeInTheDocument()
|
||||
|
||||
const nestedInput = screen.getByTestId('nested-input')
|
||||
nestedInput.focus()
|
||||
fireEvent.keyDown(nestedInput, { key: 'Escape' })
|
||||
|
||||
expect(screen.getByTestId('settings-open')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -67,6 +67,13 @@ export function SettingsDialog() {
|
||||
}
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && !isVersionDialogOpen) {
|
||||
const target = e.target
|
||||
if (target instanceof Element) {
|
||||
const closestDialog = target.closest('[role="dialog"]')
|
||||
if (closestDialog && !closestDialog.hasAttribute('data-settings-dialog')) {
|
||||
return
|
||||
}
|
||||
}
|
||||
close()
|
||||
}
|
||||
}
|
||||
@@ -100,7 +107,7 @@ export function SettingsDialog() {
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} modal={false} onOpenChange={(open) => !open && close()}>
|
||||
<DialogContent
|
||||
<DialogContent
|
||||
className="inset-0 w-full h-full max-w-none max-h-none p-0 rounded-none bg-gradient-to-br from-background via-background to-background border-border overflow-hidden !flex !flex-col !gap-0"
|
||||
fullscreen
|
||||
canSwipeBack={() => mobileView !== 'menu'}
|
||||
@@ -108,6 +115,7 @@ export function SettingsDialog() {
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
onFocusOutside={(e) => e.preventDefault()}
|
||||
onPointerDownOutside={(e) => e.preventDefault()}
|
||||
data-settings-dialog
|
||||
>
|
||||
<DialogTitle className="sr-only">Settings</DialogTitle>
|
||||
<div className="hidden sm:flex sm:flex-col sm:h-full sm:min-h-0">
|
||||
|
||||
@@ -82,7 +82,8 @@ describe('SkillsEditor', () => {
|
||||
await user.click(screen.getByText('Install Skill'))
|
||||
|
||||
const urlInput = screen.getByPlaceholderText('Paste a GitHub skill URL')
|
||||
await user.type(urlInput, 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach')
|
||||
await user.click(urlInput)
|
||||
await user.paste('https://github.com/mattpocock/skills/tree/main/skills/productivity/teach')
|
||||
|
||||
await user.click(screen.getByText('Install'))
|
||||
|
||||
@@ -143,7 +144,8 @@ describe('SkillsEditor', () => {
|
||||
await user.click(screen.getByText('Install Skill'))
|
||||
|
||||
const urlInput = screen.getByPlaceholderText('Paste a GitHub skill URL')
|
||||
await user.type(urlInput, 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach')
|
||||
await user.click(urlInput)
|
||||
await user.paste('https://github.com/mattpocock/skills/tree/main/skills/productivity/teach')
|
||||
|
||||
await user.click(screen.getByText('Install'))
|
||||
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { CodeEditor } from './code-editor'
|
||||
|
||||
describe('CodeEditor', () => {
|
||||
it('renders a line number for every logical line', () => {
|
||||
render(<CodeEditor value={'{\n "a": 1\n}'} onChange={vi.fn()} ariaLabel="config" />)
|
||||
expect(screen.getByText('1')).toBeInTheDocument()
|
||||
expect(screen.getByText('2')).toBeInTheDocument()
|
||||
expect(screen.getByText('3')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders a trailing empty line number when the value ends in a newline', () => {
|
||||
render(<CodeEditor value={'a\n'} onChange={vi.fn()} ariaLabel="config" />)
|
||||
expect(screen.getByText('2')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports edits through onChange', async () => {
|
||||
const onChange = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
render(<CodeEditor value="" onChange={onChange} ariaLabel="config" />)
|
||||
await user.type(screen.getByLabelText('config'), 'x')
|
||||
expect(onChange).toHaveBeenCalledWith('x')
|
||||
})
|
||||
|
||||
it('applies identical font, wrap and tab metrics to the textarea and the mirror', () => {
|
||||
const { container } = render(<CodeEditor value={'a'} onChange={vi.fn()} ariaLabel="config" />)
|
||||
const textarea = screen.getByLabelText('config')
|
||||
const mirror = container.querySelector('[data-editor-mirror]') as HTMLElement
|
||||
for (const token of ['font-mono', 'text-[16px]', 'min-[769px]:text-sm', 'leading-6', '[tab-size:2]', 'whitespace-pre-wrap', '[overflow-wrap:anywhere]', 'py-2', 'pr-3', 'pl-10', '[scrollbar-gutter:stable]']) {
|
||||
expect(textarea.className).toContain(token)
|
||||
expect(mirror.className).toContain(token)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the mirror hidden from assistive tech', () => {
|
||||
const { container } = render(<CodeEditor value={'a'} onChange={vi.fn()} ariaLabel="config" />)
|
||||
expect(container.querySelector('[data-editor-mirror]')).toHaveAttribute('aria-hidden', 'true')
|
||||
})
|
||||
|
||||
it('mirrors textarea scrolling', () => {
|
||||
const { container } = render(<CodeEditor value={'a\nb\nc'} onChange={vi.fn()} ariaLabel="config" />)
|
||||
const textarea = screen.getByLabelText('config') as HTMLTextAreaElement
|
||||
const mirror = container.querySelector('[data-editor-mirror]') as HTMLElement
|
||||
textarea.scrollTop = 120
|
||||
textarea.dispatchEvent(new Event('scroll', { bubbles: true }))
|
||||
expect(mirror.scrollTop).toBe(120)
|
||||
})
|
||||
|
||||
const HIGHLIGHT_VALUE = '{\n "model": "sonnet",\n "theme": "sonnet"\n}'
|
||||
|
||||
it('renders a mark for each highlight', () => {
|
||||
const { container } = render(
|
||||
<CodeEditor value={HIGHLIGHT_VALUE} onChange={vi.fn()} ariaLabel="config"
|
||||
highlights={[{ startIndex: 14, endIndex: 20 }, { startIndex: 35, endIndex: 41 }]} activeHighlightIndex={0} />,
|
||||
)
|
||||
const marks = container.querySelectorAll('mark')
|
||||
expect(marks).toHaveLength(2)
|
||||
expect(marks[0]).toHaveTextContent('sonnet')
|
||||
})
|
||||
|
||||
it('flags only the active match', () => {
|
||||
const { container } = render(
|
||||
<CodeEditor value={HIGHLIGHT_VALUE} onChange={vi.fn()} ariaLabel="config"
|
||||
highlights={[{ startIndex: 14, endIndex: 20 }, { startIndex: 35, endIndex: 41 }]} activeHighlightIndex={1} />,
|
||||
)
|
||||
const active = container.querySelectorAll('mark[data-active-match="true"]')
|
||||
expect(active).toHaveLength(1)
|
||||
expect(active[0]).toBe(container.querySelectorAll('mark')[1])
|
||||
})
|
||||
|
||||
it('keeps highlights rendered while the textarea is focused', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { container } = render(
|
||||
<CodeEditor value={HIGHLIGHT_VALUE} onChange={vi.fn()} ariaLabel="config"
|
||||
highlights={[{ startIndex: 14, endIndex: 20 }]} activeHighlightIndex={0} />,
|
||||
)
|
||||
await user.click(screen.getByLabelText('config'))
|
||||
expect(container.querySelectorAll('mark')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('hides the textarea glyphs only while highlights are active', () => {
|
||||
const { container, rerender } = render(<CodeEditor value={HIGHLIGHT_VALUE} onChange={vi.fn()} ariaLabel="config" />)
|
||||
expect(screen.getByLabelText('config').className).not.toContain('text-transparent')
|
||||
expect((container.querySelector('[data-editor-mirror]') as HTMLElement).className).toContain('text-transparent')
|
||||
|
||||
rerender(<CodeEditor value={HIGHLIGHT_VALUE} onChange={vi.fn()} ariaLabel="config"
|
||||
highlights={[{ startIndex: 14, endIndex: 20 }]} activeHighlightIndex={0} />)
|
||||
expect(screen.getByLabelText('config').className).toContain('text-transparent')
|
||||
expect((container.querySelector('[data-editor-mirror]') as HTMLElement).className).not.toContain('text-transparent')
|
||||
})
|
||||
|
||||
it('splits a highlight that spans a newline across both rows', () => {
|
||||
const { container } = render(
|
||||
<CodeEditor value={'abc\ndef'} onChange={vi.fn()} ariaLabel="config"
|
||||
highlights={[{ startIndex: 2, endIndex: 5 }]} activeHighlightIndex={0} />,
|
||||
)
|
||||
const rows = container.querySelectorAll('[data-line]')
|
||||
expect(rows[0].querySelector('mark')).toHaveTextContent('c')
|
||||
expect(rows[1].querySelector('mark')).toHaveTextContent('d')
|
||||
const active = container.querySelectorAll('mark[data-active-match="true"]')
|
||||
expect(active).toHaveLength(1)
|
||||
expect(active[0]).toBe(rows[0].querySelector('mark'))
|
||||
})
|
||||
|
||||
it('buckets out-of-order highlights to the correct rows without re-scanning', () => {
|
||||
const { container } = render(
|
||||
<CodeEditor value={'aaaa\nbbbb\ncccc\ndddd'} onChange={vi.fn()} ariaLabel="config"
|
||||
highlights={[
|
||||
{ startIndex: 10, endIndex: 14 },
|
||||
{ startIndex: 0, endIndex: 2 },
|
||||
]} activeHighlightIndex={0} />,
|
||||
)
|
||||
const rows = container.querySelectorAll('[data-line]')
|
||||
expect(rows[0].querySelector('mark')).toHaveTextContent('aa')
|
||||
expect(rows[2].querySelector('mark')).toHaveTextContent('cccc')
|
||||
expect(container.querySelectorAll('mark')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('marks the active line row', () => {
|
||||
const { container } = render(<CodeEditor value={'a\nb\nc'} onChange={vi.fn()} ariaLabel="config" activeLine={2} />)
|
||||
const banded = container.querySelectorAll('[data-active-line]')
|
||||
expect(banded).toHaveLength(1)
|
||||
expect(banded[0].closest('[data-line]')).toHaveAttribute('data-line', '2')
|
||||
})
|
||||
|
||||
it('flags the active line number', () => {
|
||||
const { container } = render(<CodeEditor value={'a\nb\nc'} onChange={vi.fn()} ariaLabel="config" activeLine={2} />)
|
||||
const number = container.querySelector('[data-line="2"] [data-line-number]') as HTMLElement
|
||||
expect(number.className).toContain('text-destructive')
|
||||
})
|
||||
|
||||
it('scrolls the active line into view', () => {
|
||||
const longValue = Array.from({ length: 40 }, (_, i) => `line ${i}`).join('\n')
|
||||
const { container, rerender } = render(<CodeEditor value={longValue} onChange={vi.fn()} ariaLabel="config" />)
|
||||
const textarea = screen.getByLabelText('config') as HTMLTextAreaElement
|
||||
Object.defineProperty(textarea, 'clientHeight', { configurable: true, value: 200 })
|
||||
Object.defineProperty(textarea, 'scrollHeight', { configurable: true, value: 960 })
|
||||
const row = container.querySelector('[data-line="30"]') as HTMLElement
|
||||
Object.defineProperty(row, 'offsetTop', { configurable: true, value: 700 })
|
||||
Object.defineProperty(row, 'offsetHeight', { configurable: true, value: 24 })
|
||||
|
||||
rerender(<CodeEditor value={longValue} onChange={vi.fn()} ariaLabel="config" activeLine={30} />)
|
||||
|
||||
const mirror = container.querySelector('[data-editor-mirror]') as HTMLElement
|
||||
expect(textarea.scrollTop).toBe(612)
|
||||
expect(mirror.scrollTop).toBe(612)
|
||||
})
|
||||
|
||||
function rect(top: number, height: number): DOMRect {
|
||||
return {
|
||||
top,
|
||||
bottom: top + height,
|
||||
left: 0,
|
||||
right: 0,
|
||||
width: 0,
|
||||
height,
|
||||
x: 0,
|
||||
y: top,
|
||||
toJSON: () => ({}),
|
||||
} as DOMRect
|
||||
}
|
||||
|
||||
function patchRect(target: Element, value: DOMRect) {
|
||||
Object.defineProperty(target, 'getBoundingClientRect', {
|
||||
configurable: true,
|
||||
value: () => value,
|
||||
})
|
||||
}
|
||||
|
||||
it('reveals the active match at the bottom of a tall wrapped line', () => {
|
||||
const startMatch = 'needleStart'
|
||||
const endMatch = 'needleEnd'
|
||||
const longValue = startMatch + 'x'.repeat(2000) + endMatch
|
||||
const startIdx = 0
|
||||
const startEnd = startMatch.length
|
||||
const endIdx = longValue.indexOf(endMatch)
|
||||
const endEnd = endIdx + endMatch.length
|
||||
|
||||
const { container, rerender } = render(
|
||||
<CodeEditor value={longValue} onChange={vi.fn()} ariaLabel="config"
|
||||
highlights={[
|
||||
{ startIndex: startIdx, endIndex: startEnd },
|
||||
{ startIndex: endIdx, endIndex: endEnd },
|
||||
]} activeHighlightIndex={1} />,
|
||||
)
|
||||
const textarea = screen.getByLabelText('config') as HTMLTextAreaElement
|
||||
Object.defineProperty(textarea, 'clientHeight', { configurable: true, value: 200 })
|
||||
Object.defineProperty(textarea, 'scrollHeight', { configurable: true, value: 1600 })
|
||||
const mirror = container.querySelector('[data-editor-mirror]') as HTMLElement
|
||||
patchRect(mirror, rect(0, 1600))
|
||||
const marks = container.querySelectorAll('mark')
|
||||
patchRect(marks[1], rect(1500, 24))
|
||||
|
||||
rerender(
|
||||
<CodeEditor value={longValue} onChange={vi.fn()} ariaLabel="config"
|
||||
highlights={[
|
||||
{ startIndex: startIdx, endIndex: startEnd },
|
||||
{ startIndex: endIdx, endIndex: endEnd },
|
||||
]} activeHighlightIndex={1} revealNonce={1} />,
|
||||
)
|
||||
expect(textarea.scrollTop).toBe(1400)
|
||||
expect(mirror.scrollTop).toBe(1400)
|
||||
})
|
||||
|
||||
it('reveals the active match at the top of a tall wrapped line', () => {
|
||||
const startMatch = 'needleStart'
|
||||
const endMatch = 'needleEnd'
|
||||
const longValue = startMatch + 'x'.repeat(2000) + endMatch
|
||||
const startIdx = 0
|
||||
const startEnd = startMatch.length
|
||||
const endIdx = longValue.indexOf(endMatch)
|
||||
const endEnd = endIdx + endMatch.length
|
||||
|
||||
const { container, rerender } = render(
|
||||
<CodeEditor value={longValue} onChange={vi.fn()} ariaLabel="config"
|
||||
highlights={[
|
||||
{ startIndex: startIdx, endIndex: startEnd },
|
||||
{ startIndex: endIdx, endIndex: endEnd },
|
||||
]} activeHighlightIndex={0} />,
|
||||
)
|
||||
const textarea = screen.getByLabelText('config') as HTMLTextAreaElement
|
||||
Object.defineProperty(textarea, 'clientHeight', { configurable: true, value: 200 })
|
||||
Object.defineProperty(textarea, 'scrollHeight', { configurable: true, value: 1600 })
|
||||
const mirror = container.querySelector('[data-editor-mirror]') as HTMLElement
|
||||
patchRect(mirror, rect(0, 1600))
|
||||
const marks = container.querySelectorAll('mark')
|
||||
patchRect(marks[0], rect(0, 24))
|
||||
|
||||
rerender(
|
||||
<CodeEditor value={longValue} onChange={vi.fn()} ariaLabel="config"
|
||||
highlights={[
|
||||
{ startIndex: startIdx, endIndex: startEnd },
|
||||
{ startIndex: endIdx, endIndex: endEnd },
|
||||
]} activeHighlightIndex={0} revealNonce={1} />,
|
||||
)
|
||||
expect(textarea.scrollTop).toBe(0)
|
||||
expect(mirror.scrollTop).toBe(0)
|
||||
})
|
||||
|
||||
it('falls back to line reveal when the active mark is not present', () => {
|
||||
const longValue = Array.from({ length: 40 }, (_, i) => `line ${i}`).join('\n')
|
||||
const startIdx = 0
|
||||
const startEnd = 4
|
||||
|
||||
const { container, rerender } = render(
|
||||
<CodeEditor value={longValue} onChange={vi.fn()} ariaLabel="config"
|
||||
highlights={[{ startIndex: startIdx, endIndex: startEnd }]} activeHighlightIndex={0} />,
|
||||
)
|
||||
const textarea = screen.getByLabelText('config') as HTMLTextAreaElement
|
||||
Object.defineProperty(textarea, 'clientHeight', { configurable: true, value: 200 })
|
||||
Object.defineProperty(textarea, 'scrollHeight', { configurable: true, value: 960 })
|
||||
const mirror = container.querySelector('[data-editor-mirror]') as HTMLElement
|
||||
patchRect(mirror, rect(0, 0))
|
||||
const marks = container.querySelectorAll('mark')
|
||||
patchRect(marks[0], rect(0, 0))
|
||||
|
||||
rerender(
|
||||
<CodeEditor value={longValue} onChange={vi.fn()} ariaLabel="config"
|
||||
highlights={[{ startIndex: startIdx, endIndex: startEnd }]} activeHighlightIndex={0} revealNonce={1} />,
|
||||
)
|
||||
expect(textarea.scrollTop).toBe(0)
|
||||
})
|
||||
|
||||
it('leaves the scroll position alone while typing away from the active match', () => {
|
||||
const value = 'needle\n' + Array.from({ length: 40 }, (_, i) => `line ${i}`).join('\n')
|
||||
|
||||
const { container, rerender } = render(
|
||||
<CodeEditor value={value} onChange={vi.fn()} ariaLabel="config"
|
||||
highlights={[{ startIndex: 0, endIndex: 6 }]} activeHighlightIndex={0} />,
|
||||
)
|
||||
const textarea = screen.getByLabelText('config') as HTMLTextAreaElement
|
||||
Object.defineProperty(textarea, 'clientHeight', { configurable: true, value: 200 })
|
||||
Object.defineProperty(textarea, 'scrollHeight', { configurable: true, value: 960 })
|
||||
const mirror = container.querySelector('[data-editor-mirror]') as HTMLElement
|
||||
patchRect(mirror, rect(0, 960))
|
||||
patchRect(container.querySelectorAll('mark')[0], rect(0, 24))
|
||||
|
||||
textarea.scrollTop = 500
|
||||
mirror.scrollTop = 500
|
||||
|
||||
rerender(
|
||||
<CodeEditor value={`${value}\ntrailing`} onChange={vi.fn()} ariaLabel="config"
|
||||
highlights={[{ startIndex: 0, endIndex: 6 }]} activeHighlightIndex={0} />,
|
||||
)
|
||||
|
||||
expect(textarea.scrollTop).toBe(500)
|
||||
expect(mirror.scrollTop).toBe(500)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,292 @@
|
||||
import { useMemo, useRef, useEffect, forwardRef, useCallback, memo, type ReactNode } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { computeScrollTopForRow } from '@/lib/editorScroll'
|
||||
|
||||
interface CodeEditorHighlight {
|
||||
startIndex: number
|
||||
endIndex: number
|
||||
}
|
||||
|
||||
interface CodeEditorProps {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
highlights?: CodeEditorHighlight[]
|
||||
activeHighlightIndex?: number
|
||||
activeLine?: number | null
|
||||
revealNonce?: number
|
||||
autoFocus?: boolean
|
||||
disabled?: boolean
|
||||
placeholder?: string
|
||||
id?: string
|
||||
ariaLabel: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
const SURFACE_CLASS =
|
||||
'font-mono text-[16px] min-[769px]:text-sm leading-6 [tab-size:2] whitespace-pre-wrap [overflow-wrap:anywhere] py-2 pr-3 pl-10 [scrollbar-gutter:stable]'
|
||||
|
||||
interface RowHighlight {
|
||||
start: number
|
||||
end: number
|
||||
index: number
|
||||
first: boolean
|
||||
}
|
||||
|
||||
const EMPTY_ROW_HIGHLIGHTS: RowHighlight[] = []
|
||||
|
||||
function lineNumberForOffset(lineStarts: number[], offset: number): number {
|
||||
let lo = 0
|
||||
let hi = lineStarts.length - 1
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi + 1) >> 1
|
||||
if (lineStarts[mid] <= offset) lo = mid
|
||||
else hi = mid - 1
|
||||
}
|
||||
return lo + 1
|
||||
}
|
||||
|
||||
interface EditorRowProps {
|
||||
line: string
|
||||
lineNumber: number
|
||||
isActiveLine: boolean
|
||||
highlights: RowHighlight[]
|
||||
activeHighlightIndex?: number
|
||||
}
|
||||
|
||||
const EditorRow = memo(function EditorRow({
|
||||
line,
|
||||
lineNumber,
|
||||
isActiveLine,
|
||||
highlights,
|
||||
activeHighlightIndex,
|
||||
}: EditorRowProps) {
|
||||
return (
|
||||
<div data-line={lineNumber} className="relative">
|
||||
<span
|
||||
data-line-number
|
||||
className={cn(
|
||||
'pointer-events-none absolute -left-10 top-0 w-10 select-none pr-2 text-right',
|
||||
isActiveLine ? 'text-destructive font-semibold' : 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{lineNumber}
|
||||
</span>
|
||||
{isActiveLine && (
|
||||
<span
|
||||
data-active-line
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute inset-y-0 -left-10 -right-3 bg-destructive/15"
|
||||
/>
|
||||
)}
|
||||
{highlights.length === 0
|
||||
? line.length > 0
|
||||
? line
|
||||
: '\u200b'
|
||||
: highlights.map((h, i) => {
|
||||
const previous = i === 0 ? 0 : highlights[i - 1].end
|
||||
const nodes: ReactNode[] = []
|
||||
if (h.start > previous) {
|
||||
nodes.push(line.substring(previous, h.start))
|
||||
}
|
||||
nodes.push(
|
||||
<mark
|
||||
key={h.index}
|
||||
data-active-match={h.first && h.index === activeHighlightIndex ? 'true' : undefined}
|
||||
className={
|
||||
h.index === activeHighlightIndex
|
||||
? 'rounded-sm bg-orange-400 text-black'
|
||||
: 'rounded-sm bg-yellow-300/60 text-black'
|
||||
}
|
||||
>
|
||||
{line.substring(h.start, h.end)}
|
||||
</mark>,
|
||||
)
|
||||
if (i === highlights.length - 1 && h.end < line.length) {
|
||||
nodes.push(line.substring(h.end))
|
||||
}
|
||||
return <span key={`frag-${h.index}`}>{nodes}</span>
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export const CodeEditor = forwardRef<HTMLTextAreaElement, CodeEditorProps>(function CodeEditor(
|
||||
{
|
||||
value,
|
||||
onChange,
|
||||
highlights,
|
||||
activeHighlightIndex,
|
||||
activeLine,
|
||||
revealNonce = 0,
|
||||
autoFocus,
|
||||
disabled,
|
||||
placeholder,
|
||||
id,
|
||||
ariaLabel,
|
||||
className,
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const lines = useMemo(() => value.split('\n'), [value])
|
||||
|
||||
const lineStarts = useMemo(() => {
|
||||
const starts: number[] = []
|
||||
let acc = 0
|
||||
for (const line of lines) {
|
||||
starts.push(acc)
|
||||
acc += line.length + 1
|
||||
}
|
||||
return starts
|
||||
}, [lines])
|
||||
|
||||
const rowHighlights = useMemo<RowHighlight[][] | null>(() => {
|
||||
if (!highlights?.length) return null
|
||||
const buckets: RowHighlight[][] = lines.map(() => [])
|
||||
const ordered = highlights
|
||||
.map((h, index) => ({ startIndex: h.startIndex, endIndex: h.endIndex, index }))
|
||||
.sort((a, b) => a.startIndex - b.startIndex)
|
||||
let cursor = 0
|
||||
for (const highlight of ordered) {
|
||||
while (cursor < lines.length && lineStarts[cursor] + lines[cursor].length < highlight.startIndex) {
|
||||
cursor += 1
|
||||
}
|
||||
let line = cursor
|
||||
let isFirst = true
|
||||
while (line < lines.length) {
|
||||
const lineStart = lineStarts[line]
|
||||
if (lineStart > highlight.endIndex) break
|
||||
const lineEnd = lineStart + lines[line].length
|
||||
if (highlight.endIndex > lineStart && highlight.startIndex < lineEnd) {
|
||||
buckets[line].push({
|
||||
start: Math.max(highlight.startIndex, lineStart) - lineStart,
|
||||
end: Math.min(highlight.endIndex, lineEnd) - lineStart,
|
||||
index: highlight.index,
|
||||
first: isFirst,
|
||||
})
|
||||
isFirst = false
|
||||
}
|
||||
line += 1
|
||||
}
|
||||
}
|
||||
return buckets
|
||||
}, [highlights, lines, lineStarts])
|
||||
|
||||
const hasHighlights = (highlights?.length ?? 0) > 0
|
||||
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null)
|
||||
const mirrorRef = useRef<HTMLDivElement | null>(null)
|
||||
|
||||
const syncMirrorScroll = useCallback(() => {
|
||||
const textarea = textareaRef.current
|
||||
const mirror = mirrorRef.current
|
||||
if (!textarea || !mirror) return
|
||||
mirror.scrollTop = textarea.scrollTop
|
||||
mirror.scrollLeft = textarea.scrollLeft
|
||||
}, [])
|
||||
|
||||
const combinedRef = useCallback(
|
||||
(node: HTMLTextAreaElement | null) => {
|
||||
textareaRef.current = node
|
||||
if (typeof ref === 'function') {
|
||||
ref(node)
|
||||
} else if (ref) {
|
||||
ref.current = node
|
||||
}
|
||||
},
|
||||
[ref],
|
||||
)
|
||||
|
||||
const revealRange = useCallback((top: number, height: number) => {
|
||||
const textarea = textareaRef.current
|
||||
const mirror = mirrorRef.current
|
||||
if (!textarea || !mirror) return
|
||||
const next = computeScrollTopForRow({
|
||||
rowTop: top,
|
||||
rowHeight: height,
|
||||
viewportHeight: textarea.clientHeight,
|
||||
maxScrollTop: Math.max(0, textarea.scrollHeight - textarea.clientHeight),
|
||||
})
|
||||
textarea.scrollTop = next
|
||||
mirror.scrollTop = next
|
||||
}, [])
|
||||
|
||||
const revealLine = useCallback((lineNumber: number) => {
|
||||
const mirror = mirrorRef.current
|
||||
const row = mirror?.querySelector<HTMLElement>(`[data-line="${lineNumber}"]`)
|
||||
if (!row) return
|
||||
revealRange(row.offsetTop, row.offsetHeight)
|
||||
}, [revealRange])
|
||||
|
||||
const revealActiveMark = useCallback(() => {
|
||||
const mirror = mirrorRef.current
|
||||
const mark = mirror?.querySelector<HTMLElement>('mark[data-active-match="true"]')
|
||||
if (!mirror || !mark) return false
|
||||
const mirrorRect = mirror.getBoundingClientRect()
|
||||
const markRect = mark.getBoundingClientRect()
|
||||
revealRange(markRect.top - mirrorRect.top + mirror.scrollTop, markRect.height)
|
||||
return true
|
||||
}, [revealRange])
|
||||
|
||||
useEffect(() => {
|
||||
if (activeLine == null) return
|
||||
revealLine(activeLine)
|
||||
}, [activeLine, revealNonce, revealLine])
|
||||
|
||||
const activeHighlightStart =
|
||||
activeHighlightIndex == null ? null : highlights?.[activeHighlightIndex]?.startIndex ?? null
|
||||
|
||||
const lineStartsRef = useRef(lineStarts)
|
||||
lineStartsRef.current = lineStarts
|
||||
|
||||
useEffect(() => {
|
||||
if (activeHighlightStart == null) return
|
||||
if (revealActiveMark()) return
|
||||
revealLine(lineNumberForOffset(lineStartsRef.current, activeHighlightStart))
|
||||
}, [activeHighlightStart, revealNonce, revealLine, revealActiveMark])
|
||||
|
||||
return (
|
||||
<div className={cn('relative h-full w-full overflow-hidden', className)}>
|
||||
<div
|
||||
ref={mirrorRef}
|
||||
aria-hidden="true"
|
||||
data-editor-mirror
|
||||
className={cn(
|
||||
'pointer-events-none absolute inset-0 overflow-hidden',
|
||||
SURFACE_CLASS,
|
||||
hasHighlights ? 'text-foreground' : 'text-transparent',
|
||||
)}
|
||||
>
|
||||
{lines.map((line, index) => (
|
||||
<EditorRow
|
||||
key={index}
|
||||
line={line}
|
||||
lineNumber={index + 1}
|
||||
isActiveLine={activeLine === index + 1}
|
||||
highlights={rowHighlights?.[index] ?? EMPTY_ROW_HIGHLIGHTS}
|
||||
activeHighlightIndex={activeHighlightIndex}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<textarea
|
||||
id={id}
|
||||
ref={combinedRef}
|
||||
aria-label={ariaLabel}
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
autoFocus={autoFocus}
|
||||
spellCheck={false}
|
||||
autoCapitalize="off"
|
||||
autoCorrect="off"
|
||||
autoComplete="off"
|
||||
disabled={disabled}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
onScroll={syncMirrorScroll}
|
||||
className={cn(
|
||||
'absolute inset-0 h-full w-full resize-none border-0 bg-transparent outline-none',
|
||||
SURFACE_CLASS,
|
||||
hasHighlights ? 'text-transparent caret-foreground' : undefined,
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
|
||||
interface ConfirmDestructiveDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
title: string
|
||||
description: ReactNode
|
||||
warning?: ReactNode
|
||||
confirmLabel: string
|
||||
pendingLabel?: string
|
||||
cancelLabel?: string
|
||||
isPending?: boolean
|
||||
}
|
||||
|
||||
export function ConfirmDestructiveDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
title,
|
||||
description,
|
||||
warning,
|
||||
confirmLabel,
|
||||
pendingLabel,
|
||||
cancelLabel = 'Cancel',
|
||||
isPending = false,
|
||||
}: ConfirmDestructiveDialogProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-[90%] sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{warning && (
|
||||
<Alert className="overflow-hidden">
|
||||
<AlertTriangle className="h-4 w-4 flex-shrink-0" />
|
||||
<AlertDescription className="break-all">{warning}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<DialogFooter className="gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onCancel}
|
||||
disabled={isPending}
|
||||
className="flex-1 sm:flex-none"
|
||||
>
|
||||
{cancelLabel}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={onConfirm}
|
||||
disabled={isPending}
|
||||
className="flex-1 sm:flex-none bg-red-600 hover:bg-red-700 text-white font-semibold border-red-600"
|
||||
>
|
||||
{isPending && pendingLabel ? pendingLabel : confirmLabel}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
|
||||
|
||||
interface DeleteDialogProps {
|
||||
open: boolean
|
||||
@@ -9,55 +7,35 @@ interface DeleteDialogProps {
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
title: string
|
||||
description: React.ReactNode
|
||||
description: ReactNode
|
||||
itemName?: string
|
||||
isDeleting?: boolean
|
||||
}
|
||||
|
||||
export function DeleteDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
title,
|
||||
description,
|
||||
export function DeleteDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
title,
|
||||
description,
|
||||
itemName,
|
||||
isDeleting = false
|
||||
isDeleting = false
|
||||
}: DeleteDialogProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className='max-w-[90%] sm:max-w-sm'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{description}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{itemName && (
|
||||
<Alert className="overflow-hidden">
|
||||
<AlertTriangle className="h-4 w-4 flex-shrink-0" />
|
||||
<AlertDescription className="break-all">
|
||||
This will permanently delete "<span className="font-medium">{itemName}</span>". This action cannot be undone.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<DialogFooter className='gap-2'>
|
||||
<Button variant="outline" onClick={onCancel} disabled={isDeleting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={onConfirm}
|
||||
disabled={isDeleting}
|
||||
className="bg-red-600 hover:bg-red-700 text-white font-semibold border-red-600"
|
||||
>
|
||||
{isDeleting && 'Deleting...'}
|
||||
{!isDeleting && (title.includes('Configuration') ? 'Delete Configuration' : 'Delete')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<ConfirmDestructiveDialog
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
onConfirm={onConfirm}
|
||||
onCancel={onCancel}
|
||||
title={title}
|
||||
description={description}
|
||||
warning={itemName ? (
|
||||
<>This will permanently delete "<span className="font-medium">{itemName}</span>". This action cannot be undone.</>
|
||||
) : undefined}
|
||||
confirmLabel={title.includes('Configuration') ? 'Delete Configuration' : 'Delete'}
|
||||
pendingLabel="Deleting..."
|
||||
isPending={isDeleting}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { render, screen, act } from "@testing-library/react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -382,3 +382,87 @@ describe("DialogContent", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function stubVisualViewport(height: number) {
|
||||
const listeners = new Set<() => void>()
|
||||
Object.defineProperty(window, 'visualViewport', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: {
|
||||
height,
|
||||
offsetTop: 0,
|
||||
addEventListener: (_: string, fn: () => void) => listeners.add(fn),
|
||||
removeEventListener: (_: string, fn: () => void) => listeners.delete(fn),
|
||||
},
|
||||
})
|
||||
return listeners
|
||||
}
|
||||
|
||||
describe('keyboardAware', () => {
|
||||
const originalInnerHeight = window.innerHeight
|
||||
const originalVisualViewport = Object.getOwnPropertyDescriptor(window, 'visualViewport')
|
||||
|
||||
afterEach(() => {
|
||||
if (originalVisualViewport) {
|
||||
Object.defineProperty(window, 'visualViewport', originalVisualViewport)
|
||||
} else {
|
||||
// @ts-expect-error allow delete
|
||||
delete window.visualViewport
|
||||
}
|
||||
Object.defineProperty(window, 'innerHeight', {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
value: originalInnerHeight,
|
||||
})
|
||||
})
|
||||
|
||||
it('applies keyboard inset as bottom padding when keyboardAware and a text input is focused', () => {
|
||||
window.innerHeight = 800
|
||||
const listeners = stubVisualViewport(500)
|
||||
render(
|
||||
<Dialog open>
|
||||
<DialogContent keyboardAware mobileFullscreen data-testid="dialog-content">
|
||||
<textarea autoFocus data-testid="dialog-input" />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
screen.getByTestId('dialog-input').focus()
|
||||
act(() => {
|
||||
listeners.forEach((fn) => fn())
|
||||
})
|
||||
const content = screen.getByTestId('dialog-content')
|
||||
expect(content).toHaveStyle({ paddingBottom: '300px' })
|
||||
})
|
||||
|
||||
it('does not set inline bottom padding when no keyboard is present', () => {
|
||||
window.innerHeight = 800
|
||||
const listeners = stubVisualViewport(800)
|
||||
render(
|
||||
<Dialog open>
|
||||
<DialogContent keyboardAware mobileFullscreen data-testid="dialog-content">
|
||||
<textarea autoFocus data-testid="dialog-input" />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
screen.getByTestId('dialog-input').focus()
|
||||
listeners.forEach((fn) => fn())
|
||||
const content = screen.getByTestId('dialog-content')
|
||||
expect(content.style.paddingBottom).toBe('')
|
||||
})
|
||||
|
||||
it('does not set inline bottom padding when keyboardAware is omitted', () => {
|
||||
window.innerHeight = 800
|
||||
const listeners = stubVisualViewport(500)
|
||||
render(
|
||||
<Dialog open>
|
||||
<DialogContent mobileFullscreen data-testid="dialog-content">
|
||||
<textarea autoFocus data-testid="dialog-input" />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
screen.getByTestId('dialog-input').focus()
|
||||
listeners.forEach((fn) => fn())
|
||||
const content = screen.getByTestId('dialog-content')
|
||||
expect(content.style.paddingBottom).toBe('')
|
||||
})
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import { X } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { useSwipeBack } from '@/hooks/useMobile'
|
||||
import { useVisualViewport } from '@/hooks/useVisualViewport'
|
||||
|
||||
const DialogOpenContext = React.createContext<boolean>(true)
|
||||
|
||||
@@ -42,6 +43,7 @@ interface DialogContentProps
|
||||
fullscreen?: boolean
|
||||
mobileFullscreen?: boolean
|
||||
mobileSwipeToClose?: boolean
|
||||
keyboardAware?: boolean
|
||||
canSwipeBack?: () => boolean
|
||||
onSwipeBack?: () => void
|
||||
onOpenChange?: (open: boolean) => void
|
||||
@@ -51,17 +53,18 @@ interface DialogContentProps
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
DialogContentProps
|
||||
>(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, mobileSwipeToClose, canSwipeBack, onSwipeBack, overlayClassName, style, ...props }, ref) => {
|
||||
>(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, mobileSwipeToClose, keyboardAware, canSwipeBack, onSwipeBack, overlayClassName, style, ...props }, ref) => {
|
||||
const isMobileFullscreenMode = fullscreen || mobileFullscreen
|
||||
const isDialogOpen = React.useContext(DialogOpenContext)
|
||||
const [isMobile, setIsMobile] = React.useState(() => typeof window !== 'undefined' ? window.innerWidth < 768 : false)
|
||||
const shouldEnableMobileSwipe = mobileSwipeToClose !== false && isMobile && isDialogOpen
|
||||
const shouldAnimateSwipe = shouldEnableMobileSwipe && isMobileFullscreenMode
|
||||
const swipeContainerRef = React.useRef<HTMLDivElement>(null)
|
||||
const { keyboardHeight } = useVisualViewport({ enabled: keyboardAware === true && isDialogOpen })
|
||||
const [swipeContainer, setSwipeContainer] = React.useState<HTMLDivElement | null>(null)
|
||||
const closeTriggerRef = React.useRef<HTMLButtonElement>(null)
|
||||
|
||||
const combinedRef = React.useCallback((node: HTMLDivElement | null) => {
|
||||
swipeContainerRef.current = node
|
||||
setSwipeContainer(node)
|
||||
if (typeof ref === 'function') {
|
||||
ref(node)
|
||||
} else if (ref) {
|
||||
@@ -81,10 +84,10 @@ const DialogContent = React.forwardRef<
|
||||
|
||||
React.useEffect(() => {
|
||||
if (shouldEnableMobileSwipe) {
|
||||
return swipeBind(swipeContainerRef.current)
|
||||
return swipeBind(swipeContainer)
|
||||
}
|
||||
return undefined
|
||||
}, [shouldEnableMobileSwipe, swipeBind])
|
||||
}, [shouldEnableMobileSwipe, swipeBind, swipeContainer])
|
||||
|
||||
const baseStyle = isMobileFullscreenMode
|
||||
? { paddingTop: 'env(safe-area-inset-top, 0px)' }
|
||||
@@ -94,6 +97,7 @@ const DialogContent = React.forwardRef<
|
||||
...baseStyle,
|
||||
...style,
|
||||
...(shouldAnimateSwipe ? swipeStyles : undefined),
|
||||
...(keyboardAware && keyboardHeight > 0 ? { paddingBottom: `${keyboardHeight}px` } : undefined),
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
|
||||
|
||||
interface DiscardDialogProps {
|
||||
open: boolean
|
||||
@@ -23,37 +20,17 @@ export function DiscardDialog({
|
||||
const itemText = fileCount === 1 ? '1 file' : `${fileCount} files`
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className='max-w-[90%] sm:max-w-sm'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Discard Changes</DialogTitle>
|
||||
<DialogDescription>
|
||||
Are you sure you want to discard changes to {itemText}? This action cannot be undone.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<Alert className="overflow-hidden">
|
||||
<AlertTriangle className="h-4 w-4 flex-shrink-0" />
|
||||
<AlertDescription>
|
||||
This will permanently delete your uncommitted changes to {itemText}. If these changes exist in the staging area, they will also be removed.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<DialogFooter className='gap-2'>
|
||||
<Button variant="outline" onClick={onCancel} disabled={isDiscarding}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={onConfirm}
|
||||
disabled={isDiscarding}
|
||||
className="bg-red-600 hover:bg-red-700 text-white font-semibold border-red-600"
|
||||
>
|
||||
{isDiscarding && 'Discarding...'}
|
||||
{!isDiscarding && 'Discard'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<ConfirmDestructiveDialog
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
onConfirm={onConfirm}
|
||||
onCancel={onCancel}
|
||||
title="Discard Changes"
|
||||
description={`Are you sure you want to discard changes to ${itemText}? This action cannot be undone.`}
|
||||
warning={`This will permanently delete your uncommitted changes to ${itemText}. If these changes exist in the staging area, they will also be removed.`}
|
||||
confirmLabel="Discard"
|
||||
pendingLabel="Discarding..."
|
||||
isPending={isDiscarding}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { EditorFindBar } from './editor-find-bar'
|
||||
|
||||
const baseProps = {
|
||||
query: '',
|
||||
onQueryChange: vi.fn(),
|
||||
matchCount: 0,
|
||||
currentMatch: 0,
|
||||
onPrev: vi.fn(),
|
||||
onNext: vi.fn(),
|
||||
inputName: 'config-find',
|
||||
}
|
||||
|
||||
describe('EditorFindBar', () => {
|
||||
it('hides the match counter when the query is empty', () => {
|
||||
render(<EditorFindBar {...baseProps} />)
|
||||
expect(screen.queryByTestId('find-match-count')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports the current match position', () => {
|
||||
render(<EditorFindBar {...baseProps} query="model" matchCount={3} currentMatch={2} />)
|
||||
expect(screen.getByTestId('find-match-count')).toHaveTextContent('2 of 3')
|
||||
})
|
||||
|
||||
it('reports zero matches', () => {
|
||||
render(<EditorFindBar {...baseProps} query="zzz" matchCount={0} currentMatch={0} />)
|
||||
expect(screen.getByTestId('find-match-count')).toHaveTextContent('0 matches')
|
||||
})
|
||||
|
||||
it('disables navigation when there are no matches', () => {
|
||||
render(<EditorFindBar {...baseProps} query="zzz" />)
|
||||
expect(screen.getByRole('button', { name: 'Previous match' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Next match' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('advances on Enter and goes back on Shift+Enter', async () => {
|
||||
const onNext = vi.fn()
|
||||
const onPrev = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
render(<EditorFindBar {...baseProps} query="model" matchCount={2} currentMatch={1} onNext={onNext} onPrev={onPrev} />)
|
||||
const input = screen.getByRole('textbox', { name: 'Find in content' })
|
||||
await user.click(input)
|
||||
await user.keyboard('{Enter}')
|
||||
expect(onNext).toHaveBeenCalledTimes(1)
|
||||
await user.keyboard('{Shift>}{Enter}{/Shift}')
|
||||
expect(onPrev).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('sizes navigation controls for touch on mobile', () => {
|
||||
render(<EditorFindBar {...baseProps} query="model" matchCount={1} currentMatch={1} />)
|
||||
const next = screen.getByRole('button', { name: 'Next match' })
|
||||
expect(next.className).toContain('size-10')
|
||||
expect(next.className).toContain('md:size-8')
|
||||
})
|
||||
|
||||
it('uses a 16px input on mobile to prevent iOS zoom', () => {
|
||||
render(<EditorFindBar {...baseProps} />)
|
||||
expect(screen.getByRole('textbox', { name: 'Find in content' }).className).toContain('text-[16px]')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,83 @@
|
||||
import { Search, ChevronUp, ChevronDown } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface EditorFindBarProps {
|
||||
query: string
|
||||
onQueryChange: (query: string) => void
|
||||
matchCount: number
|
||||
currentMatch: number
|
||||
onPrev: () => void
|
||||
onNext: () => void
|
||||
inputName: string
|
||||
placeholder?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function EditorFindBar({
|
||||
query,
|
||||
onQueryChange,
|
||||
matchCount,
|
||||
currentMatch,
|
||||
onPrev,
|
||||
onNext,
|
||||
inputName,
|
||||
placeholder = 'Find in content...',
|
||||
className,
|
||||
}: EditorFindBarProps) {
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
if (e.shiftKey) onPrev()
|
||||
else onNext()
|
||||
}
|
||||
}
|
||||
|
||||
const noMatches = matchCount === 0
|
||||
|
||||
return (
|
||||
<div className={cn('flex shrink-0 items-center gap-2 border-b bg-muted/30 px-3 py-2', className)}>
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(e) => onQueryChange(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={placeholder}
|
||||
aria-label="Find in content"
|
||||
autoComplete="off"
|
||||
name={inputName}
|
||||
className="pl-9 h-10 md:h-9 text-[16px] md:text-sm"
|
||||
/>
|
||||
</div>
|
||||
{query && (
|
||||
<span data-testid="find-match-count" className="whitespace-nowrap text-xs text-muted-foreground">
|
||||
{matchCount > 0 ? `${currentMatch} of ${matchCount}` : '0 matches'}
|
||||
</span>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-lg"
|
||||
className="md:size-8"
|
||||
aria-label="Previous match"
|
||||
disabled={noMatches}
|
||||
onClick={onPrev}
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-lg"
|
||||
className="md:size-8"
|
||||
aria-label="Next match"
|
||||
disabled={noMatches}
|
||||
onClick={onNext}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
|
||||
|
||||
interface UnsavedChangesDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onDiscard: () => void
|
||||
onKeepEditing: () => void
|
||||
itemName?: string
|
||||
}
|
||||
|
||||
export function UnsavedChangesDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onDiscard,
|
||||
onKeepEditing,
|
||||
itemName,
|
||||
}: UnsavedChangesDialogProps) {
|
||||
return (
|
||||
<ConfirmDestructiveDialog
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
onConfirm={onDiscard}
|
||||
onCancel={onKeepEditing}
|
||||
title="Unsaved Changes"
|
||||
description={itemName ? `You have unsaved edits to ${itemName}.` : 'You have unsaved edits.'}
|
||||
warning="Discarding will permanently lose these edits."
|
||||
confirmLabel="Discard"
|
||||
cancelLabel="Keep Editing"
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback, useRef, type CSSProperties } from 're
|
||||
import { useSwipeNavigation } from '@/contexts/SwipeNavigationContext'
|
||||
|
||||
export function useMobile() {
|
||||
const [isMobile, setIsMobile] = useState(false)
|
||||
const [isMobile, setIsMobile] = useState(() => (typeof window !== 'undefined' ? window.innerWidth < 768 : false))
|
||||
|
||||
useEffect(() => {
|
||||
const checkMobile = () => {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { act, renderHook } from '@testing-library/react'
|
||||
import { useVisualViewport } from './useVisualViewport'
|
||||
|
||||
interface StubViewport {
|
||||
height: number
|
||||
offsetTop: number
|
||||
listeners: Set<() => void>
|
||||
}
|
||||
|
||||
function stubVisualViewport(height: number): StubViewport {
|
||||
const listeners = new Set<() => void>()
|
||||
Object.defineProperty(window, 'visualViewport', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: {
|
||||
height,
|
||||
offsetTop: 0,
|
||||
addEventListener: (_: string, fn: () => void) => listeners.add(fn),
|
||||
removeEventListener: (_: string, fn: () => void) => listeners.delete(fn),
|
||||
},
|
||||
})
|
||||
return { height, offsetTop: 0, listeners }
|
||||
}
|
||||
|
||||
function createInput(id: string): HTMLInputElement {
|
||||
const input = document.createElement('input')
|
||||
input.id = id
|
||||
document.body.appendChild(input)
|
||||
return input
|
||||
}
|
||||
|
||||
describe('useVisualViewport', () => {
|
||||
const originalVisualViewport = Object.getOwnPropertyDescriptor(window, 'visualViewport')
|
||||
const originalInnerHeight = window.innerHeight
|
||||
|
||||
afterEach(() => {
|
||||
if (originalVisualViewport) {
|
||||
Object.defineProperty(window, 'visualViewport', originalVisualViewport)
|
||||
} else {
|
||||
// @ts-expect-error allow delete
|
||||
delete window.visualViewport
|
||||
}
|
||||
Object.defineProperty(window, 'innerHeight', {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
value: originalInnerHeight,
|
||||
})
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
it('returns 0 when disabled', () => {
|
||||
stubVisualViewport(500)
|
||||
const { result } = renderHook(() => useVisualViewport({ enabled: false }))
|
||||
expect(result.current.keyboardHeight).toBe(0)
|
||||
})
|
||||
|
||||
it('reports the keyboard height when a text input is focused', () => {
|
||||
window.innerHeight = 800
|
||||
const viewport = stubVisualViewport(500)
|
||||
const input = createInput('a')
|
||||
const { result } = renderHook(() => useVisualViewport())
|
||||
act(() => {
|
||||
input.focus()
|
||||
viewport.listeners.forEach((fn) => fn())
|
||||
})
|
||||
expect(result.current.keyboardHeight).toBe(300)
|
||||
})
|
||||
|
||||
it('preserves the keyboard inset when focus transfers between text inputs', () => {
|
||||
window.innerHeight = 800
|
||||
const viewport = stubVisualViewport(500)
|
||||
const first = createInput('a')
|
||||
const second = createInput('b')
|
||||
const { result } = renderHook(() => useVisualViewport())
|
||||
|
||||
act(() => {
|
||||
first.focus()
|
||||
viewport.listeners.forEach((fn) => fn())
|
||||
})
|
||||
expect(result.current.keyboardHeight).toBe(300)
|
||||
|
||||
act(() => {
|
||||
second.focus()
|
||||
})
|
||||
expect(result.current.keyboardHeight).toBe(300)
|
||||
})
|
||||
|
||||
it('drops the keyboard inset when focus leaves all text inputs', () => {
|
||||
window.innerHeight = 800
|
||||
const viewport = stubVisualViewport(500)
|
||||
const input = createInput('a')
|
||||
const { result } = renderHook(() => useVisualViewport())
|
||||
|
||||
act(() => {
|
||||
input.focus()
|
||||
viewport.listeners.forEach((fn) => fn())
|
||||
})
|
||||
expect(result.current.keyboardHeight).toBe(300)
|
||||
|
||||
act(() => {
|
||||
input.blur()
|
||||
})
|
||||
expect(result.current.keyboardHeight).toBe(0)
|
||||
})
|
||||
|
||||
it('does not subscribe to visualViewport when disabled', () => {
|
||||
const viewport = stubVisualViewport(500)
|
||||
const addEventListener = vi.fn()
|
||||
Object.defineProperty(window, 'visualViewport', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: {
|
||||
height: 500,
|
||||
offsetTop: 0,
|
||||
addEventListener,
|
||||
removeEventListener: vi.fn(),
|
||||
},
|
||||
})
|
||||
renderHook(() => useVisualViewport({ enabled: false }))
|
||||
expect(addEventListener).not.toHaveBeenCalled()
|
||||
void viewport
|
||||
})
|
||||
})
|
||||
@@ -7,10 +7,18 @@ const isTextInputFocused = () => {
|
||||
return tag === 'TEXTAREA' || tag === 'INPUT' || (el as HTMLElement).isContentEditable
|
||||
}
|
||||
|
||||
export function useVisualViewport() {
|
||||
interface UseVisualViewportOptions {
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
export function useVisualViewport({ enabled = true }: UseVisualViewportOptions = {}) {
|
||||
const [keyboardHeight, setKeyboardHeight] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
setKeyboardHeight(0)
|
||||
return
|
||||
}
|
||||
const viewport = window.visualViewport
|
||||
if (!viewport) return
|
||||
|
||||
@@ -27,6 +35,7 @@ export function useVisualViewport() {
|
||||
|
||||
viewport.addEventListener('resize', update)
|
||||
viewport.addEventListener('scroll', update)
|
||||
window.addEventListener('focusin', update)
|
||||
window.addEventListener('focusout', update)
|
||||
window.addEventListener('pageshow', update)
|
||||
document.addEventListener('visibilitychange', update)
|
||||
@@ -35,11 +44,12 @@ export function useVisualViewport() {
|
||||
return () => {
|
||||
viewport.removeEventListener('resize', update)
|
||||
viewport.removeEventListener('scroll', update)
|
||||
window.removeEventListener('focusin', update)
|
||||
window.removeEventListener('focusout', update)
|
||||
window.removeEventListener('pageshow', update)
|
||||
document.removeEventListener('visibilitychange', update)
|
||||
}
|
||||
}, [])
|
||||
}, [enabled])
|
||||
|
||||
return { keyboardHeight }
|
||||
}
|
||||
@@ -414,24 +414,3 @@ input:-webkit-autofill:active {
|
||||
.animate-progress {
|
||||
animation: progress 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* Error line highlighting - red-orange selection color */
|
||||
.error-highlight::selection {
|
||||
background-color: #fecaca;
|
||||
color: #991b1b;
|
||||
}
|
||||
|
||||
.dark .error-highlight::selection {
|
||||
background-color: #7f1d1d;
|
||||
color: #fecaca;
|
||||
}
|
||||
|
||||
.error-highlight::-moz-selection {
|
||||
background-color: #fecaca;
|
||||
color: #991b1b;
|
||||
}
|
||||
|
||||
.dark .error-highlight::-moz-selection {
|
||||
background-color: #7f1d1d;
|
||||
color: #fecaca;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { computeScrollTopForRow } from './editorScroll'
|
||||
|
||||
describe('computeScrollTopForRow', () => {
|
||||
it('centres the row in the viewport', () => {
|
||||
expect(computeScrollTopForRow({ rowTop: 500, rowHeight: 24, viewportHeight: 200, maxScrollTop: 1000 })).toBe(412)
|
||||
})
|
||||
|
||||
it('clamps to zero when the row is near the top', () => {
|
||||
expect(computeScrollTopForRow({ rowTop: 8, rowHeight: 24, viewportHeight: 400, maxScrollTop: 1000 })).toBe(0)
|
||||
})
|
||||
|
||||
it('clamps to maxScrollTop when the row is near the end', () => {
|
||||
expect(computeScrollTopForRow({ rowTop: 980, rowHeight: 24, viewportHeight: 200, maxScrollTop: 800 })).toBe(800)
|
||||
})
|
||||
|
||||
it('returns zero when the content is shorter than the viewport', () => {
|
||||
expect(computeScrollTopForRow({ rowTop: 48, rowHeight: 24, viewportHeight: 400, maxScrollTop: 0 })).toBe(0)
|
||||
})
|
||||
|
||||
it('tolerates an unmeasured viewport', () => {
|
||||
expect(computeScrollTopForRow({ rowTop: 100, rowHeight: 0, viewportHeight: 0, maxScrollTop: 0 })).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
interface RowScrollInput {
|
||||
rowTop: number
|
||||
rowHeight: number
|
||||
viewportHeight: number
|
||||
maxScrollTop: number
|
||||
}
|
||||
|
||||
export function computeScrollTopForRow({ rowTop, rowHeight, viewportHeight, maxScrollTop }: RowScrollInput): number {
|
||||
const centred = rowTop - viewportHeight / 2 + rowHeight / 2
|
||||
const upperBound = Math.max(0, maxScrollTop)
|
||||
return Math.min(Math.max(0, centred), upperBound)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseJsonc, parseJsoncErrorLine, resolveJsoncIssueLine } from './jsonc'
|
||||
|
||||
const CONFIG = `{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"theme": "system",
|
||||
"model": "anthropic/claude-sonnet-4",
|
||||
"provider": {
|
||||
"anthropic": {
|
||||
"options": {
|
||||
"apiKey": "sk-test"
|
||||
}
|
||||
}
|
||||
}
|
||||
}`
|
||||
|
||||
describe('parseJsoncErrorLine', () => {
|
||||
it('extracts the line from a parseJsonc SyntaxError', () => {
|
||||
let line: number | null = null
|
||||
try {
|
||||
parseJsonc('{\n "a": 1,\n "b" 2\n}')
|
||||
} catch (error) {
|
||||
line = parseJsoncErrorLine(error)
|
||||
}
|
||||
expect(line).toBe(3)
|
||||
})
|
||||
|
||||
it('returns null for a non-syntax error', () => {
|
||||
expect(parseJsoncErrorLine(new Error('network down'))).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for a syntax error with no location', () => {
|
||||
expect(parseJsoncErrorLine(new SyntaxError('Invalid JSONC'))).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveJsoncIssueLine', () => {
|
||||
it('resolves a top-level property to its line', () => {
|
||||
expect(resolveJsoncIssueLine(CONFIG, 'theme')).toBe(3)
|
||||
})
|
||||
|
||||
it('resolves a nested property path', () => {
|
||||
expect(resolveJsoncIssueLine(CONFIG, 'provider.anthropic.options.apiKey')).toBe(8)
|
||||
})
|
||||
|
||||
it('resolves a structured property path containing a dotted object key', () => {
|
||||
const dotted = `{
|
||||
"provider": {
|
||||
"api.example.com": {
|
||||
"key": "x"
|
||||
}
|
||||
}
|
||||
}`
|
||||
expect(resolveJsoncIssueLine(dotted, ['provider', 'api.example.com', 'key'])).toBe(4)
|
||||
})
|
||||
|
||||
it('resolves a structured array index path', () => {
|
||||
expect(resolveJsoncIssueLine('{\n "tools": [\n "a",\n "b"\n ]\n}', ['tools', 1])).toBe(4)
|
||||
})
|
||||
|
||||
it('returns null for an unknown structured path', () => {
|
||||
expect(resolveJsoncIssueLine(CONFIG, ['provider', 'anthropic', 'missing'])).toBeNull()
|
||||
})
|
||||
|
||||
it('resolves an array index segment', () => {
|
||||
expect(resolveJsoncIssueLine('{\n "tools": [\n "a",\n "b"\n ]\n}', 'tools.1')).toBe(4)
|
||||
})
|
||||
|
||||
it('returns null for an unknown path', () => {
|
||||
expect(resolveJsoncIssueLine(CONFIG, 'nope.missing')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for the synthetic root path', () => {
|
||||
expect(resolveJsoncIssueLine(CONFIG, 'root')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when the content cannot be parsed into a tree', () => {
|
||||
expect(resolveJsoncIssueLine('', 'theme')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,12 @@
|
||||
export { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
export { parseJsonc, parseJsoncErrorLine } from '@opencode-manager/shared/utils'
|
||||
import { findJsoncLineForPath, parseJsoncPathSegments } from '@opencode-manager/shared/utils'
|
||||
|
||||
export function resolveJsoncIssueLine(content: string, path: PropertyKey[] | string): number | null {
|
||||
const segments = Array.isArray(path)
|
||||
? path.map((segment) => (typeof segment === 'number' ? segment : String(segment)))
|
||||
: parseJsoncPathSegments(path)
|
||||
return findJsoncLineForPath(content, segments)
|
||||
}
|
||||
|
||||
export function hasJsoncComments(content: string): boolean {
|
||||
return content.split('\n').some(line => {
|
||||
|
||||
@@ -16,12 +16,14 @@ interface UseFindInTextReturn {
|
||||
clear: () => void
|
||||
}
|
||||
|
||||
const EMPTY_MATCHES: FindMatch[] = []
|
||||
|
||||
export function useFindInText(text: string): UseFindInTextReturn {
|
||||
const [query, setQueryState] = useState('')
|
||||
const [currentMatchIndex, setCurrentMatchIndex] = useState(0)
|
||||
|
||||
const matches = useMemo(() => {
|
||||
if (!query.trim()) return []
|
||||
if (!query.trim()) return EMPTY_MATCHES
|
||||
const results: FindMatch[] = []
|
||||
const lowerText = text.toLowerCase()
|
||||
const lowerQuery = query.toLowerCase()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { parse as parseJsoncLib, type ParseError } from 'jsonc-parser'
|
||||
import { parse as parseJsoncLib, parseTree, findNodeAtLocation, type ParseError, type JSONPath } from 'jsonc-parser'
|
||||
|
||||
export function parseJsonc<T = unknown>(content: string): T {
|
||||
const errors: ParseError[] = []
|
||||
@@ -40,6 +40,26 @@ function getErrorMessageByCode(error: number): string {
|
||||
8: 'Unexpected end of input',
|
||||
9: 'Invalid comment',
|
||||
}
|
||||
|
||||
|
||||
return errorMessages[error] || 'Invalid JSONC'
|
||||
}
|
||||
|
||||
export function parseJsoncErrorLine(error: unknown): number | null {
|
||||
if (!(error instanceof SyntaxError)) return null
|
||||
const match = error.message.match(/at line (\d+)/)
|
||||
return match ? Number(match[1]) : null
|
||||
}
|
||||
|
||||
export function findJsoncLineForPath(content: string, path: JSONPath): number | null {
|
||||
if (path.length === 0) return null
|
||||
const root = parseTree(content, [], { allowTrailingComma: true, disallowComments: false })
|
||||
if (!root) return null
|
||||
const node = findNodeAtLocation(root, path)
|
||||
if (!node) return null
|
||||
return content.substring(0, node.offset).split('\n').length
|
||||
}
|
||||
|
||||
export function parseJsoncPathSegments(path: string): JSONPath {
|
||||
if (!path || path === 'root') return []
|
||||
return path.split('.').map((segment) => (/^\d+$/.test(segment) ? Number(segment) : segment))
|
||||
}
|
||||
Reference in new issue
Block a user