: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(notebooks): restore clipboard shortcuts for selected cells (#120986)
Marius Andra220b8d77a411
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.jupyter.test.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.jupyter.test.tsxindex 122e073931d6..29c3cdec0352 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.jupyter.test.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.jupyter.test.tsx@@ -111,6 +111,55 @@ async function flushFrames(): Promise<void> {const TWO_CELLS = '# Title\n\nIntro\n\n<Py code="a = 1" />\n\n<Py code="b = 2" />'describe('MarkdownNotebook in Jupyter mode', () => {+ it.each([+ ['text to output', false, false],+ ['output to text', true, false],+ ['text to output backwards', false, true],+ ['output to text backwards', true, true],+ ])('extends a drag across cell boundaries: %s', (_label, startsInOutput, backwards) => {+ jest.useFakeTimers()+ const notebook = renderJupyterNotebook(+ '# Title\n\nBefore text here\n\n<Py code="a = 1" />\n\n<Sql code="select 1" />\n\nAfter text here'+ )+ const textBlocks = notebook.container.querySelectorAll('.MarkdownNotebook__text-block')+ const outputs = notebook.container.querySelectorAll('.MarkdownNotebook__jupyter-output')+ const first = (startsInOutput ? outputs[0].firstChild! : textBlocks[1]) as HTMLElement+ const last = (startsInOutput ? textBlocks[2] : outputs[1].firstChild!) as HTMLElement+ const start = backwards ? last : first+ const end = backwards ? first : last+ const startOffset = backwards ? (startsInOutput ? 5 : 3) : startsInOutput ? 2 : 7+ const endOffset = backwards ? (startsInOutput ? 2 : 7) : startsInOutput ? 5 : 3+ const caret = document.createRange()+ caret.setStart(end.firstChild!, endOffset)+ caret.collapse(true)+ const caretDocument = document as Document & { caretRangeFromPoint?: () => Range }+ const originalCaretRangeFromPoint = caretDocument.caretRangeFromPoint+ caretDocument.caretRangeFromPoint = () => caret+ try {+ fireEvent.mouseDown(start, { button: 0 })+ act(() => window.getSelection()!.collapse(start.firstChild!, startOffset))+ fireEvent.mouseMove(document, { buttons: 1, clientX: 10, clientY: 20 })+ if (!backwards) {+ act(() => jest.advanceTimersByTime(16))+ }+ fireEvent.mouseUp(document)+ fireEvent(document, new Event('selectionchange'))++ expect(notebook.container.querySelectorAll('.MarkdownNotebook__component-shell--selected')).toHaveLength(2)+ const clipboardData = { setData: jest.fn() }+ fireEvent.copy(notebook.container.querySelector('.MarkdownNotebook')!, { clipboardData })+ expect(clipboardData.setData).toHaveBeenCalledWith(+ 'text/markdown',+ startsInOutput+ ? '<Py code="a = 1" />\n\n<Sql code="select 1" />\n\nAfter'+ : 'text here\n\n<Py code="a = 1" />\n\n<Sql code="select 1" />'+ )+ } finally {+ caretDocument.caretRangeFromPoint = originalCaretRangeFromPoint+ jest.useRealTimers()+ }+ })+it.each(['Backspace', 'Delete'])('deletes only the focused discussion thread with %s', (key) => {const notebook = renderJupyterNotebook('# Title\n\n<Comment ref="note" replies={[]} />\n\nA <ref id="note">useful</ref> paragraph.\n\nAnother paragraph.'@@ -190,6 +239,80 @@ describe('MarkdownNotebook in Jupyter mode', () => {expect(notebook.latest()).toEqual(expected)})+ it.each([+ ['code', false],+ ['markdown', false],+ ['multiple', false],+ ['code', true],+ ['markdown', true],+ ['multiple', true],+ ])('copies or cuts selected %s cells through the system clipboard (cut: %s)', async (kind, cut) => {+ const notebook = renderJupyterNotebook(+ '# Title\n\n<Py nodeId="original" code="a = 1" />\n\nOne\n\nTwo\n\n<Sql code="select 1" />'+ )+ act(() => notebook.cell(0).focus())+ if (kind === 'markdown') {+ press(notebook.cell(0), 'ArrowDown')+ } else if (kind === 'multiple') {+ press(notebook.cell(0), 'ArrowDown', { shiftKey: true })+ }+ const target = document.activeElement as HTMLElement+ const clipboard = new Map<string, string>()+ const clipboardData = {+ setData: (type: string, value: string) => clipboard.set(type, value),+ getData: (type: string) => clipboard.get(type) ?? '',+ }+ for (const modifier of [{ metaKey: true }, { ctrlKey: true }]) {+ expect(fireEvent.keyDown(target, { key: cut ? 'x' : 'c', ...modifier })).toBe(true)+ }+ expect(fireEvent[cut ? 'cut' : 'copy'](target, { clipboardData })).toBe(false)+ const copied = clipboard.get('text/markdown')!+ expect(clipboard.get('text/plain')).toEqual(copied)+ expect(copied).not.toContain('# Title')+ expect(copied).not.toContain('select 1')+ expect(copied.includes('a = 1')).toBe(kind !== 'markdown')+ expect(copied.includes('One\n\nTwo')).toBe(kind !== 'code')+ if (cut) {+ expect(notebook.latest().includes('a = 1')).toBe(kind === 'markdown')+ expect(notebook.latest().includes('One\n\nTwo')).toBe(kind === 'code')+ expect(notebook.latest()).toContain('# Title')+ }++ const destination = renderJupyterNotebook('# Destination\n\n<Py code="target" />\n\nAfter')+ act(() => destination.cell(0).focus())+ if (kind !== 'code') {+ press(destination.cell(0), 'ArrowDown')+ }+ const pasteTarget = document.activeElement as HTMLElement+ for (const modifier of [{ metaKey: true }, { ctrlKey: true }]) {+ expect(fireEvent.keyDown(pasteTarget, { key: 'v', ...modifier })).toBe(true)+ }+ expect(fireEvent.paste(pasteTarget, { clipboardData })).toBe(false)+ await waitFor(() => {+ expect(destination.latest()).toContain(kind === 'code' ? 'a = 1' : 'One\n\nTwo')+ })+ expect(destination.latest()).not.toContain('nodeId="original"')+ if (kind === 'code') {+ expect(destination.latest().indexOf('a = 1')).toBeLessThan(destination.latest().indexOf('After'))+ } else {+ expect(destination.latest().indexOf('After')).toBeLessThan(+ destination.latest().indexOf(kind === 'markdown' ? 'One' : 'a = 1')+ )+ }+ if (kind === 'markdown') {+ expect(destination.latest()).toContain('\n\n\nOne\n\nTwo')+ }+ })++ it.each(['copy', 'cut', 'paste'] as const)('leaves native %s inside a code editor alone', (eventType) => {+ const notebook = renderJupyterNotebook(TWO_CELLS)+ act(() => notebook.editor(0).focus())+ const clipboardData = { setData: jest.fn(), getData: () => 'ordinary text' }+ expect(fireEvent[eventType](notebook.editor(0), { clipboardData })).toBe(true)+ expect(clipboardData.setData).not.toHaveBeenCalled()+ expect(notebook.latest()).toEqual(TWO_CELLS)+ })+it('keeps a markdown cell whole when a code cell moves up past it', async () => {const notebook = renderJupyterNotebook('# Title\n\nIntro\n\n<Py code="a = 1" />\n\n\nOne\n\nTwo\n\n<Py code="b = 2" />'diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scssindex e017134f4180..badeec84999c 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss@@ -1733,7 +1733,7 @@ h3.MarkdownNotebook__text-block--heading {}.MarkdownNotebook__component-shell--selected,-.MarkdownNotebook__component-shell--selected * {+.MarkdownNotebook__component-shell.MarkdownNotebook__component-shell--selected * {user-select: none;}diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsxindex a2d81b9a39b5..ba198cf834b1 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx@@ -205,6 +205,7 @@ import {serializeMarkdownNotebook,} from './markdown'import { NOTEBOOK_AI_WRITING_PLACEHOLDER } from './notebookAI'+import { installNotebookTextSelection } from './notebookTextSelection'import {NotebookOperation,applyNotebookOperations,@@ -3244,6 +3245,12 @@ function MarkdownNotebookEditor({useEffect(() => clearFloatingToolbarRevealTimeout, [clearFloatingToolbarRevealTimeout])+ useEffect(() => {+ if (mode === 'edit' && canvasRef.current) {+ return installNotebookTextSelection(canvasRef.current)+ }+ }, [mode])+const updateSelectedComponentBlocksFromSelection = useCallback((): void => {const nextSelectedComponentNodeIds =mode === 'edit'@@ -3541,11 +3548,35 @@ function MarkdownNotebookEditor({void readSystemClipboardText().then(pasteMarkdown)}+ const getJupyterClipboardCell = (target: EventTarget | null): NotebookJupyterCell | null => {+ if (!jupyterMode || mode !== 'edit' || !window.getSelection()?.isCollapsed) {+ return null+ }+ if (target === jupyterCommandSinkRef.current) {+ return findJupyterCell(jupyterStore.getState().activeCellId)+ }+ const component = getFocusedComponentNode(+ target instanceof Element ? target : null,+ documentRef.current.nodes,+ blockRefs.current+ )+ return component ? findJupyterCell(component.id) : null+ }+const handleCopy = (event: ReactClipboardEvent<HTMLDivElement>): void => {if (event.target instanceof HTMLElement && isNativeEditableElement(event.target)) {return}+ const cell = getJupyterClipboardCell(event.target)+ if (cell) {+ const targets = getJupyterTargetCells(cell)+ const markdown = copyJupyterCells(targets)+ event.preventDefault()+ setClipboardMarkdown(event.clipboardData, markdown)+ return+ }+const selection = window.getSelection()if (getComponentNodeForSelection(selection, documentRef.current.nodes, blockRefs.current)) {return@@ -3586,6 +3617,16 @@ function MarkdownNotebookEditor({return}+ const cell = getJupyterClipboardCell(event.target)+ if (cell) {+ const targets = getJupyterTargetCells(cell)+ const markdown = copyJupyterCells(targets)+ event.preventDefault()+ setClipboardMarkdown(event.clipboardData, markdown)+ deleteJupyterCells(targets)+ return+ }+const selection = window.getSelection()if (getComponentNodeForSelection(selection, documentRef.current.nodes, blockRefs.current)) {return@@ -3670,6 +3711,17 @@ function MarkdownNotebookEditor({}}+ const cell = getJupyterClipboardCell(event.target)+ if (cell) {+ const markdown = getClipboardMarkdown(event.clipboardData)+ if (markdown) {+ event.preventDefault()+ event.stopPropagation()+ insertJupyterNodesAt(cell.endIndex + 1, copyJupyterNodes(markdown), 'command')+ }+ return+ }+const targetComponentNode = getFocusedComponentNode(event.target, documentRef.current.nodes, blockRefs.current)if (!targetComponentNode) {return@@ -5070,6 +5122,10 @@ function MarkdownNotebookEditor({}const key = event.key.toLowerCase()+ // Native clipboard events carry both markdown and plain text and work without async clipboard permissions.+ if (!event.shiftKey && ['c', 'x', 'v'].includes(key) && getJupyterClipboardCell(event.target)) {+ return+ }const inlineMarkShortcuts: Partial<Record<string, NotebookInlineMark['type']>> = {b: 'bold',i: 'italic',@@ -5660,11 +5716,12 @@ function MarkdownNotebookEditor({}}- const copyJupyterCells = (targets: NotebookJupyterCell[]): void => {+ const copyJupyterCells = (targets: NotebookJupyterCell[]): string => {const nodes = getNotebookNodes()jupyterStore.clipboard = serializeJupyterNodes(targets.flatMap((cell) => nodes.slice(cell.startIndex, cell.endIndex + 1)))+ return jupyterStore.clipboard}const pasteJupyterCells = (cell: NotebookJupyterCell, position: 'above' | 'below'): void => {diff --git a/frontend/src/lib/components/MarkdownNotebook/notebookTextSelection.ts b/frontend/src/lib/components/MarkdownNotebook/notebookTextSelection.tsnew file mode 100644index 000000000000..a41c5b498f4a--- /dev/null+++ b/frontend/src/lib/components/MarkdownNotebook/notebookTextSelection.ts@@ -0,0 +1,135 @@+import { isNativeEditableElement } from './domSelection'++function elementForNode(node: Node): Element | null {+ return node instanceof Element ? node : node.parentElement+}++function caretAtPoint(document: Document, x: number, y: number): Range | null {+ const caretDocument = document as Document & {+ caretPositionFromPoint?: (x: number, y: number) => { offsetNode: Node; offset: number } | null+ caretRangeFromPoint?: (x: number, y: number) => Range | null+ }+ const position = caretDocument.caretPositionFromPoint?.(x, y)+ if (position) {+ const range = document.createRange()+ range.setStart(position.offsetNode, position.offset)+ range.collapse(true)+ return range+ }+ return caretDocument.caretRangeFromPoint?.(x, y) ?? null+}++export function installNotebookTextSelection(canvas: HTMLElement): () => void {+ const document = canvas.ownerDocument+ const window = document.defaultView!+ let startRow: Element | null = null+ let anchor: Range | null = null+ let frame: number | null = null+ let pendingUpdate: (() => void) | null = null+ let crossedRows = false++ const stop = (): void => {+ startRow = null+ anchor = null+ pendingUpdate = null+ crossedRows = false+ if (frame !== null) {+ window.cancelAnimationFrame(frame)+ frame = null+ }+ }++ const onMouseDown = (event: MouseEvent): void => {+ stop()+ const target = event.target+ if (+ event.button !== 0 ||+ !(target instanceof HTMLElement) ||+ isNativeEditableElement(target) ||+ target.closest('button, a, [role="button"], [draggable="true"]')+ ) {+ return+ }+ startRow = target.closest('.MarkdownNotebook__row')+ }++ const onMouseMove = (event: MouseEvent): void => {+ if (!startRow || !(event.buttons & 1)) {+ return+ }+ const selection = window.getSelection()+ if (!anchor && selection?.anchorNode && startRow.contains(selection.anchorNode)) {+ anchor = document.createRange()+ anchor.setStart(selection.anchorNode, selection.anchorOffset)+ anchor.collapse(true)+ }+ const focus = caretAtPoint(document, event.clientX, event.clientY)+ if (!anchor || !focus || !canvas.contains(focus.startContainer)) {+ return+ }+ const focusRow = elementForNode(focus.startContainer)?.closest('.MarkdownNotebook__row')+ if (!focusRow || (focusRow === startRow && !crossedRows)) {+ if (frame !== null) {+ window.cancelAnimationFrame(frame)+ frame = null+ pendingUpdate = null+ }+ return+ }+ crossedRows ||= focusRow !== startRow++ const backwards = anchor.compareBoundaryPoints(Range.START_TO_START, focus) > 0+ const range = document.createRange()+ const start = backwards ? focus : anchor+ const end = backwards ? anchor : focus+ range.setStart(start.startContainer, start.startOffset)+ range.setEnd(end.startContainer, end.startOffset)+ const startComponent = elementForNode(range.startContainer)?.closest('.MarkdownNotebook__component-shell')+ const endComponent = elementForNode(range.endContainer)?.closest('.MarkdownNotebook__component-shell')+ if (startComponent && focusRow !== startRow) {+ range.setStartBefore(startComponent)+ }+ if (endComponent && focusRow !== startRow) {+ range.setEndAfter(endComponent)+ }++ // Native dragging stops at contenteditable=false cell boundaries. Apply the notebook range+ // after the browser's default selection update, with crossed components selected as blocks.+ if (frame !== null) {+ window.cancelAnimationFrame(frame)+ }+ pendingUpdate = () => {+ canvas.focus({ preventScroll: true })+ selection?.setBaseAndExtent(+ backwards ? range.endContainer : range.startContainer,+ backwards ? range.endOffset : range.startOffset,+ backwards ? range.startContainer : range.endContainer,+ backwards ? range.startOffset : range.endOffset+ )+ }+ frame = window.requestAnimationFrame(() => {+ frame = null+ pendingUpdate?.()+ pendingUpdate = null+ })+ }++ const onMouseUp = (): void => {+ pendingUpdate?.()+ stop()+ }++ canvas.addEventListener('mousedown', onMouseDown)+ document.addEventListener('mousemove', onMouseMove)+ document.addEventListener('mouseup', onMouseUp)+ document.addEventListener('dragstart', stop)+ window.addEventListener('blur', stop)+ return () => {+ stop()+ canvas.removeEventListener('mousedown', onMouseDown)+ document.removeEventListener('mousemove', onMouseMove)+ document.removeEventListener('mouseup', onMouseUp)+ document.removeEventListener('dragstart', stop)+ window.removeEventListener('blur', stop)+ }+}