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): count line breaks in cursor offsets (#110633)

Marius Andrafc2de30fbdbf
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index daae7c445271..796cdd1d14c7 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -6257,6 +6257,34 @@ Second`)
}
})
+ it.each(['keydown', 'beforeinput'])('splits multiline text at the visible caret via %s', (input) => {
+ const onChange = jest.fn()
+ const value = withNotebookTitle('Red\n**Green**\nBlue ribbon')
+ const { container } = render(createElement(MarkdownNotebook, { value, onChange }))
+ const canvas = container.querySelector('.MarkdownNotebook__canvas') as HTMLElement
+ const textBlock = getBodyTextBlock(container)
+ const range = document.createRange()
+ range.setStart(textBlock.lastChild!, 'Blue'.length)
+ range.collapse(true)
+ window.getSelection()!.removeAllRanges()
+ window.getSelection()!.addRange(range)
+
+ if (input === 'keydown') {
+ fireEvent.keyDown(canvas, { key: 'Enter' })
+ } else {
+ fireBeforeInput(canvas, 'insertParagraph')
+ }
+
+ expect(onChange).toHaveBeenLastCalledWith(withNotebookTitle('Red\n**Green**\nBlue\n\n ribbon'))
+ expect(window.getSelection()?.anchorOffset).toBe(0)
+
+ fireBeforeInput(canvas, 'deleteContentBackward')
+
+ expect(onChange).toHaveBeenLastCalledWith(value)
+ expect(window.getSelection()?.anchorNode?.textContent).toBe('Blue ribbon')
+ expect(window.getSelection()?.anchorOffset).toBe('Blue'.length)
+ })
+
it('deletes selected text when pressing Enter and splits at the selection', () => {
const onChange = jest.fn()
const { container } = render(
diff --git a/frontend/src/lib/components/MarkdownNotebook/domSelection.test.ts b/frontend/src/lib/components/MarkdownNotebook/domSelection.test.ts
index 264ce589b855..39eb132f7b70 100644
--- a/frontend/src/lib/components/MarkdownNotebook/domSelection.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/domSelection.test.ts
@@ -1,4 +1,10 @@
-import { getSelectedCodeRanges } from './domSelection'
+import {
+ findTextPosition,
+ getSelectedCodeRanges,
+ getSelectionRange,
+ getTextOffset,
+ restoreSelection,
+} from './domSelection'
import { NotebookCodeBlockNode } from './types'
function codeNode(language: string, text: string): NotebookCodeBlockNode {
@@ -14,6 +20,48 @@ function selectContents(element: HTMLElement): Selection {
return selection
}
+describe('inline selection offsets', () => {
+ afterEach(() => {
+ window.getSelection()?.removeAllRanges()
+ document.body.innerHTML = ''
+ })
+
+ it.each([
+ ['plain text', 'abcd', 4],
+ ['line breaks', 'ab<br>cd<br>ef', 8],
+ ['nested marks', '<strong>ab<br><em>cd</em></strong><br><a href="https://example.com">ef</a>', 8],
+ ['consecutive and edge breaks', '<br>ab<br><br>cd<br>', 8],
+ ['only breaks', '<br><br>', 2],
+ ['empty text', '', 0],
+ ])('reads and restores every position in %s', (_, html, length) => {
+ const element = document.createElement('p')
+ element.innerHTML = html
+ document.body.appendChild(element)
+
+ expect(getTextOffset(element, element, element.childNodes.length)).toBe(length)
+ for (let offset = 0; offset <= length; offset++) {
+ const position = findTextPosition(element, offset)
+ expect(getTextOffset(element, position.node, position.offset)).toBe(offset)
+ restoreSelection(element, offset, length)
+ expect(getSelectionRange(element, 'paragraph')).toEqual({ nodeId: 'paragraph', start: offset, end: length })
+ }
+ })
+
+ it('includes line breaks when a selection extends past the block', () => {
+ const element = document.createElement('p')
+ element.innerHTML = 'ab<br>cd'
+ const next = document.createElement('p')
+ next.textContent = 'next'
+ document.body.append(element, next)
+ const range = document.createRange()
+ range.setStart(element.lastChild!, 1)
+ range.setEnd(next.firstChild!, 2)
+ window.getSelection()!.addRange(range)
+
+ expect(getSelectionRange(element, 'paragraph')).toEqual({ nodeId: 'paragraph', start: 4, end: 5 })
+ })
+})
+
describe('getSelectedCodeRanges', () => {
afterEach(() => {
window.getSelection()?.removeAllRanges()
diff --git a/frontend/src/lib/components/MarkdownNotebook/domSelection.ts b/frontend/src/lib/components/MarkdownNotebook/domSelection.ts
index 1703b1db663e..736be4060f6f 100644
--- a/frontend/src/lib/components/MarkdownNotebook/domSelection.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/domSelection.ts
@@ -44,6 +44,16 @@ export function getElementLineHeight(element: HTMLElement): number {
return Number.isFinite(fontSize) ? fontSize * 1.55 : 24
}
+function getInlineDOMTextLength(node: Node): number {
+ if (node.nodeType === Node.TEXT_NODE) {
+ return node.textContent?.length ?? 0
+ }
+ if (node instanceof HTMLBRElement) {
+ return 1
+ }
+ return Array.from(node.childNodes).reduce((length, child) => length + getInlineDOMTextLength(child), 0)
+}
+
export function getSelectionRange(element: HTMLElement, nodeId: string): NotebookTextSelectionRange | null {
const selection = window.getSelection()
if (!selection || selection.rangeCount === 0) {
@@ -54,7 +64,7 @@ export function getSelectionRange(element: HTMLElement, nodeId: string): Noteboo
if (!element.contains(range.commonAncestorContainer) && !rangeIntersectsNode(range, element)) {
return null
}
- const textLength = element.textContent?.length ?? 0
+ const textLength = getInlineDOMTextLength(element)
return {
nodeId,
@@ -104,10 +114,24 @@ export function getCollapsedSelectionRange(element: HTMLElement, nodeId: string)
}
export function getTextOffset(root: HTMLElement, container: Node, offset: number): number {
- const range = document.createRange()
- range.selectNodeContents(root)
- range.setEnd(container, offset)
- return range.toString().length
+ // Range.toString() omits <br>, but each break occupies one character in the inline model.
+ let textOffset =
+ container.nodeType === Node.TEXT_NODE
+ ? offset
+ : Array.from(container.childNodes)
+ .slice(0, offset)
+ .reduce((length, child) => length + getInlineDOMTextLength(child), 0)
+
+ let current: Node | null = container
+ while (current && current !== root) {
+ let sibling = current.previousSibling
+ while (sibling) {
+ textOffset += getInlineDOMTextLength(sibling)
+ sibling = sibling.previousSibling
+ }
+ current = current.parentNode
+ }
+ return textOffset
}
export function restoreSelection(element: HTMLElement, start: number, end: number): void {
@@ -674,13 +698,24 @@ export function isFormattingToolbarFocused(): boolean {
}
export function findTextPosition(root: HTMLElement, offset: number): { node: Node; offset: number } {
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, {
+ acceptNode: (node) =>
+ node.nodeType === Node.TEXT_NODE || node instanceof HTMLBRElement
+ ? NodeFilter.FILTER_ACCEPT
+ : NodeFilter.FILTER_SKIP,
+ })
let remaining = offset
let current = walker.nextNode()
while (current) {
- const length = current.textContent?.length ?? 0
+ const length = getInlineDOMTextLength(current)
if (remaining <= length) {
+ if (current instanceof HTMLBRElement && current.parentNode) {
+ return {
+ node: current.parentNode,
+ offset: Array.from(current.parentNode.childNodes).indexOf(current) + remaining,
+ }
+ }
return { node: current, offset: remaining }
}
remaining -= length