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): make links openable in the markdown notebook editor (#69904)

Marius Andra7996472ef5ff
diff --git a/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx b/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx
index 6ca1471f79f3..afa75de11e31 100644
--- a/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx
@@ -8,7 +8,7 @@ import {
useState,
} from 'react'
-import { IconCode, IconComment, IconCopy, IconQuote, IconSparkles } from '@posthog/icons'
+import { IconCode, IconComment, IconCopy, IconExternal, IconQuote, IconSparkles } from '@posthog/icons'
import { LemonButton, LemonInput } from '@posthog/lemon-ui'
import { IconBold, IconItalic, IconLink } from 'lib/lemon-ui/icons'
@@ -77,9 +77,11 @@ export function FormattingToolbar({
/** Moves focus back into the editor (Escape while the toolbar holds focus). */
returnFocusToEditor?: () => void
}): JSX.Element {
- const [isLinkEditorOpen, setIsLinkEditorOpen] = useState(initialLinkEditorOpen)
+ const [isLinkEditorOpen, setIsLinkEditorOpen] = useState(initialLinkEditorOpen || !!currentLinkHref)
+ const [shouldFocusLinkInput, setShouldFocusLinkInput] = useState(initialLinkEditorOpen)
const [linkHref, setLinkHref] = useState(currentLinkHref ?? '')
const toolbarRef = useRef<HTMLDivElement | null>(null)
+ const linkInputRef = useRef<HTMLInputElement | null>(null)
const [boundsShift, setBoundsShift] = useState({ x: 0, y: 0 })
// The anchor point only clamps the toolbar's center to the viewport, so the rendered toolbar
@@ -130,21 +132,28 @@ export function FormattingToolbar({
const normalizedLinkHref = sanitizeNotebookLinkHref(linkHref)
const hasExistingLink = !!currentLinkHref
+ // Selecting linked text opens the URL editor right away (no extra click), but without
+ // stealing focus from the selection: the input only autofocuses on an explicit open.
useEffect(() => {
- if (initialLinkEditorOpen) {
+ if (initialLinkEditorOpen || currentLinkHref) {
setLinkHref(currentLinkHref ?? '')
setIsLinkEditorOpen(true)
+ if (initialLinkEditorOpen) {
+ setShouldFocusLinkInput(true)
+ }
return
}
- if (!isLinkEditorOpen) {
- setLinkHref(currentLinkHref ?? '')
- }
- }, [currentLinkHref, initialLinkEditorOpen, isLinkEditorOpen])
+ setIsLinkEditorOpen(false)
+ setShouldFocusLinkInput(false)
+ setLinkHref('')
+ }, [currentLinkHref, initialLinkEditorOpen])
const openLinkEditor = (): void => {
setLinkHref(currentLinkHref ?? '')
setIsLinkEditorOpen(true)
+ setShouldFocusLinkInput(true)
+ linkInputRef.current?.focus()
}
const setLink = (): void => {
@@ -354,10 +363,32 @@ export function FormattingToolbar({
aria-label="Link URL"
value={linkHref}
onChange={setLinkHref}
- onPressEnter={setLink}
- autoFocus
+ onPressEnter={(event) => {
+ // Cancel the keystroke fully: applying the link unmounts the toolbar
+ // and returns focus/selection to the editor, where an uncancelled
+ // Enter would still insert a paragraph and wipe the selected text
+ event.preventDefault()
+ event.stopPropagation()
+ setLink()
+ }}
+ inputRef={linkInputRef}
+ autoFocus={shouldFocusLinkInput}
className="MarkdownNotebook__format-link-input"
/>
+ {hasExistingLink && sanitizeNotebookLinkHref(currentLinkHref ?? '') ? (
+ <LemonButton
+ size="xsmall"
+ icon={<IconExternal />}
+ tooltip="Open link in new tab"
+ aria-label="Open link in new tab"
+ onClick={() => {
+ const href = sanitizeNotebookLinkHref(currentLinkHref ?? '')
+ if (href) {
+ window.open(href, '_blank', 'noopener')
+ }
+ }}
+ />
+ ) : null}
{hasExistingLink ? (
<LemonButton size="xsmall" status="danger" onClick={removeLink}>
Remove
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
index d584551d99e6..1ba4339b02c4 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
@@ -872,6 +872,18 @@
pointer-events: none;
}
+// Holding Cmd/Ctrl (MarkdownNotebook--link-modifier-held, toggled in MarkdownNotebook.tsx)
+// makes links clickable again so modifier-click can open them while editing
+.MarkdownNotebook--link-modifier-held .MarkdownNotebook__text-block[contenteditable='true'] a,
+.MarkdownNotebook--link-modifier-held
+ .MarkdownNotebook__list-block[contenteditable='true']
+ .MarkdownNotebook__list-item-content
+ a,
+.MarkdownNotebook--link-modifier-held .MarkdownNotebook__table-cell-content[contenteditable='true'] a {
+ pointer-events: auto;
+ cursor: pointer;
+}
+
.MarkdownNotebook__text-block--invalid-insert-filter {
color: inherit;
text-decoration: underline wavy var(--danger);
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index 25c2233a3666..99d1f9dd8bcc 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -785,6 +785,72 @@ continued line
expect(container.querySelector('.MarkdownNotebook__component-shell')).toBeInstanceOf(HTMLElement)
})
+ it('opens links on modifier-click while editing but not on plain click', () => {
+ const windowOpen = jest.spyOn(window, 'open').mockImplementation(() => null)
+ const { container } = render(
+ createElement(MarkdownNotebook, { value: withNotebookTitle('See [docs](https://posthog.com/docs)') })
+ )
+ const link = container.querySelector('.MarkdownNotebook__text-block a[href]') as HTMLAnchorElement
+ expect(link).toBeInstanceOf(HTMLAnchorElement)
+
+ fireEvent.click(link)
+ expect(windowOpen).not.toHaveBeenCalled()
+
+ fireEvent.click(link, { metaKey: true })
+ expect(windowOpen).toHaveBeenCalledWith('https://posthog.com/docs', '_blank', 'noopener')
+
+ // View mode keeps native navigation: the handler must not add a second open
+ windowOpen.mockClear()
+ const { container: viewContainer } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('See [docs](https://posthog.com/docs)'),
+ mode: 'view',
+ })
+ )
+ const viewLink = viewContainer.querySelector('.MarkdownNotebook__text-block a[href]') as HTMLAnchorElement
+ expect(viewLink).toBeInstanceOf(HTMLAnchorElement)
+ fireEvent.click(viewLink, { metaKey: true })
+ expect(windowOpen).not.toHaveBeenCalled()
+
+ windowOpen.mockRestore()
+ })
+
+ it('opens the link editor automatically when the selection is inside a link, without stealing focus', () => {
+ const { container } = render(
+ createElement(MarkdownNotebook, { value: withNotebookTitle('See [docs](https://posthog.com/docs) here') })
+ )
+ const anchor = getBodyTextBlock(container).querySelector('a')
+ expect(anchor).toBeInstanceOf(HTMLAnchorElement)
+
+ selectTextNode(getFirstTextNode(anchor as HTMLElement), 0, 4, true)
+
+ const input = container.querySelector('[aria-label="Link URL"]') as HTMLInputElement
+ expect(input).toBeInstanceOf(HTMLInputElement)
+ expect(input.value).toEqual('https://posthog.com/docs')
+ expect(window.document.activeElement).not.toBe(input)
+ })
+
+ it('applies the link and cancels the keystroke when pressing Enter in the link editor', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, { value: withNotebookTitle('Hello world out there'), onChange })
+ )
+
+ selectTextNode(getFirstTextNode(getBodyTextBlock(container)), 0, 5, true)
+
+ const toolbar = container.querySelector('.MarkdownNotebook__format-toolbar') as HTMLElement
+ fireEvent.click(toolbar.querySelector('[aria-label="Link"]') as HTMLButtonElement)
+
+ const input = container.querySelector('[aria-label="Link URL"]') as HTMLInputElement
+ fireEvent.change(input, { target: { value: 'https://posthog.com' } })
+
+ // The keystroke must be cancelled: once focus returns to the editor, an uncancelled
+ // Enter inserts a paragraph over the restored selection and wipes the linked text
+ const enterNotCancelled = fireEvent.keyDown(input, { key: 'Enter' })
+ expect(enterNotCancelled).toBe(false)
+ expect(onChange).toHaveBeenLastCalledWith(withNotebookTitle('[Hello](https://posthog.com) world out there'))
+ })
+
it('groups consecutive text, heading, and list rows into text surfaces', () => {
const { container } = render(
createElement(MarkdownNotebook, {
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
index b489b588d7f2..43f1f06e0d95 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
@@ -178,6 +178,7 @@ import {
makeEmptyParagraph,
makeListItemId,
parseMarkdownNotebook,
+ sanitizeNotebookLinkHref,
serializeMarkdownNotebook,
} from './markdown'
import { NOTEBOOK_AI_WRITING_PLACEHOLDER } from './notebookAI'
@@ -318,6 +319,11 @@ type NotebookHistoryState = {
}
/** Consecutive single-block edits within this window fold into one undo step. */
+// The editable surfaces whose links are pointer-inert while editing (see MarkdownNotebook.scss);
+// only these get the modifier-click open behavior, everything else keeps native navigation
+const POINTER_INERT_LINK_CONTAINER_SELECTOR =
+ '.MarkdownNotebook__text-block[contenteditable="true"], .MarkdownNotebook__list-block[contenteditable="true"], .MarkdownNotebook__table-cell-content[contenteditable="true"]'
+
const UNDO_TYPING_GROUP_MS = 1000
/** How many recent local serializations to remember for save-echo detection. Must comfortably
@@ -3935,9 +3941,53 @@ function MarkdownNotebookEditor({
}, 0)
}
+ // Links in editable blocks are pointer-inert so plain clicks place the caret; holding
+ // Cmd/Ctrl re-enables them (see MarkdownNotebook.scss) so they can be opened, matching
+ // the TipTap editor's link mark behavior.
+ useEffect(() => {
+ if (mode !== 'edit') {
+ return
+ }
+
+ const setLinkModifierHeld = (isHeld: boolean): void => {
+ notebookRef.current?.classList.toggle('MarkdownNotebook--link-modifier-held', isHeld)
+ }
+ const handleModifierKeyChange = (event: globalThis.KeyboardEvent): void =>
+ setLinkModifierHeld(event.metaKey || event.ctrlKey)
+ const resetLinkModifier = (): void => setLinkModifierHeld(false)
+
+ window.addEventListener('keydown', handleModifierKeyChange)
+ window.addEventListener('keyup', handleModifierKeyChange)
+ window.addEventListener('blur', resetLinkModifier)
+ return () => {
+ window.removeEventListener('keydown', handleModifierKeyChange)
+ window.removeEventListener('keyup', handleModifierKeyChange)
+ window.removeEventListener('blur', resetLinkModifier)
+ resetLinkModifier()
+ }
+ }, [mode])
+
const handleCanvasClick = (event: ReactMouseEvent<HTMLDivElement>): void => {
- const refElement = event.target instanceof Element ? event.target.closest('[data-notebook-ref]') : null
- const refId = refElement?.getAttribute('data-notebook-ref')
+ if (!(event.target instanceof Element)) {
+ return
+ }
+
+ const linkElement = event.target.closest('a[href]')
+ if (linkElement && linkElement.closest(POINTER_INERT_LINK_CONTAINER_SELECTOR)) {
+ if (event.metaKey || event.ctrlKey) {
+ const href = sanitizeNotebookLinkHref(linkElement.getAttribute('href') ?? '')
+ if (href) {
+ event.preventDefault()
+ window.open(href, '_blank', 'noopener')
+ return
+ }
+ } else {
+ // While editing, a plain click only places the caret, never navigates
+ event.preventDefault()
+ }
+ }
+
+ const refId = event.target.closest('[data-notebook-ref]')?.getAttribute('data-notebook-ref')
if (refId) {
focusDiscussionCommentForRef(refId)
}