Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(notebooks): preserve reading position during remote edits (#100080)

Marius Andrae474b3f61d1d
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index a800ab34dd14..a4405f25f8d6 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -1865,50 +1865,81 @@ Repeated block`),
expect(container.querySelector('[data-attr="notebook-comment-editor"]')).toBeNull()
})
- it('moves the caret with the text when a collaborator inserts before it', () => {
- const onChange = jest.fn()
- const onCaretChange = jest.fn()
- const { container, rerender } = render(
- createElement(MarkdownNotebook, {
- value: '# Title\n\nHello',
- onChange,
- onCaretChange,
- remoteValue: '# Title\n\nHello',
- })
- )
- const blocks = container.querySelectorAll(NOTEBOOK_TEST_EDITABLE_SELECTOR)
- const paragraphBlock = blocks[blocks.length - 1] as HTMLElement
- expect(paragraphBlock.textContent).toEqual('Hello')
+ it.each(['remote', 'external'] as const)(
+ 'maps the caret without scrolling when an incoming %s edit inserts before it',
+ (source) => {
+ const onChange = jest.fn()
+ const onCaretChange = jest.fn()
+ const { container, rerender } = render(
+ createElement(MarkdownNotebook, {
+ value: '# Title\n\nHello',
+ onChange,
+ onCaretChange,
+ remoteValue: '# Title\n\nHello',
+ })
+ )
+ const blocks = container.querySelectorAll(NOTEBOOK_TEST_EDITABLE_SELECTOR)
+ const paragraphBlock = blocks[blocks.length - 1] as HTMLElement
+ expect(paragraphBlock.textContent).toEqual('Hello')
- // Caret at the end of the line while a collaborator types at the beginning.
- placeCaretInElement(paragraphBlock, paragraphBlock.childNodes.length)
+ // Caret at the end of the line while a collaborator types at the beginning.
+ placeCaretInElement(paragraphBlock, paragraphBlock.childNodes.length)
- rerender(
- createElement(MarkdownNotebook, {
- value: '# Title\n\nHello',
- onChange,
- onCaretChange,
- remoteValue: '# Title\n\nWell, Hello',
- })
+ const focus = jest.spyOn(paragraphBlock, 'focus')
+ const scrollIntoView = jest.fn()
+ paragraphBlock.scrollIntoView = scrollIntoView
+
+ rerender(
+ createElement(MarkdownNotebook, {
+ value: source === 'external' ? '# Title\n\nWell, Hello' : '# Title\n\nHello',
+ onChange,
+ onCaretChange,
+ remoteValue: source === 'remote' ? '# Title\n\nWell, Hello' : '# Title\n\nHello',
+ })
+ )
+
+ const updatedBlocks = container.querySelectorAll(NOTEBOOK_TEST_EDITABLE_SELECTOR)
+ const updatedBlock = updatedBlocks[updatedBlocks.length - 1] as HTMLElement
+ expect(updatedBlock.textContent).toEqual('Well, Hello')
+
+ // The caret must still sit at the end of "Hello" — after the remote insertion,
+ // not at the stale numeric offset 5 (which would now be inside "Well,").
+ const range = window.getSelection()?.getRangeAt(0)
+ expect(range?.collapsed).toBe(true)
+ expect(range?.startContainer.textContent).toEqual('Well, Hello')
+ expect(range?.startOffset).toEqual('Well, Hello'.length)
+
+ expect(focus).not.toHaveBeenCalled()
+ expect(scrollIntoView).not.toHaveBeenCalled()
+ focus.mockRestore()
+
+ // The corrected caret is re-published right away so collaborators see it move too.
+ if (source === 'remote') {
+ expect(onCaretChange).toHaveBeenCalledWith({
+ nodeIndex: 1,
+ offset: 'Well, Hello'.length,
+ listItemIndex: undefined,
+ })
+ }
+ }
+ )
+
+ it.each(['outside', 'embedded'] as const)('keeps focus in an %s input during a remote edit', (location) => {
+ const initial = '# Title\n\nHello'
+ const { container, rerender } = render(
+ createElement(MarkdownNotebook, { value: initial, remoteValue: initial })
)
+ const paragraph = getBodyTextBlock(container)
+ placeCaretInElement(paragraph, paragraph.childNodes.length)
+ const input = document.createElement('input')
+ const parent = location === 'embedded' ? container.querySelector('.MarkdownNotebook')! : container
+ parent.appendChild(input)
+ input.focus()
- const updatedBlocks = container.querySelectorAll(NOTEBOOK_TEST_EDITABLE_SELECTOR)
- const updatedBlock = updatedBlocks[updatedBlocks.length - 1] as HTMLElement
- expect(updatedBlock.textContent).toEqual('Well, Hello')
+ rerender(createElement(MarkdownNotebook, { value: initial, remoteValue: '# Title\n\nWell, Hello' }))
- // The caret must still sit at the end of "Hello" — after the remote insertion,
- // not at the stale numeric offset 5 (which would now be inside "Well,").
- const range = window.getSelection()?.getRangeAt(0)
- expect(range?.collapsed).toBe(true)
- expect(range?.startContainer.textContent).toEqual('Well, Hello')
- expect(range?.startOffset).toEqual('Well, Hello'.length)
-
- // The corrected caret is re-published right away so collaborators see it move too.
- expect(onCaretChange).toHaveBeenCalledWith({
- nodeIndex: 1,
- offset: 'Well, Hello'.length,
- listItemIndex: undefined,
- })
+ expect(getBodyTextBlock(container).textContent).toEqual('Well, Hello')
+ expect(document.activeElement).toBe(input)
})
it('keeps the caret in place when a collaborator inserts after it', () => {
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
index 5c9bf5fb52e2..471600ca3bff 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
@@ -1085,11 +1085,12 @@ function MarkdownNotebookEditor({
if (restoreSelectionRequest) {
// Map the caret through the incoming change so it stays at the same place in
// the text, not at the same numeric offset.
- restoreSelectionRef.current = mapRestoreSelectionThroughDocumentChange(
+ const mappedRequest = mapRestoreSelectionThroughDocumentChange(
restoreSelectionRequest,
previousDocument,
reconciledDocument
)
+ restoreSelectionRef.current = mappedRequest && { ...mappedRequest, preserveViewport: true }
}
setDebugMarkdown(value)
// The base is intentionally left untouched: an external `value` change is a local-side
@@ -1103,6 +1104,14 @@ function MarkdownNotebookEditor({
const request = restoreSelectionRef.current
if (request) {
restoreSelectionRef.current = null
+ const activeElement = window.document.activeElement
+ if (
+ request.preserveViewport &&
+ (!notebookRef.current?.contains(activeElement) ||
+ (activeElement instanceof HTMLElement && isNativeEditableElement(activeElement)))
+ ) {
+ return
+ }
if ('textRanges' in request) {
restoreTextSelectionRanges(request.textRanges, blockRefs.current, listItemRefs.current)
return
@@ -1121,9 +1130,13 @@ function MarkdownNotebookEditor({
? undefined
: listItemRefs.current[getListItemRefKey(request.nodeId, request.listItemIndex)]))
if (element) {
- element.focus()
+ if (!request.preserveViewport) {
+ element.focus()
+ }
restoreSelection(element, request.start, request.end)
- scrollNotebookElementIntoView(element)
+ if (!request.preserveViewport) {
+ scrollNotebookElementIntoView(element)
+ }
}
return
}
@@ -1314,7 +1327,7 @@ function MarkdownNotebookEditor({
previousDocument,
reconciledDocument
)
- restoreSelectionRef.current = mappedRequest
+ restoreSelectionRef.current = mappedRequest && { ...mappedRequest, preserveViewport: true }
// Re-publish the corrected caret right away, so collaborators see this
// client's caret at its mapped position instead of the stale offset.
if (mappedRequest && 'nodeId' in mappedRequest) {
diff --git a/frontend/src/lib/components/MarkdownNotebook/editorTypes.ts b/frontend/src/lib/components/MarkdownNotebook/editorTypes.ts
index 8e8bb26d570d..5fe81152b0ca 100644
--- a/frontend/src/lib/components/MarkdownNotebook/editorTypes.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/editorTypes.ts
@@ -31,7 +31,9 @@ export type RestoreTextSelectionRequest = {
textRanges: RestoreTextRange[]
}
-export type RestoreSelectionRequest = RestoreInlineSelectionRequest | RestoreTextSelectionRequest
+export type RestoreSelectionRequest = (RestoreInlineSelectionRequest | RestoreTextSelectionRequest) & {
+ preserveViewport?: boolean
+}
export type InsertCommand = {
key: string