: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
feat(notebooks): hint cmd-click to open links while editing (#103146)
posthog[bot]a4664692ed53
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scssindex b3a99e720115..8eb2d40cccf6 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss@@ -888,6 +888,11 @@pointer-events: auto;}+.MarkdownNotebook__link-hint-anchor {+ position: fixed;+ 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,diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.tsindex 038443b050a7..066319a5c504 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts@@ -943,6 +943,42 @@ Following paragraph`,windowOpen.mockRestore()})+ it('hints Ctrl-click on a hovered link while editing, but not in view mode', () => {+ jest.useFakeTimers()+ try {+ const hoverLink = (mode: 'edit' | 'view'): HTMLAnchorElement => {+ const { container } = render(+ createElement(MarkdownNotebook, {+ value: withNotebookTitle('See [docs](https://posthog.com/docs)'),+ mode,+ })+ )+ const link = container.querySelector('.MarkdownNotebook__text-block a[href]') as HTMLAnchorElement+ fireEvent.mouseOver(link)+ act(() => {+ jest.advanceTimersByTime(1000)+ })+ return link+ }++ const link = hoverLink('edit')+ expect(document.body.textContent).toContain('Ctrl + click to open link')++ // Moving onto the surrounding text clears the hint+ fireEvent.mouseOver(link.parentElement as HTMLElement)+ act(() => {+ jest.advanceTimersByTime(1000)+ })+ expect(document.body.textContent).not.toContain('click to open link')++ // A plain click already opens links in view mode, so the hint would be wrong there+ hoverLink('view')+ expect(document.body.textContent).not.toContain('click to open link')+ } finally {+ jest.useRealTimers()+ }+ })+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') })diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsxindex e92880a69879..51bc68144dd7 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx@@ -22,10 +22,10 @@ import {} from 'react'import { IconCode, IconComment, IconDrag } from '@posthog/icons'-import { LemonButton } from '@posthog/lemon-ui'+import { LemonButton, Tooltip } from '@posthog/lemon-ui'import { Spinner } from 'lib/lemon-ui/Spinner'-import { downloadFile } from 'lib/utils/dom'+import { downloadFile, isMac } from 'lib/utils/dom'import { lazyWithRetry } from 'lib/utils/retryImport'// Monaco is heavy, so the markdown source editor only loads when the source drawer opens.@@ -353,6 +353,9 @@ const POINTER_INERT_LINK_CONTAINER_SELECTOR =const UNDO_TYPING_GROUP_MS = 1000+/** How long the pointer rests on a link in an editable block before the open-link hint appears. */+const LINK_HINT_DELAY_MS = 400+/** How many recent local serializations to remember for save-echo detection. Must comfortably* cover the keystrokes that can land between a save being sent and its response echoing back. */const MAX_TRACKED_LOCAL_SNAPSHOTS = 100@@ -641,6 +644,9 @@ function MarkdownNotebookEditor({ensureEditableNotebookDocument(parseMarkdownNotebook(value)))const [floatingToolbar, setFloatingToolbar] = useState<FloatingToolbarState | null>(null)+ const [linkHintRect, setLinkHintRect] = useState<DOMRect | null>(null)+ const hoveredLinkRef = useRef<Element | null>(null)+ const linkHintTimeoutRef = useRef<number | null>(null)const [insertMenu, setInsertMenu] = useState<InsertMenuState | null>(null)const [insertMenuPosition, setInsertMenuPosition] = useState<InsertMenuPosition | null>(null)const [activeRowIndex, setActiveRowIndex] = useState<number | null>(null)@@ -4090,6 +4096,47 @@ function MarkdownNotebookEditor({}}, [mode])+ const clearLinkHint = useCallback((): void => {+ if (linkHintTimeoutRef.current !== null) {+ window.clearTimeout(linkHintTimeoutRef.current)+ linkHintTimeoutRef.current = null+ }+ hoveredLinkRef.current = null+ setLinkHintRect(null)+ }, [])++ useEffect(() => clearLinkHint, [clearLinkHint])++ // The hint is positioned from the link's rect at hover time, so a scroll would strand it+ useEffect(() => {+ if (!linkHintRect) {+ return+ }+ window.addEventListener('scroll', clearLinkHint, { capture: true, passive: true })+ return () => window.removeEventListener('scroll', clearLinkHint, { capture: true })+ }, [linkHintRect, clearLinkHint])++ // Links in editable blocks only open on modifier-click, which nothing else on screen tells+ // the reader. Leaving the link for any other part of the canvas lands here too and clears it.+ const handleCanvasMouseOver = (event: ReactMouseEvent<HTMLDivElement>): void => {+ const linkElement = mode === 'edit' && event.target instanceof Element ? event.target.closest('a[href]') : null+ if (!linkElement || !linkElement.closest(POINTER_INERT_LINK_CONTAINER_SELECTOR)) {+ if (hoveredLinkRef.current) {+ clearLinkHint()+ }+ return+ }+ if (linkElement === hoveredLinkRef.current) {+ return+ }+ clearLinkHint()+ hoveredLinkRef.current = linkElement+ linkHintTimeoutRef.current = window.setTimeout(() => {+ linkHintTimeoutRef.current = null+ setLinkHintRect(linkElement.getBoundingClientRect())+ }, LINK_HINT_DELAY_MS)+ }+const handleCanvasClick = (event: ReactMouseEvent<HTMLDivElement>): void => {if (!(event.target instanceof Element)) {return@@ -5047,6 +5094,7 @@ function MarkdownNotebookEditor({}const handleCanvasMouseLeave = (): void => {+ clearLinkHint()setActiveRowIndex(null)setActiveBoundaryIndex(null)}@@ -6224,6 +6272,7 @@ function MarkdownNotebookEditor({aria-activedescendant={activeInsertMenuOptionDomId}onInput={handleRootEditableInput}onKeyDown={handleRootEditableKeyDown}+ onMouseOver={handleCanvasMouseOver}onMouseLeave={handleCanvasMouseLeave}onClick={handleCanvasClick}onDragStartCapture={() => {@@ -6318,6 +6367,23 @@ function MarkdownNotebookEditor({containerRef={mainRef}/>) : null}+ {linkHintRect && mode === 'edit' && !floatingToolbar ? (+ // A link in the canvas is raw HTML, so no Tooltip can wrap it; this empty+ // box sits over the hovered link and anchors the tooltip instead. The+ // formatting toolbar has its own open-link button and would sit under it.+ <Tooltip visible title={`${isMac() ? '⌘' : 'Ctrl'} + click to open link`}>+ <span+ aria-hidden+ className="MarkdownNotebook__link-hint-anchor"+ style={{+ top: linkHintRect.top,+ left: linkHintRect.left,+ width: linkHintRect.width,+ height: linkHintRect.height,+ }}+ />+ </Tooltip>+ ) : null}{floatingToolbar && mode === 'edit' ? (<FormattingToolbarselectedBlockStyle={getSelectedBlockStyle(diff --git a/frontend/src/lib/components/MarkdownNotebook/README.md b/frontend/src/lib/components/MarkdownNotebook/README.mdindex e04eca4e9c7b..af0a15f9369b 100644--- a/frontend/src/lib/components/MarkdownNotebook/README.md+++ b/frontend/src/lib/components/MarkdownNotebook/README.md@@ -24,7 +24,7 @@ See [COMPONENTS.md](./COMPONENTS.md) for how to register embeddable components (## Supported markdown-Inline: bold (`**`/`__`), italic (`*`/`_`, underscores only at word boundaries), underline (`<u>`), strikethrough (`~~`), inline code, links (http/https only; balanced parentheses in hrefs supported), hard breaks, ref anchors (`<ref id="x">highlighted text</ref>`, lowercase inline tags so they can never collide with uppercase component tags), and mentions (`<mention id="5">@Name</mention>`; the text is the display label, the id is the member). Blocks: paragraphs, headings (`#`–`######` parse and round-trip; the UI offers H1–H3), blockquotes (including quoted headings — `> ## Heading` — and quoted lists), ordered/unordered lists with nesting, GFM task lists (`- [ ]`/`- [x]` on bullet items; the checkbox replaces the bullet and `1. [x]` stays literal), GFM tables with column alignment (header and body rows must start with `|`), fenced code blocks (language tag preserved; the serializer picks a fence longer than any backtick run in the content), dividers (`---`/`***`/`___`, stored as a reserved `Divider` component tag), images (``, stored as the `Image` component), and JSX-like component tags. Blocks are separated by a blank line; a second blank line additionally starts a new card (see [Visual grouping](#visual-grouping)).+Inline: bold (`**`/`__`), italic (`*`/`_`, underscores only at word boundaries), underline (`<u>`), strikethrough (`~~`), inline code, links (http/https only; balanced parentheses in hrefs supported, as is the pointy-bracket href form `[label](<href>)` that Slack copies produce), hard breaks, ref anchors (`<ref id="x">highlighted text</ref>`, lowercase inline tags so they can never collide with uppercase component tags), and mentions (`<mention id="5">@Name</mention>`; the text is the display label, the id is the member). Blocks: paragraphs, headings (`#`–`######` parse and round-trip; the UI offers H1–H3), blockquotes (including quoted headings — `> ## Heading` — and quoted lists), ordered/unordered lists with nesting, GFM task lists (`- [ ]`/`- [x]` on bullet items; the checkbox replaces the bullet and `1. [x]` stays literal), GFM tables with column alignment (header and body rows must start with `|`), fenced code blocks (language tag preserved; the serializer picks a fence longer than any backtick run in the content), dividers (`---`/`***`/`___`, stored as a reserved `Divider` component tag), images (``, stored as the `Image` component), and JSX-like component tags. Blocks are separated by a blank line; a second blank line additionally starts a new card (see [Visual grouping](#visual-grouping)).### Round-trip guaranteediff --git a/frontend/src/lib/components/MarkdownNotebook/markdown.ts b/frontend/src/lib/components/MarkdownNotebook/markdown.tsindex 96d1e6aafa31..a4840e722530 100644--- a/frontend/src/lib/components/MarkdownNotebook/markdown.ts+++ b/frontend/src/lib/components/MarkdownNotebook/markdown.ts@@ -555,6 +555,21 @@ function parseInlineLink(return null}+ const label = markdown.slice(index + 1, labelEnd)++ // CommonMark's pointy-bracket form, `[label](<href>)`. Slack writes links this way, so it+ // arrives with every link someone copies out of a Slack message.+ if (markdown[labelEnd + 2] === '<') {+ const hrefEnd = markdown.indexOf('>', labelEnd + 3)+ if (hrefEnd !== -1 && markdown[hrefEnd + 1] === ')') {+ return {+ label,+ href: sanitizeNotebookLinkHref(markdown.slice(labelEnd + 3, hrefEnd)),+ nextIndex: hrefEnd + 2,+ }+ }+ }+// Hrefs may contain backslash-escaped characters and balanced parentheses (Wikipedia-style URLs)let cursor = labelEnd + 2let parenDepth = 0@@ -573,7 +588,7 @@ function parseInlineLink(if (character === ')') {if (parenDepth === 0) {return {- label: markdown.slice(index + 1, labelEnd),+ label,href: sanitizeNotebookLinkHref(rawHref),nextIndex: cursor + 1,}diff --git a/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts b/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.tsindex e94a8414d586..963bf5cbd439 100644--- a/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts@@ -504,6 +504,25 @@ describe('markdown round trip', () => {expect(getNodeText(nodes[0])).toEqual('wiki end')})+ it('parses the pointy-bracket href form that Slack copies produce', () => {+ const nodes = parseMarkdownNotebook('See [Payloads](<https://posthog.com/docs/payloads>) now').nodes+ const children = (nodes[0] as NotebookTextBlockNode).children++ expect(children[1].type === 'text' && children[1].marks?.[0]).toEqual({+ type: 'link',+ href: 'https://posthog.com/docs/payloads',+ })+ expect(getNodeText(nodes[0])).toEqual('See Payloads now')+ })++ it('keeps the label but drops the link when a pointy bracket is left unclosed', () => {+ const nodes = parseMarkdownNotebook('[Payloads](<https://posthog.com/docs) end').nodes++ expect(getNodeText(nodes[0])).toEqual('Payloads end')+ const child = (nodes[0] as NotebookTextBlockNode).children[0]+ expect(child.type === 'text' && child.marks).toBeUndefined()+ })+it('drops disallowed link schemes but keeps the label text', () => {// eslint-disable-next-line no-script-urlconst nodes = parseMarkdownNotebook('[click](javascript:alert(1)) safe').nodes