mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 02:47:34 +00:00
fix(diffs): preserve note navigation and current reading bindings
This commit is contained in:
@@ -0,0 +1,248 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, renderHook } from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { useAppStore } from '@/store'
|
||||
import { consumeDiffCommentScrollCommand } from './diff-comment-scroll-command'
|
||||
import {
|
||||
createScrollCommandFixture,
|
||||
flushScrollCommand,
|
||||
scrollNote
|
||||
} from './diff-comment-scroll.test-fixture'
|
||||
|
||||
vi.mock('monaco-editor', () => import('monaco-editor/esm/vs/editor/editor.api.js'))
|
||||
vi.mock('../right-sidebar/source-control/panel/worktree-scope', () => ({
|
||||
useSourceControlScope: () => null,
|
||||
sourceControlScopeRuntimeEnvironmentId: () => undefined
|
||||
}))
|
||||
afterEach(() => {
|
||||
useAppStore.getState().setScrollToDiffCommentId(null)
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('cancels through the real owner and accepts the actual batched same-note opener without stale consumption', async () => {
|
||||
const fixture = createScrollCommandFixture()
|
||||
const surface = fixture.bindEditor()
|
||||
const hook = renderHook(() => fixture.useSurface(surface))
|
||||
try {
|
||||
await act(async () => {
|
||||
hook.result.current.handleOpenComment(scrollNote)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
const canceled = fixture.combinedScrollRequestRef.current!
|
||||
expect(canceled.isCurrent()).toBe(true)
|
||||
await act(async () => {
|
||||
fixture.owner.input(0)
|
||||
surface.navigation.zoneMeasured(scrollNote.id)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBeNull()
|
||||
expect(fixture.combinedScrollRequestRef.current).toBeNull()
|
||||
await act(async () => {
|
||||
hook.result.current.handleOpenComment(scrollNote)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
const old = fixture.combinedScrollRequestRef.current!
|
||||
await act(async () => {
|
||||
hook.result.current.handleOpenComment(scrollNote)
|
||||
old.consume(() => {
|
||||
throw new Error('Old same-note callback consumed successor')
|
||||
})
|
||||
old.cancel()
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBe('note')
|
||||
expect(fixture.combinedScrollRequestRef.current).not.toBe(old)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
const current = fixture.combinedScrollRequestRef.current!
|
||||
await act(async () => {
|
||||
useAppStore.getState().setScrollToDiffCommentId('different')
|
||||
current.consume(() => {
|
||||
throw new Error('Old callback consumed different note')
|
||||
})
|
||||
current.cancel()
|
||||
await flushScrollCommand()
|
||||
})
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBe('different')
|
||||
await act(async () => {
|
||||
hook.result.current.handleOpenComment(scrollNote)
|
||||
canceled.cancel()
|
||||
fixture.setReady(true)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBeNull()
|
||||
expect(fixture.owner.getScrollTop()).toBe(700)
|
||||
} finally {
|
||||
hook.unmount()
|
||||
fixture.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves a command across native release but cancels it when input arrives during the binding gap', async () => {
|
||||
const fixture = createScrollCommandFixture()
|
||||
const hook = renderHook(({ surface }) => fixture.useSurface(surface), {
|
||||
initialProps: { surface: fixture.bindEditor() }
|
||||
})
|
||||
try {
|
||||
await act(async () => {
|
||||
hook.result.current.handleOpenComment(scrollNote)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
const old = fixture.combinedScrollRequestRef.current!
|
||||
await act(async () => {
|
||||
fixture.owner.releaseItemNavigation(fixture.item)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBe('note')
|
||||
expect(fixture.combinedScrollRequestRef.current).toBeNull()
|
||||
await act(async () => {
|
||||
fixture.owner.input(0)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBeNull()
|
||||
hook.rerender({ surface: fixture.bindEditor() })
|
||||
expect(fixture.combinedScrollRequestRef.current).toBeNull()
|
||||
await act(async () => {
|
||||
hook.result.current.handleOpenComment(scrollNote)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
await act(async () => {
|
||||
fixture.owner.releaseItemNavigation(fixture.item)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
hook.rerender({ surface: fixture.bindEditor() })
|
||||
expect(fixture.combinedScrollRequestRef.current).not.toBeNull()
|
||||
await act(async () => {
|
||||
old.consume(() => {
|
||||
throw new Error('Released binding consumed a new attempt')
|
||||
})
|
||||
fixture.setReady(true)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBeNull()
|
||||
expect(fixture.owner.getScrollTop()).toBe(700)
|
||||
} finally {
|
||||
hook.unmount()
|
||||
fixture.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps a superseded single-file frame from consuming the newer same-note opening', async () => {
|
||||
const frames: FrameRequestCallback[] = []
|
||||
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => frames.push(callback))
|
||||
vi.stubGlobal('cancelAnimationFrame', () => {})
|
||||
const fixture = createScrollCommandFixture()
|
||||
const surface = fixture.bindEditor(false)
|
||||
const hook = renderHook(() => fixture.useSurface(surface))
|
||||
try {
|
||||
await act(async () => {
|
||||
hook.result.current.handleOpenComment(scrollNote)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
const oldFrame = frames.at(-1)!
|
||||
await act(async () => {
|
||||
hook.result.current.handleOpenComment(scrollNote)
|
||||
oldFrame(0)
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBe('note')
|
||||
await flushScrollCommand()
|
||||
})
|
||||
await act(async () => {
|
||||
frames.at(-1)!(0)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
expect(surface.editor.getScrollTop()).toBe(580)
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBeNull()
|
||||
} finally {
|
||||
hook.unmount()
|
||||
fixture.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps note navigation through an overlay-only rebuild and releases actual zone lifetimes', async () => {
|
||||
const fixture = createScrollCommandFixture()
|
||||
let surface: ReturnType<typeof fixture.bindEditor> | null = fixture.bindEditor()
|
||||
const consumed = vi.fn(consumeDiffCommentScrollCommand)
|
||||
const hook = renderHook(
|
||||
({
|
||||
current,
|
||||
label
|
||||
}: {
|
||||
current: ReturnType<typeof fixture.bindEditor> | null
|
||||
label: string
|
||||
}) => fixture.useDecoratorSurface(current, label, consumed),
|
||||
{ initialProps: { current: surface, label: 'Add note' } }
|
||||
)
|
||||
const mountCard = async (): Promise<void> => {
|
||||
await act(async () => {
|
||||
await flushScrollCommand()
|
||||
})
|
||||
const zone = [...surface!.fake.zones.values()][0]
|
||||
expect(zone).toBeDefined()
|
||||
surface!.fake.domNode.append(zone.domNode)
|
||||
zone.domNode.style.padding = '0px'
|
||||
const card = zone.domNode.firstElementChild
|
||||
expect(card).toBeInstanceOf(HTMLElement)
|
||||
Object.defineProperty(card, 'offsetHeight', { configurable: true, value: 152 })
|
||||
card!.getBoundingClientRect = () => new DOMRect(0, 0, 400, 152)
|
||||
await act(async () => {
|
||||
surface!.layout()
|
||||
await flushScrollCommand()
|
||||
})
|
||||
}
|
||||
try {
|
||||
await mountCard()
|
||||
await act(async () => {
|
||||
hook.result.current.handleOpenComment(scrollNote)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBe('note')
|
||||
hook.rerender({ current: surface, label: 'Add a note' })
|
||||
await act(async () => {
|
||||
fixture.setReady(true)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
expect(fixture.owner.getScrollTop()).toBe(700)
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBeNull()
|
||||
expect(consumed.mock.calls).toEqual([['note']])
|
||||
|
||||
await act(async () => {
|
||||
fixture.setReady(false)
|
||||
hook.result.current.handleOpenComment(scrollNote)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
hook.rerender({ current: null, label: 'Add a note' })
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBe('note')
|
||||
await act(async () => {
|
||||
fixture.owner.input(0)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBeNull()
|
||||
surface = fixture.bindEditor()
|
||||
hook.rerender({ current: surface, label: 'Add a note' })
|
||||
await mountCard()
|
||||
await act(async () => {
|
||||
fixture.setReady(true)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
expect(consumed.mock.calls).toEqual([['note']])
|
||||
|
||||
await act(async () => {
|
||||
fixture.setReady(false)
|
||||
hook.result.current.handleOpenComment(scrollNote)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
hook.rerender({ current: null, label: 'Add a note' })
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBe('note')
|
||||
surface = fixture.bindEditor()
|
||||
hook.rerender({ current: surface, label: 'Add a note' })
|
||||
await mountCard()
|
||||
await act(async () => {
|
||||
fixture.setReady(true)
|
||||
await flushScrollCommand()
|
||||
})
|
||||
expect(useAppStore.getState().scrollToDiffCommentId).toBeNull()
|
||||
expect(consumed.mock.calls).toEqual([['note'], ['note']])
|
||||
} finally {
|
||||
hook.unmount()
|
||||
await act(flushScrollCommand)
|
||||
fixture.dispose()
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useAppStore } from '@/store'
|
||||
import type { DiffNavigationCommand } from '../editor/combined-diff/scroll-viewport/combined-diff-viewport-anchor'
|
||||
export type DiffCommentScrollCommand = DiffNavigationCommand & {
|
||||
consume(consumed?: (id: string) => void): void
|
||||
}
|
||||
|
||||
export function consumeDiffCommentScrollCommand(expectedId: string): void {
|
||||
const state = useAppStore.getState()
|
||||
if (state.scrollToDiffCommentId === expectedId) {
|
||||
state.setScrollToDiffCommentId(null)
|
||||
}
|
||||
}
|
||||
|
||||
export function createDiffCommentScrollCommand(
|
||||
id: string,
|
||||
releaseAttempt: () => void
|
||||
): DiffCommentScrollCommand {
|
||||
let active = true
|
||||
let release: (() => void) | undefined = releaseAttempt
|
||||
const releaseNative = (): void => {
|
||||
const callback = release
|
||||
release = undefined
|
||||
callback?.()
|
||||
}
|
||||
const isCurrent = (): boolean => active && useAppStore.getState().scrollToDiffCommentId === id
|
||||
const dispose = (): void => {
|
||||
active = false
|
||||
unsubscribe()
|
||||
releaseNative()
|
||||
}
|
||||
const unsubscribe = useAppStore.subscribe((state) => {
|
||||
if (state.scrollToDiffCommentId !== id) {
|
||||
dispose()
|
||||
}
|
||||
})
|
||||
return {
|
||||
key: id,
|
||||
isCurrent,
|
||||
release: releaseNative,
|
||||
dispose,
|
||||
cancel: () => {
|
||||
const current = isCurrent()
|
||||
dispose()
|
||||
if (current) {
|
||||
consumeDiffCommentScrollCommand(id)
|
||||
}
|
||||
},
|
||||
consume: (consumed) => {
|
||||
if (!isCurrent()) {
|
||||
return
|
||||
}
|
||||
dispose()
|
||||
if (consumed) {
|
||||
consumed(id)
|
||||
} else {
|
||||
consumeDiffCommentScrollCommand(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import { useRef } from 'react'
|
||||
import { useAppStore } from '@/store'
|
||||
import { createFakeDiffCommentEditor } from './diff-comment-editor-test-fixture'
|
||||
import {
|
||||
createDiffCommentZoneNavigation,
|
||||
usePendingDiffCommentZoneReveal
|
||||
} from './diff-comment-zone-geometry'
|
||||
import {
|
||||
consumeDiffCommentScrollCommand,
|
||||
type DiffCommentScrollCommand
|
||||
} from './diff-comment-scroll-command'
|
||||
import type { DecoratedDiffComment } from './decorated-diff-comment'
|
||||
import type { ZoneEntry } from './diff-comment-view-zone-entry'
|
||||
import { CombinedDiffViewportOwner } from '../editor/combined-diff/scroll-viewport/combined-diff-viewport-owner'
|
||||
import { registerCombinedEditorGeometry } from '../editor/combined-diff/scroll-viewport/combined-diff-editor-geometry'
|
||||
import { useSourceControlNoteOpening } from '../right-sidebar/source-control/notes/use-note-opening'
|
||||
import { useDiffCommentDecorator } from './useDiffCommentDecorator'
|
||||
|
||||
export const scrollNote: DecoratedDiffComment = {
|
||||
id: 'note',
|
||||
worktreeId: 'workspace',
|
||||
filePath: 'long.ts',
|
||||
lineNumber: 40,
|
||||
body: 'Review this line',
|
||||
createdAt: 1,
|
||||
side: 'modified'
|
||||
}
|
||||
|
||||
export async function flushScrollCommand(): Promise<void> {
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
}
|
||||
|
||||
export function createScrollCommandFixture() {
|
||||
const owner = new CombinedDiffViewportOwner()
|
||||
const host = document.createElement('div')
|
||||
Object.defineProperties(host, { clientHeight: { value: 500 }, clientWidth: { value: 800 } })
|
||||
document.body.append(host)
|
||||
const unmount = owner.mount(host)
|
||||
owner.setItems([
|
||||
{
|
||||
key: 'long.ts',
|
||||
generation: '1',
|
||||
height: 2000,
|
||||
index: 0,
|
||||
collapsed: false,
|
||||
bodyKind: 'native'
|
||||
}
|
||||
])
|
||||
const item = owner.getItem('long.ts')!
|
||||
let ready = false
|
||||
const unbind = owner.bind(item, {
|
||||
readHeight: () => (ready ? 2000 : null),
|
||||
apply: () => {},
|
||||
capture: () => null,
|
||||
hasFocus: () => false,
|
||||
detach: () => owner.releaseItemNavigation(item)
|
||||
})
|
||||
const pendingScrollRef: { current: string | null } = { current: null }
|
||||
const combinedScrollRequestRef: { current: DiffCommentScrollCommand | null } = { current: null }
|
||||
const scrollToZoneFrameRef: { current: number | null } = { current: null }
|
||||
const scrollToZoneRef: { current: ((id: string) => void) | null } = { current: null }
|
||||
const onPendingScrollConsumedRef = { current: consumeDiffCommentScrollCommand }
|
||||
const zonesRef = { current: new Map<string, ZoneEntry>() }
|
||||
const cancelScrollToZoneFrame = (): void => {
|
||||
if (scrollToZoneFrameRef.current !== null) {
|
||||
cancelAnimationFrame(scrollToZoneFrameRef.current)
|
||||
}
|
||||
scrollToZoneFrameRef.current = null
|
||||
}
|
||||
const releases: (() => void)[] = []
|
||||
const bindEditor = (combined = true) => {
|
||||
const fake = createFakeDiffCommentEditor()
|
||||
const layouts = new Set<() => void>()
|
||||
const layoutInfo = fake.editor.getLayoutInfo()
|
||||
let contentWidth = 0
|
||||
Object.assign(fake.editor, {
|
||||
getViewZoneBounds: () => ({ hidden: false }),
|
||||
getScrollWidth: () => 800,
|
||||
getLayoutInfo: () => ({ ...layoutInfo, contentWidth }),
|
||||
onDidLayoutChange: (listener: () => void) => {
|
||||
layouts.add(listener)
|
||||
return { dispose: () => layouts.delete(listener) }
|
||||
},
|
||||
onDidContentSizeChange: () => ({ dispose: () => {} })
|
||||
})
|
||||
const node = document.createElement('div')
|
||||
const card = document.createElement('div')
|
||||
node.style.padding = '0px'
|
||||
Object.defineProperty(card, 'offsetHeight', { value: 152 })
|
||||
card.getBoundingClientRect = () => new DOMRect(0, 0, 400, 152)
|
||||
node.append(card)
|
||||
host.append(node)
|
||||
const identity = String(releases.length)
|
||||
const entry: ZoneEntry = {
|
||||
zoneId: 'zone',
|
||||
domNode: node,
|
||||
delegate: { afterLineNumber: 40, heightInPx: 152, domNode: node },
|
||||
root: { render: () => {}, unmount: () => {} },
|
||||
lifetime: new AbortController(),
|
||||
disposeMouseDownStopper: () => {},
|
||||
lastRenderSignature: '',
|
||||
laidOut: true
|
||||
}
|
||||
zonesRef.current = new Map([[scrollNote.id, entry]])
|
||||
const unregister = registerCombinedEditorGeometry(fake.editor, {
|
||||
item,
|
||||
identity,
|
||||
onUnbind: new Set(),
|
||||
registerZone: () => () => {},
|
||||
measureZone: (_id, _node, measure) => measure(),
|
||||
zonePoint: (_id, zoneNode) => ({
|
||||
isValid: () => zoneNode.isConnected && !entry.lifetime.signal.aborted,
|
||||
project: () => 800 - owner.getScrollTop(),
|
||||
resolveScrollTop: (displacement) => 800 - displacement,
|
||||
revealDisplacement: () => 100,
|
||||
dispose: () => {}
|
||||
})
|
||||
})
|
||||
const navigation = createDiffCommentZoneNavigation({
|
||||
editor: fake.editor,
|
||||
monacoModelIdentity: identity,
|
||||
zones: zonesRef.current,
|
||||
combined,
|
||||
pendingScrollRef,
|
||||
combinedScrollRequestRef,
|
||||
scrollToZoneFrameRef,
|
||||
onPendingScrollConsumedRef,
|
||||
cancelScrollToZoneFrame
|
||||
})
|
||||
scrollToZoneRef.current = navigation.scrollToZone
|
||||
releases.push(() => {
|
||||
unregister()
|
||||
fake.domNode.remove()
|
||||
node.remove()
|
||||
})
|
||||
return {
|
||||
editor: fake.editor,
|
||||
identity,
|
||||
navigation,
|
||||
fake,
|
||||
layout: () => {
|
||||
contentWidth = 800
|
||||
layouts.forEach((listener) => listener())
|
||||
}
|
||||
}
|
||||
}
|
||||
function useOpening() {
|
||||
const sourceControlRef = useRef<HTMLDivElement | null>(null)
|
||||
return useSourceControlNoteOpening({
|
||||
activeWorktreeId: 'workspace',
|
||||
worktreePath: '/workspace',
|
||||
entries: [{ path: 'long.ts', area: 'unstaged', status: 'modified' }],
|
||||
branchEntries: [],
|
||||
branchSummary: null,
|
||||
handleOpenDiff: () => {},
|
||||
openCommittedDiff: () => {},
|
||||
sourceControlRef
|
||||
})
|
||||
}
|
||||
function useSurface(surface: ReturnType<typeof bindEditor>) {
|
||||
const id = useAppStore((state) => state.scrollToDiffCommentId)
|
||||
const opening = useOpening()
|
||||
usePendingDiffCommentZoneReveal({
|
||||
editor: surface.editor,
|
||||
monacoModelIdentity: surface.identity,
|
||||
comments: [scrollNote],
|
||||
filePath: 'long.ts',
|
||||
worktreeId: 'workspace',
|
||||
pendingScrollCommentId: id,
|
||||
pendingScrollRef,
|
||||
combinedScrollRequestRef,
|
||||
zonesRef,
|
||||
scrollToZoneRef,
|
||||
cancelScrollToZoneFrame
|
||||
})
|
||||
return opening
|
||||
}
|
||||
const comments = [scrollNote]
|
||||
const deleteComment = (): void => {}
|
||||
function useDecoratorSurface(
|
||||
surface: ReturnType<typeof bindEditor> | null,
|
||||
addButtonLabel: string,
|
||||
onConsumed: (id: string) => void
|
||||
) {
|
||||
const id = useAppStore((state) => state.scrollToDiffCommentId)
|
||||
const opening = useOpening()
|
||||
useDiffCommentDecorator({
|
||||
editor: surface?.editor ?? null,
|
||||
monacoModelIdentity: surface?.identity,
|
||||
filePath: scrollNote.filePath,
|
||||
worktreeId: scrollNote.worktreeId,
|
||||
comments,
|
||||
addButtonLabel,
|
||||
onDeleteComment: deleteComment,
|
||||
pendingScrollCommentId: id,
|
||||
onPendingScrollConsumed: onConsumed
|
||||
})
|
||||
return opening
|
||||
}
|
||||
return {
|
||||
owner,
|
||||
item,
|
||||
bindEditor,
|
||||
useSurface,
|
||||
useDecoratorSurface,
|
||||
combinedScrollRequestRef,
|
||||
setReady: (value: boolean) => {
|
||||
ready = value
|
||||
owner.invalidate(item)
|
||||
},
|
||||
dispose: () => {
|
||||
unbind()
|
||||
unmount()
|
||||
owner.dispose()
|
||||
releases.forEach((release) => release())
|
||||
host.remove()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,11 @@ import {
|
||||
} from '../editor/combined-diff/scroll-viewport/combined-diff-editor-geometry'
|
||||
import { resizeDiffCommentZone, type ZoneEntry } from './diff-comment-view-zone-entry'
|
||||
import { requestDiffCommentZoneMeasurement } from './diff-comment-zone-measurement'
|
||||
import { useAppStore } from '@/store'
|
||||
import {
|
||||
createDiffCommentScrollCommand,
|
||||
type DiffCommentScrollCommand
|
||||
} from './diff-comment-scroll-command'
|
||||
|
||||
type ZoneNavigationContext = {
|
||||
editor: monacoEditor.ICodeEditor
|
||||
@@ -15,9 +20,9 @@ type ZoneNavigationContext = {
|
||||
zones: Map<string, ZoneEntry>
|
||||
combined: boolean
|
||||
pendingScrollRef: RefObject<string | null>
|
||||
combinedScrollRequestRef: RefObject<object | null>
|
||||
combinedScrollRequestRef: RefObject<DiffCommentScrollCommand | null>
|
||||
scrollToZoneFrameRef: RefObject<number | null>
|
||||
onPendingScrollConsumedRef: RefObject<(() => void) | undefined>
|
||||
onPendingScrollConsumedRef: RefObject<((id: string) => void) | undefined>
|
||||
cancelScrollToZoneFrame: () => void
|
||||
}
|
||||
|
||||
@@ -67,21 +72,32 @@ export function createDiffCommentZoneNavigation({
|
||||
|
||||
// Combined targets are zone-local; the legacy route retains its deferred native centering.
|
||||
const scrollToZone = (commentId: string): void => {
|
||||
cancelScrollToZoneFrame()
|
||||
const entry = zones.get(commentId)
|
||||
if (
|
||||
!entry ||
|
||||
entry.lifetime.signal.aborted ||
|
||||
pendingScrollRef.current !== commentId ||
|
||||
useAppStore.getState().scrollToDiffCommentId !== commentId ||
|
||||
!isCombinedEditorBindingCurrent(editor, monacoModelIdentity)
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (combinedScrollRequestRef.current) {
|
||||
return
|
||||
}
|
||||
cancelScrollToZoneFrame()
|
||||
if (combined) {
|
||||
if (combinedScrollRequestRef.current) {
|
||||
return
|
||||
}
|
||||
measureCombinedCommentZone(editor, entry.zoneId, entry.domNode, () => {
|
||||
if (
|
||||
combinedScrollRequestRef.current ||
|
||||
pendingScrollRef.current !== commentId ||
|
||||
useAppStore.getState().scrollToDiffCommentId !== commentId ||
|
||||
zones.get(commentId) !== entry ||
|
||||
entry.lifetime.signal.aborted ||
|
||||
!isCombinedEditorBindingCurrent(editor, monacoModelIdentity)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
if (!resizeDiffCommentZone(editor, entry)) {
|
||||
return false
|
||||
}
|
||||
@@ -90,7 +106,16 @@ export function createDiffCommentZoneNavigation({
|
||||
if (!(card instanceof HTMLElement) || card.offsetHeight <= 0) {
|
||||
return false
|
||||
}
|
||||
const request = { resolved: false }
|
||||
let resolved = false
|
||||
const request = createDiffCommentScrollCommand(commentId, () => {
|
||||
if (combinedScrollRequestRef.current === request) {
|
||||
combinedScrollRequestRef.current = null
|
||||
if (pendingScrollRef.current === commentId) {
|
||||
pendingScrollRef.current = null
|
||||
}
|
||||
cancelScrollToZoneFrame()
|
||||
}
|
||||
})
|
||||
combinedScrollRequestRef.current = request
|
||||
const zoneCurrent = (): boolean =>
|
||||
zones.get(commentId) === entry &&
|
||||
@@ -98,25 +123,25 @@ export function createDiffCommentZoneNavigation({
|
||||
isCombinedEditorBindingCurrent(editor, monacoModelIdentity)
|
||||
const current = (): boolean =>
|
||||
combinedScrollRequestRef.current === request &&
|
||||
request.isCurrent() &&
|
||||
pendingScrollRef.current === commentId &&
|
||||
zoneCurrent()
|
||||
const accepted = revealCombinedCommentZone({
|
||||
editor,
|
||||
id: entry.zoneId,
|
||||
node: entry.domNode,
|
||||
controls: () => (zoneCurrent() && (request.resolved || current()) ? [card] : []),
|
||||
controls: () => (zoneCurrent() && (resolved || current()) ? [card] : []),
|
||||
command: request,
|
||||
focus: () => {
|
||||
if (!current()) {
|
||||
return
|
||||
}
|
||||
request.resolved = true
|
||||
pendingScrollRef.current = null
|
||||
combinedScrollRequestRef.current = null
|
||||
onPendingScrollConsumedRef.current?.()
|
||||
resolved = true
|
||||
request.consume(onPendingScrollConsumedRef.current)
|
||||
}
|
||||
})
|
||||
if (!accepted) {
|
||||
combinedScrollRequestRef.current = null
|
||||
request.dispose()
|
||||
}
|
||||
return accepted
|
||||
})
|
||||
@@ -125,10 +150,19 @@ export function createDiffCommentZoneNavigation({
|
||||
if (!entry.laidOut) {
|
||||
return
|
||||
}
|
||||
const request = createDiffCommentScrollCommand(commentId, () => {
|
||||
if (combinedScrollRequestRef.current === request) {
|
||||
combinedScrollRequestRef.current = null
|
||||
pendingScrollRef.current = null
|
||||
cancelScrollToZoneFrame()
|
||||
}
|
||||
})
|
||||
combinedScrollRequestRef.current = request
|
||||
scrollToZoneFrameRef.current = requestAnimationFrame(() => {
|
||||
scrollToZoneFrameRef.current = null
|
||||
const entry = zones.get(commentId)
|
||||
if (!entry || !editor.getModel() || entry.lifetime.signal.aborted) {
|
||||
if (!entry || !editor.getModel() || entry.lifetime.signal.aborted || !request.isCurrent()) {
|
||||
request.dispose()
|
||||
return
|
||||
}
|
||||
if (pendingScrollRef.current !== commentId) {
|
||||
@@ -137,8 +171,7 @@ export function createDiffCommentZoneNavigation({
|
||||
const top = editor.getTopForLineNumber(entry.delegate.afterLineNumber, true)
|
||||
const editorHeight = editor.getLayoutInfo().height
|
||||
editor.setScrollTop(Math.max(0, top - editorHeight / 2))
|
||||
pendingScrollRef.current = null
|
||||
onPendingScrollConsumedRef.current?.()
|
||||
request.consume(onPendingScrollConsumedRef.current)
|
||||
})
|
||||
}
|
||||
return { resizeZone, zoneMeasured, scrollToZone }
|
||||
@@ -152,7 +185,7 @@ type PendingZoneRevealContext = {
|
||||
worktreeId: string
|
||||
pendingScrollCommentId?: string | null
|
||||
pendingScrollRef: RefObject<string | null>
|
||||
combinedScrollRequestRef: RefObject<object | null>
|
||||
combinedScrollRequestRef: RefObject<DiffCommentScrollCommand | null>
|
||||
zonesRef: RefObject<Map<string, ZoneEntry>>
|
||||
scrollToZoneRef: RefObject<((commentId: string) => void) | null>
|
||||
cancelScrollToZoneFrame: () => void
|
||||
@@ -176,11 +209,14 @@ export function usePendingDiffCommentZoneReveal({
|
||||
if (!editor || !isCombinedEditorBindingCurrent(editor, monacoModelIdentity)) {
|
||||
return
|
||||
}
|
||||
// Cancel cleared requests so late layout callbacks cannot snap-scroll.
|
||||
if (!pendingScrollCommentId) {
|
||||
const clearAttempt = (): void => {
|
||||
cancelScrollToZoneFrame()
|
||||
combinedScrollRequestRef.current?.dispose()
|
||||
pendingScrollRef.current = null
|
||||
combinedScrollRequestRef.current = null
|
||||
}
|
||||
if (!pendingScrollCommentId) {
|
||||
clearAttempt()
|
||||
return
|
||||
}
|
||||
const target = comments.find(
|
||||
@@ -189,19 +225,30 @@ export function usePendingDiffCommentZoneReveal({
|
||||
)
|
||||
if (!target) {
|
||||
// Drop foreign requests so late layout cannot acknowledge another surface’s note.
|
||||
cancelScrollToZoneFrame()
|
||||
pendingScrollRef.current = null
|
||||
combinedScrollRequestRef.current = null
|
||||
clearAttempt()
|
||||
return
|
||||
}
|
||||
if (pendingScrollRef.current !== pendingScrollCommentId) {
|
||||
combinedScrollRequestRef.current = null
|
||||
}
|
||||
pendingScrollRef.current = pendingScrollCommentId
|
||||
const entry = zonesRef.current.get(pendingScrollCommentId)
|
||||
if (entry && (entry.laidOut || !isCombinedEditorBindingCurrent(editor))) {
|
||||
scrollToZoneRef.current?.(pendingScrollCommentId)
|
||||
const synchronize = (): void => {
|
||||
if (useAppStore.getState().scrollToDiffCommentId !== pendingScrollCommentId) {
|
||||
clearAttempt()
|
||||
return
|
||||
}
|
||||
if (pendingScrollRef.current !== pendingScrollCommentId) {
|
||||
clearAttempt()
|
||||
}
|
||||
pendingScrollRef.current = pendingScrollCommentId
|
||||
const entry = zonesRef.current.get(pendingScrollCommentId)
|
||||
if (entry && (entry.laidOut || !isCombinedEditorBindingCurrent(editor))) {
|
||||
scrollToZoneRef.current?.(pendingScrollCommentId)
|
||||
}
|
||||
}
|
||||
const unsubscribe = useAppStore.subscribe((state, previous) => {
|
||||
if (state.scrollToDiffCommentId !== previous.scrollToDiffCommentId) {
|
||||
synchronize()
|
||||
}
|
||||
})
|
||||
synchronize()
|
||||
return unsubscribe
|
||||
}, [
|
||||
cancelScrollToZoneFrame,
|
||||
editor,
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { editor as monacoEditor } from 'monaco-editor'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import {
|
||||
invalidateCombinedEditorGeometry,
|
||||
releaseCombinedEditorNavigation,
|
||||
isCombinedEditorBindingCurrent,
|
||||
onCombinedEditorUnbind
|
||||
} from '../editor/combined-diff/scroll-viewport/combined-diff-editor-geometry'
|
||||
@@ -35,6 +36,7 @@ import {
|
||||
} from './diff-comment-view-zone-entry'
|
||||
import type { DiffCommentLineRange, DiffCommentLineTarget } from './diff-comment-line-range'
|
||||
import { useDiffCommentDraftZone, type DiffCommentDraft } from './diff-comment-draft-zone'
|
||||
import type { DiffCommentScrollCommand } from './diff-comment-scroll-command'
|
||||
|
||||
export type { DiffCommentDraft }
|
||||
|
||||
@@ -68,7 +70,7 @@ type DecoratorArgs = {
|
||||
formatCommentPrompt?: (comment: DecoratedDiffComment) => string
|
||||
// Pending scroll-to-note id from the sidebar; decorator reveals the line and acks so the same id can be re-requested later.
|
||||
pendingScrollCommentId?: string | null
|
||||
onPendingScrollConsumed?: () => void
|
||||
onPendingScrollConsumed?: (id: string) => void
|
||||
}
|
||||
|
||||
export function useDiffCommentDecorator({
|
||||
@@ -117,7 +119,7 @@ export function useDiffCommentDecorator({
|
||||
// Stash the diff-zones effect's scrollToZone closure so the request-effect can invoke the latest version.
|
||||
const scrollToZoneRef = useRef<((commentId: string) => void) | null>(null)
|
||||
const scrollToZoneFrameRef = useRef<number | null>(null)
|
||||
const combinedScrollRequestRef = useRef<object | null>(null)
|
||||
const combinedScrollRequestRef = useRef<DiffCommentScrollCommand | null>(null)
|
||||
|
||||
// Read current inline callbacks without tearing down zones on every parent render.
|
||||
const onDeleteCommentRef = useRef(onDeleteComment)
|
||||
@@ -247,6 +249,7 @@ export function useDiffCommentDecorator({
|
||||
zonesRef.current = zones
|
||||
|
||||
return onCombinedEditorUnbind(editor, () => {
|
||||
releaseCombinedEditorNavigation(editor)
|
||||
// Clear zones synchronously; defer root unmounts until after React 19’s commit to avoid unmount-while-rendering warnings.
|
||||
const rootsToUnmount = Array.from(zones.values(), (z) => {
|
||||
z.lifetime.abort()
|
||||
@@ -272,6 +275,7 @@ export function useDiffCommentDecorator({
|
||||
})
|
||||
}
|
||||
cancelScrollToZoneFrame()
|
||||
combinedScrollRequestRef.current?.dispose()
|
||||
pendingScrollRef.current = null
|
||||
combinedScrollRequestRef.current = null
|
||||
scrollToZoneRef.current = null
|
||||
|
||||
+3
-19
@@ -1,4 +1,4 @@
|
||||
import { observeCombinedDiffRowChrome } from './combined-diff-row-chrome'
|
||||
import { observeCombinedDiffRowContent } from './combined-diff-row-chrome'
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
@@ -59,28 +59,12 @@ function DiffViewportRow({
|
||||
children: ReactNode
|
||||
}): React.JSX.Element {
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
useLayoutEffect(
|
||||
() => observeCombinedDiffRowChrome(item, ref.current?.firstElementChild ?? null),
|
||||
[item]
|
||||
)
|
||||
useLayoutEffect(() => {
|
||||
const node = ref.current!
|
||||
item.owner.setNode(item, node)
|
||||
const observer = new ResizeObserver(() => {
|
||||
if (item.binding || node.querySelector('[data-combined-diff-native]')) {
|
||||
return
|
||||
}
|
||||
const content = node.firstElementChild
|
||||
if (content instanceof HTMLElement) {
|
||||
item.owner.measure(item, content.offsetHeight)
|
||||
}
|
||||
})
|
||||
const content = node.firstElementChild
|
||||
if (content) {
|
||||
observer.observe(content)
|
||||
}
|
||||
const stopContent = observeCombinedDiffRowContent(item, node)
|
||||
return () => {
|
||||
observer.disconnect()
|
||||
stopContent()
|
||||
item.owner.setNode(item, null)
|
||||
}
|
||||
}, [item])
|
||||
|
||||
+12
-1
@@ -1,5 +1,6 @@
|
||||
import type { editor } from 'monaco-editor'
|
||||
import type { DiffSemanticPoint, DiffViewportItem } from './combined-diff-viewport-owner'
|
||||
import type { DiffNavigationCommand } from './combined-diff-viewport-anchor'
|
||||
|
||||
export type CombinedEditorGeometry = {
|
||||
readonly item: DiffViewportItem
|
||||
@@ -83,6 +84,13 @@ export function invalidateCombinedEditorGeometry(editor: editor.ICodeEditor): vo
|
||||
}
|
||||
}
|
||||
|
||||
export function releaseCombinedEditorNavigation(editor: editor.ICodeEditor): void {
|
||||
const geometry = bindings.get(editor)
|
||||
if (geometry) {
|
||||
geometry.item.owner.releaseItemNavigation(geometry.item)
|
||||
}
|
||||
}
|
||||
|
||||
export function scrollCombinedEditorBy(editor: editor.ICodeEditor, delta: number): boolean {
|
||||
const geometry = bindings.get(editor)
|
||||
if (!geometry) {
|
||||
@@ -98,6 +106,7 @@ export function revealCombinedCommentZone(args: {
|
||||
node: HTMLElement
|
||||
controls: () => readonly HTMLElement[]
|
||||
focus?: () => void
|
||||
command?: DiffNavigationCommand
|
||||
}): boolean {
|
||||
const geometry = bindings.get(args.editor)
|
||||
if (!geometry) {
|
||||
@@ -106,7 +115,9 @@ export function revealCombinedCommentZone(args: {
|
||||
geometry.item.owner.reveal(
|
||||
geometry.item,
|
||||
() => geometry.zonePoint(args.id, args.node, args.controls),
|
||||
args.focus
|
||||
args.focus,
|
||||
undefined,
|
||||
args.command
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
+15
-2
@@ -45,9 +45,22 @@ export class CombinedDiffNativeAnchor {
|
||||
if (top >= this.item.owner.root.clientHeight || top + item.renderedHeight <= 0) {
|
||||
return null
|
||||
}
|
||||
const pane = this.context.editor.getModifiedEditor()
|
||||
const root = this.context.editor.getContainerDomNode().firstElementChild
|
||||
return (
|
||||
this.capturePane(this.context.editor.getModifiedEditor(), edge, previous) ??
|
||||
(root?.classList.contains('side-by-side')
|
||||
? this.capturePane(this.context.editor.getOriginalEditor(), edge, previous)
|
||||
: null)
|
||||
)
|
||||
}
|
||||
|
||||
private capturePane(
|
||||
pane: editor.ICodeEditor,
|
||||
edge: number,
|
||||
previous?: DiffSemanticPoint
|
||||
): DiffSemanticPoint | null {
|
||||
const model = pane.getModel()
|
||||
if (!model) {
|
||||
if (!model || pane.getLayoutInfo().contentWidth <= 0) {
|
||||
return null
|
||||
}
|
||||
const usable = this.usableInterval(pane)
|
||||
|
||||
+1
-1
@@ -282,7 +282,7 @@ export class CombinedDiffNativeBinding implements DiffViewportBinding {
|
||||
return
|
||||
}
|
||||
this.template.editor.stopHiddenRegionDrag()
|
||||
this.item.owner.cancelItemNavigation(this.item)
|
||||
this.item.owner.releaseItemNavigation(this.item)
|
||||
this.record.viewState = this.template.editor.saveViewState()
|
||||
for (const dispose of this.onUnbind) {
|
||||
dispose()
|
||||
|
||||
+47
@@ -319,6 +319,53 @@ describe('combined native reveal integration', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ contentWidth: 760, split: true, expectedTop: 1019 },
|
||||
{ contentWidth: 0, split: true, expectedTop: 1000 },
|
||||
{ contentWidth: 5, split: false, expectedTop: 1000 }
|
||||
])(
|
||||
'preserves original deletion text with applied content layout $contentWidth / $split',
|
||||
async ({ contentWidth, split, expectedTop }) => {
|
||||
const fixture = await createNativeBindingFixture()
|
||||
fixture.setSideBySide(split)
|
||||
const model = fixture.original.getModel()!
|
||||
const layout = fixture.original.getLayoutInfo()
|
||||
vi.spyOn(fixture.original, 'getLayoutInfo').mockReturnValue({
|
||||
...layout,
|
||||
width: contentWidth === 0 ? 40 : 800,
|
||||
contentWidth
|
||||
})
|
||||
vi.spyOn(fixture.modified, 'getPositionAtVerticalOffset').mockReturnValue({
|
||||
lineNumber: 1,
|
||||
column: 1
|
||||
})
|
||||
try {
|
||||
fixture.owner.input(1000)
|
||||
model.pushEditOperations(
|
||||
null,
|
||||
[
|
||||
{
|
||||
range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 },
|
||||
text: 'inserted\n'
|
||||
}
|
||||
],
|
||||
() => null
|
||||
)
|
||||
fixture.owner.invalidate(fixture.item)
|
||||
await nativeCommit()
|
||||
expect(fixture.owner.getScrollTop()).toBe(expectedTop)
|
||||
if (split && contentWidth > 0) {
|
||||
expect(
|
||||
28 + fixture.original.getTopForPosition(54, 1) - fixture.original.getScrollTop()
|
||||
).toBe(16)
|
||||
}
|
||||
} finally {
|
||||
vi.restoreAllMocks()
|
||||
fixture.dispose()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it('lets an explicit reveal supersede input queued while the viewport was detached', async () => {
|
||||
const fixture = await createNativeBindingFixture()
|
||||
const host = document.createElement('div')
|
||||
|
||||
+6
@@ -169,7 +169,12 @@ export async function createNativeBindingFixture(
|
||||
}
|
||||
const original = pane(true)
|
||||
const modified = pane(false)
|
||||
const diffRoot = document.createElement('div')
|
||||
const nativeRoot = document.createElement('div')
|
||||
nativeRoot.className = 'monaco-diff-editor side-by-side'
|
||||
diffRoot.append(nativeRoot)
|
||||
const rawDiff = {
|
||||
getContainerDomNode: () => diffRoot,
|
||||
updateOptions: () => {},
|
||||
setModel: () => {},
|
||||
restoreViewState: () => {},
|
||||
@@ -223,6 +228,7 @@ export async function createNativeBindingFixture(
|
||||
binding,
|
||||
modified,
|
||||
original,
|
||||
setSideBySide: (enabled: boolean) => nativeRoot.classList.toggle('side-by-side', enabled),
|
||||
restoreItems,
|
||||
completeAlignment: () => {
|
||||
aligned = true
|
||||
|
||||
+55
-3
@@ -2,13 +2,14 @@ import type { DiffViewportItem } from './combined-diff-viewport-item'
|
||||
|
||||
export function observeCombinedDiffRowChrome(
|
||||
item: DiffViewportItem,
|
||||
wrapper: Element | null
|
||||
wrapper: Element | null,
|
||||
isCurrent: () => boolean = () => true
|
||||
): () => void {
|
||||
let active = true
|
||||
let chrome: DiffViewportItem['chrome'] | null = null
|
||||
const heights = new Map<HTMLElement, number>()
|
||||
const resize = new ResizeObserver(() => {
|
||||
if (!active) {
|
||||
if (!active || !isCurrent()) {
|
||||
return
|
||||
}
|
||||
let changed = false
|
||||
@@ -24,7 +25,7 @@ export function observeCombinedDiffRowChrome(
|
||||
}
|
||||
})
|
||||
const refresh = (): void => {
|
||||
if (!active) {
|
||||
if (!active || !isCurrent()) {
|
||||
return
|
||||
}
|
||||
const next: DiffViewportItem['chrome'] = { header: null, conflict: null, body: null }
|
||||
@@ -75,3 +76,54 @@ export function observeCombinedDiffRowChrome(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function observeCombinedDiffRowContent(
|
||||
item: DiffViewportItem,
|
||||
row: HTMLElement
|
||||
): () => void {
|
||||
let active = true
|
||||
let content: Element | null = null
|
||||
let releaseContent = (): void => {}
|
||||
const refresh = (): void => {
|
||||
if (!active || row.firstElementChild === content) {
|
||||
return
|
||||
}
|
||||
releaseContent()
|
||||
content = row.firstElementChild
|
||||
if (!content) {
|
||||
releaseContent = () => {}
|
||||
return
|
||||
}
|
||||
const current = content
|
||||
let bound = true
|
||||
const isCurrent = (): boolean => active && bound && row.firstElementChild === current
|
||||
const stopChrome = observeCombinedDiffRowChrome(item, current, isCurrent)
|
||||
const measure = (): void => {
|
||||
if (
|
||||
isCurrent() &&
|
||||
!item.binding &&
|
||||
item.bodyKind !== 'native' &&
|
||||
current instanceof HTMLElement &&
|
||||
current.offsetHeight > 0
|
||||
) {
|
||||
item.owner.measure(item, current.offsetHeight)
|
||||
}
|
||||
}
|
||||
const resize = new ResizeObserver(measure)
|
||||
resize.observe(current)
|
||||
measure()
|
||||
releaseContent = () => {
|
||||
bound = false
|
||||
resize.disconnect()
|
||||
stopChrome()
|
||||
}
|
||||
}
|
||||
refresh()
|
||||
const mutation = new MutationObserver(refresh)
|
||||
mutation.observe(row, { childList: true })
|
||||
return () => {
|
||||
active = false
|
||||
mutation.disconnect()
|
||||
releaseContent()
|
||||
}
|
||||
}
|
||||
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import { CombinedDiffViewportOwner } from './combined-diff-viewport-owner'
|
||||
import { observeCombinedDiffRowContent } from './combined-diff-row-chrome'
|
||||
|
||||
it('rebinds retained content after an earlier row disappears and ignores retired observations', async () => {
|
||||
const mutations: { callback: () => void; node?: Node }[] = []
|
||||
const resizes: { callback: () => void; nodes: Element[] }[] = []
|
||||
vi.stubGlobal(
|
||||
'MutationObserver',
|
||||
class {
|
||||
entry: (typeof mutations)[number]
|
||||
constructor(callback: () => void) {
|
||||
this.entry = { callback }
|
||||
mutations.push(this.entry)
|
||||
}
|
||||
observe(node: Node): void {
|
||||
this.entry.node = node
|
||||
}
|
||||
disconnect(): void {}
|
||||
}
|
||||
)
|
||||
vi.stubGlobal(
|
||||
'ResizeObserver',
|
||||
class {
|
||||
entry: (typeof resizes)[number]
|
||||
constructor(callback: () => void) {
|
||||
this.entry = { callback, nodes: [] }
|
||||
resizes.push(this.entry)
|
||||
}
|
||||
observe(node: Element): void {
|
||||
this.entry.nodes.push(node)
|
||||
}
|
||||
disconnect(): void {}
|
||||
}
|
||||
)
|
||||
const owner = new CombinedDiffViewportOwner()
|
||||
const host = document.createElement('div')
|
||||
Object.defineProperties(host, {
|
||||
clientWidth: { value: 800 },
|
||||
clientHeight: { value: 500 }
|
||||
})
|
||||
const unmount = owner.mount(host)
|
||||
const commit = async (): Promise<void> => {
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
}
|
||||
const a = { key: 'a', generation: 'deferred', height: 200, collapsed: false, index: 0 }
|
||||
const b = { ...a, key: 'b', index: 1 }
|
||||
owner.setItems([a, b])
|
||||
const item = owner.getItem('b')!
|
||||
const row = document.createElement('div')
|
||||
const wrapper = (): { content: HTMLDivElement; header: HTMLDivElement } => {
|
||||
const content = document.createElement('div')
|
||||
const header = document.createElement('div')
|
||||
header.setAttribute('data-combined-diff-section-header', '')
|
||||
content.append(header)
|
||||
return { content, header }
|
||||
}
|
||||
const old = wrapper()
|
||||
let oldHeight = 200
|
||||
Object.defineProperty(old.content, 'offsetHeight', { get: () => oldHeight })
|
||||
row.append(old.content)
|
||||
const stop = observeCombinedDiffRowContent(item, row)
|
||||
try {
|
||||
const stale = resizes.filter(
|
||||
({ nodes }) => nodes.includes(old.content) || nodes.includes(old.header)
|
||||
)
|
||||
const rootMutation = mutations.find(({ node }) => node === row)!.callback
|
||||
owner.setItems([{ ...b, index: 0 }])
|
||||
expect(owner.getItem('b')).toBe(item)
|
||||
row.replaceChildren()
|
||||
oldHeight = 900
|
||||
stale.forEach(({ callback }) => callback())
|
||||
await commit()
|
||||
expect(owner.getLayout().logicalHeight).toBe(200)
|
||||
rootMutation()
|
||||
await commit()
|
||||
expect(owner.getLayout().logicalHeight).toBe(200)
|
||||
const next = wrapper()
|
||||
let nextHeight = 320
|
||||
Object.defineProperty(next.content, 'offsetHeight', { get: () => nextHeight })
|
||||
row.append(next.content)
|
||||
rootMutation()
|
||||
await commit()
|
||||
expect(item.chrome.header).toBe(next.header)
|
||||
expect(owner.getLayout().logicalHeight).toBe(320)
|
||||
oldHeight = 900
|
||||
stale.forEach(({ callback }) => callback())
|
||||
await commit()
|
||||
expect(item.chrome.header).toBe(next.header)
|
||||
expect(owner.getLayout().logicalHeight).toBe(320)
|
||||
nextHeight = 400
|
||||
resizes.find(({ nodes }) => nodes.includes(next.content))!.callback()
|
||||
await commit()
|
||||
expect(owner.getLayout().logicalHeight).toBe(400)
|
||||
owner.updateItems([{ ...b, index: 0, bodyKind: 'native' }])
|
||||
nextHeight = 80
|
||||
resizes.find(({ nodes }) => nodes.includes(next.content))!.callback()
|
||||
await commit()
|
||||
expect(owner.getLayout().logicalHeight).toBe(400)
|
||||
stop()
|
||||
stale.forEach(({ callback }) => callback())
|
||||
resizes.forEach(({ callback }) => callback())
|
||||
await commit()
|
||||
expect(item.chrome.header).toBeNull()
|
||||
expect(owner.getLayout().logicalHeight).toBe(400)
|
||||
} finally {
|
||||
stop()
|
||||
unmount()
|
||||
owner.dispose()
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
})
|
||||
+48
-13
@@ -13,6 +13,13 @@ export type DiffSemanticPoint = {
|
||||
dispose(): void
|
||||
}
|
||||
type CommittedPoint = { point: DiffSemanticPoint; displacement: number }
|
||||
export type DiffNavigationCommand = {
|
||||
readonly key: string
|
||||
isCurrent(): boolean
|
||||
release(): void
|
||||
cancel(): void
|
||||
dispose(): void
|
||||
}
|
||||
type AnchorContext = {
|
||||
invalidate(): void
|
||||
getIndex(): CombinedDiffExtentIndex
|
||||
@@ -32,10 +39,11 @@ export class CombinedDiffViewportAnchor {
|
||||
private committed: CommittedPoint | null = null
|
||||
private readingDirty = false
|
||||
private pending: {
|
||||
item: DiffViewportItem
|
||||
resolve: () => DiffSemanticPoint | null
|
||||
item?: DiffViewportItem
|
||||
resolve?: () => DiffSemanticPoint | null
|
||||
focus?: () => void
|
||||
point?: DiffSemanticPoint
|
||||
command?: DiffNavigationCommand
|
||||
} | null = null
|
||||
private imported: { anchor: DiffReadingAnchor | null; fallback: number } | null = null
|
||||
constructor(private readonly context: AnchorContext) {}
|
||||
@@ -80,27 +88,53 @@ export class CombinedDiffViewportAnchor {
|
||||
item: DiffViewportItem,
|
||||
resolve: () => DiffSemanticPoint | null,
|
||||
focus?: () => void,
|
||||
point?: DiffSemanticPoint
|
||||
point?: DiffSemanticPoint,
|
||||
command?: DiffNavigationCommand
|
||||
): void {
|
||||
this.cancelNavigation()
|
||||
this.pending = { item, resolve, focus, point }
|
||||
const previous = this.pending?.command
|
||||
if (command && previous?.key === command.key && previous.isCurrent() && command.isCurrent()) {
|
||||
this.releasePending(false)
|
||||
} else {
|
||||
this.cancelNavigation()
|
||||
}
|
||||
this.pending = { item, resolve, focus, point, command }
|
||||
this.context.invalidate()
|
||||
}
|
||||
|
||||
cancelNavigation(): void {
|
||||
this.pending?.point?.dispose()
|
||||
this.pending = null
|
||||
this.imported = null
|
||||
this.releasePending(true)
|
||||
}
|
||||
cancelItemNavigation(item: DiffViewportItem): void {
|
||||
releaseItemNavigation(item: DiffViewportItem): void {
|
||||
if (this.pending?.item === item) {
|
||||
this.pending.point?.dispose()
|
||||
this.pending = null
|
||||
const command = this.pending.command
|
||||
this.releasePending(false, Boolean(command))
|
||||
}
|
||||
}
|
||||
|
||||
private releasePending(cancel: boolean, retainCommand = false): void {
|
||||
const pending = this.pending
|
||||
this.pending = retainCommand && pending?.command ? { command: pending.command } : null
|
||||
if (pending?.point === this.committed?.point && pending?.point) {
|
||||
this.clearPoint()
|
||||
} else {
|
||||
pending?.point?.dispose()
|
||||
}
|
||||
pending?.command?.release()
|
||||
if (!retainCommand) {
|
||||
if (cancel) {
|
||||
pending?.command?.cancel()
|
||||
} else {
|
||||
pending?.command?.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
reconcile(): (() => void) | undefined {
|
||||
let navigation: typeof this.pending = null
|
||||
if (this.pending?.command && !this.pending.command.isCurrent()) {
|
||||
this.releasePending(false)
|
||||
}
|
||||
if (this.imported && !this.applyImport()) {
|
||||
return
|
||||
}
|
||||
@@ -110,16 +144,17 @@ export class CombinedDiffViewportAnchor {
|
||||
const pending = this.pending
|
||||
if (
|
||||
pending &&
|
||||
pending.item &&
|
||||
!pending.item.retired &&
|
||||
pending.item.binding &&
|
||||
pending.item.binding.readHeight() !== null
|
||||
) {
|
||||
const point = pending.point ?? pending.resolve()
|
||||
const point = pending.point ?? pending.resolve?.()
|
||||
if (point) {
|
||||
pending.point = point
|
||||
}
|
||||
if (point?.isValid && !point.isValid()) {
|
||||
this.cancelItemNavigation(pending.item)
|
||||
this.releaseItemNavigation(pending.item)
|
||||
} else if (point) {
|
||||
const projected = point.project()
|
||||
if (projected !== null) {
|
||||
@@ -262,7 +297,7 @@ export class CombinedDiffViewportAnchor {
|
||||
this.readingDirty = false
|
||||
}
|
||||
dispose(): void {
|
||||
this.cancelNavigation()
|
||||
this.releasePending(false)
|
||||
this.clearPoint()
|
||||
clearTimeout(this.directionTimer)
|
||||
}
|
||||
|
||||
+5
-10
@@ -157,7 +157,7 @@ export class CombinedDiffViewportOwner {
|
||||
}
|
||||
|
||||
retireItem(item: DiffViewportItem): void {
|
||||
this.cancelItemNavigation(item)
|
||||
this.releaseItemNavigation(item)
|
||||
this.geometry.forget(item)
|
||||
}
|
||||
private focusChanged(): void {
|
||||
@@ -215,19 +215,14 @@ export class CombinedDiffViewportOwner {
|
||||
this.cancelNavigation()
|
||||
this.anchor.preserve(point, displacement)
|
||||
}
|
||||
reveal(
|
||||
item: DiffViewportItem,
|
||||
resolve: () => DiffSemanticPoint | null,
|
||||
focus?: () => void,
|
||||
point?: DiffSemanticPoint
|
||||
): void {
|
||||
this.anchor.reveal(item, resolve, focus, point)
|
||||
reveal(...args: Parameters<CombinedDiffViewportAnchor['reveal']>): void {
|
||||
this.anchor.reveal(...args)
|
||||
}
|
||||
cancelNavigation(): void {
|
||||
this.anchor.cancelNavigation()
|
||||
}
|
||||
cancelItemNavigation(item: DiffViewportItem): void {
|
||||
this.anchor.cancelItemNavigation(item)
|
||||
releaseItemNavigation(item: DiffViewportItem): void {
|
||||
this.anchor.releaseItemNavigation(item)
|
||||
}
|
||||
|
||||
private reconcile(resetSlack = false): void {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NO_RESOURCE_EVIDENCE } from '@/lib/workspace/ownership/workspace-copy-owner'
|
||||
import { consumeDiffCommentScrollCommand } from '../../../diff-comments/diff-comment-scroll-command'
|
||||
import { useDiffCommentView } from '../../../diff-comments/use-diff-comment-owner'
|
||||
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { DiffEditor, type DiffOnMount } from '@monaco-editor/react'
|
||||
@@ -83,7 +84,6 @@ export default function DiffViewer({
|
||||
const language = usePluginSyntaxLanguage(filePath, coreLanguage)
|
||||
const updateDiffComment = useAppStore((s) => s.updateDiffComment)
|
||||
const scrollToDiffCommentId = useAppStore((s) => s.scrollToDiffCommentId)
|
||||
const setScrollToDiffCommentId = useAppStore((s) => s.setScrollToDiffCommentId)
|
||||
const diffComments = useMemo(
|
||||
() => (allDiffComments ?? []).filter((c) => c.filePath === relativePath && isDiffComment(c)),
|
||||
[allDiffComments, relativePath]
|
||||
@@ -191,7 +191,7 @@ export default function DiffViewer({
|
||||
commentOwner ? updateDiffComment(commentOwner, id, body) : Promise.resolve(false)
|
||||
: undefined,
|
||||
pendingScrollCommentId: pendingScrollForThisViewer,
|
||||
onPendingScrollConsumed: () => setScrollToDiffCommentId(null)
|
||||
onPendingScrollConsumed: consumeDiffCommentScrollCommand
|
||||
})
|
||||
|
||||
useDiffViewerFirstChangeAutoScroll({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NO_RESOURCE_EVIDENCE } from '@/lib/workspace/ownership/workspace-copy-owner'
|
||||
import { consumeDiffCommentScrollCommand } from '../../../diff-comments/diff-comment-scroll-command'
|
||||
import { useDiffCommentView } from '../../../diff-comments/use-diff-comment-owner'
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { CombinedDiffEditorMount } from '../../combined-diff/scroll-viewport/CombinedDiffEditor'
|
||||
@@ -59,7 +60,6 @@ export function DiffSectionItem({
|
||||
const deleteDiffComment = useAppStore((s) => s.deleteDiffComment)
|
||||
const updateDiffComment = useAppStore((s) => s.updateDiffComment)
|
||||
const scrollToDiffCommentId = useAppStore((s) => s.scrollToDiffCommentId)
|
||||
const setScrollToDiffCommentId = useAppStore((s) => s.setScrollToDiffCommentId)
|
||||
const diffComments = useMemo(
|
||||
() => (allDiffComments ?? []).filter((c) => c.filePath === section.path && isDiffComment(c)),
|
||||
[allDiffComments, section.path]
|
||||
@@ -143,7 +143,7 @@ export function DiffSectionItem({
|
||||
commentOwner ? updateDiffComment(commentOwner, id, body) : Promise.resolve(false)
|
||||
: undefined,
|
||||
pendingScrollCommentId: pendingScrollForThisSection,
|
||||
onPendingScrollConsumed: () => setScrollToDiffCommentId(null)
|
||||
onPendingScrollConsumed: consumeDiffCommentScrollCommand
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -165,6 +165,18 @@ export function enqueueDiffCommentPersist(
|
||||
}
|
||||
|
||||
// Why: derive the next list inside the `set` updater so concurrent writes can't clobber each other via a stale closure.
|
||||
function pendingAfterMutation(
|
||||
id: string | null,
|
||||
previous: DiffComment[] | undefined,
|
||||
next: DiffComment[]
|
||||
): string | null {
|
||||
return id &&
|
||||
previous?.some((comment) => comment.id === id) &&
|
||||
!next.some((comment) => comment.id === id)
|
||||
? null
|
||||
: id
|
||||
}
|
||||
|
||||
export function mutateDiffComments(
|
||||
set: Parameters<StateCreator<AppState>>[0],
|
||||
owner: DiffCommentOwner,
|
||||
@@ -191,6 +203,7 @@ export function mutateDiffComments(
|
||||
}
|
||||
next = computed
|
||||
return {
|
||||
scrollToDiffCommentId: pendingAfterMutation(s.scrollToDiffCommentId, previous, computed),
|
||||
folderWorkspaces: s.folderWorkspaces.map((workspace) =>
|
||||
workspace === target ? { ...workspace, diffComments: computed } : workspace
|
||||
)
|
||||
@@ -213,7 +226,10 @@ export function mutateDiffComments(
|
||||
const nextList: Worktree[] = repoList.map((w) =>
|
||||
rows.includes(w) ? { ...w, diffComments: computed } : w
|
||||
)
|
||||
return { worktreesByRepo: { ...s.worktreesByRepo, [repoId]: nextList } }
|
||||
return {
|
||||
scrollToDiffCommentId: pendingAfterMutation(s.scrollToDiffCommentId, previous, computed),
|
||||
worktreesByRepo: { ...s.worktreesByRepo, [repoId]: nextList }
|
||||
}
|
||||
})
|
||||
if (next === null) {
|
||||
return null
|
||||
|
||||
@@ -173,6 +173,16 @@ describe('bulk clear diff comments', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('retires a removed note request without consuming a request owned by another note', async () => {
|
||||
const store = createTestStore()
|
||||
seed(store, [makeComment({ id: 'c1' }), makeComment({ id: 'c2' })])
|
||||
store.getState().setScrollToDiffCommentId('c1')
|
||||
await store.getState().deleteDiffComment(capturedOwner(store, WT), 'c2')
|
||||
expect(store.getState().scrollToDiffCommentId).toBe('c1')
|
||||
await store.getState().clearDiffComments(capturedOwner(store, WT))
|
||||
expect(store.getState().scrollToDiffCommentId).toBeNull()
|
||||
})
|
||||
|
||||
it('does not clobber a later comment array identity when rollback runs', async () => {
|
||||
const store = createTestStore()
|
||||
const comments = [makeComment({ id: 'c1' })]
|
||||
|
||||
Reference in New Issue
Block a user