: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(toolbar): invert Link's notebook drag behind a DI seam (#69135)
Rafael Audibert7026f7ec439a
diff --git a/.agents/toolbar-migration.md b/.agents/toolbar-migration.mdindex 16b699c5e8f3..d3f821ee8c35 100644--- a/.agents/toolbar-migration.md+++ b/.agents/toolbar-migration.md@@ -4,7 +4,7 @@ This file is the committed source of truth for the toolbar bundle modernization## Status-- **Current step**: Steps 1–4 and 7 implemented and in review as a Graphite stack (drafts), plus a seventh PR batching the simple Step 5/6 moves (PanelSettings, UrlMatchingHints, KeyboardShortcut, LemonMarkdown mermaid barrel — baseline 31 → 25) an eighth cutting the preflight + web-analytics-achievements edges (baseline 25 → 18), and a ninth moving themeLogic/dataThemeLogic to `lib/logic/` (baseline 18 → 12). A lint-guard PR (#69133) now sits at the bottom of the stack (oxlint exhaustive-deps suppressions where `--fix-dangerously` corrupted files). Next: Link→DraggableToNotebook DI seam, then the Step 7 eager-logic audit, then Step 8 (riskiest, last). The remaining survey-labels/taxonomy/experiments/product-tours edges are candidates for documented intentional seams rather than cuts.+- **Current step**: Steps 1–4 and 7 implemented and in review as a Graphite stack (drafts), plus a seventh PR batching the simple Step 5/6 moves (PanelSettings, UrlMatchingHints, KeyboardShortcut, LemonMarkdown mermaid barrel — baseline 31 → 25) an eighth cutting the preflight + web-analytics-achievements edges (baseline 25 → 18), a ninth moving themeLogic/dataThemeLogic to `lib/logic/` (baseline 18 → 12), and a tenth inverting Link→DraggableToNotebook with the `useLinkDrag` DI seam (baseline 12 → 11). A lint-guard PR (#69133) sits at the bottom of the stack (oxlint exhaustive-deps suppressions where `--fix-dangerously` corrupted files). Next: the Step 7 eager-logic audit, then Step 8 (riskiest, last). The remaining survey-labels/taxonomy/experiments/product-tours edges are candidates for documented intentional seams rather than cuts.- **Last updated**: 2026-07-07- **PRs**: Step 1 — `rafa/toolbar-migration-1-graph-guard` (#69045); Step 3 — `rafa/toolbar-migration-2-products-urls-split` (#69071); chain cuts + shim-leak fix — `rafa/toolbar-migration-3-shim-leak-and-chain-cuts` (#69088); Step 2 — `rafa/toolbar-migration-4-loader-esm-splitting` (#69093); Step 4 — `rafa/toolbar-migration-5-types-replay-shared-cut` (#69106); Step 7 — `rafa/toolbar-migration-6-lazy-menus` (#69113); Step 5/6 batch — `rafa/toolbar-migration-7-simple-edge-cuts` (#69122) (each stacked on the previous)- **Reorder note (resolved)**: a trial Step 2 build emitted **487 dead chunks** — with `products.tsx` reachable, every product scene's dynamic import becomes a real chunk in `dist/toolbar/`. The gate was: flip the format only once `products.tsx` leaves the graph. That's now done via two moves in the third PR. First, the remaining chains all funneled through one root cause: the kea shims only matched exact alias strings (`scenes/teamLogic`), so relative imports (`dataThemeLogic` → `./teamLogic`) and `~/`-prefixed imports pulled the REAL logics and their whole app graph — fixed with relative + `~/` matching in `createToolbarModulePlugin`, disconnecting `products.tsx`, `scenes.ts`, `teamLogic`, `PersonDisplay`, and `experimentsLogic` in one move. Second, `scenes/urls` itself (imported by lib components shared with the app) is shimmed to the toolbar's parity-tested `~/toolbar/urls` duplicate from Step 3, taking the last products-manifest path out. Bundle graph 8448 → ~1000 files (99 → ~13.5 MiB source), shipped `dist/toolbar.js` 9.95 MB → ~4 MB (was just under the 10 MB CloudFront cliff). Graph budget ratcheted 110 MB → 18 MB.@@ -105,7 +105,7 @@ Approach (revised on review): rather than restructuring the generated products m### Step 6 — shared lib → scenes back-edges (each also helps the main app)-- [ ] `lib/lemon-ui/Link/Link.tsx` → `DraggableToNotebook` (drags notebooks → tiptap): invert with a registry/context seam (the flagship shim→DI replacement)+- [x] `lib/lemon-ui/Link/Link.tsx` → `DraggableToNotebook`: inverted with the flagship DI seam — `lib/lemon-ui/Link/useLinkDrag.ts` holds a swappable hook (inert default), `registerNotebookLinkDrag()` (called from `bootApp()`, before first render — swapping later would break hook order) installs the notebook implementation. Toolbar and exporter keep the inert default and stop bundling notebooks drag; a jest test covers the registered wiring end to end (drag start → uri-list payload)- [x] `lib/lemon-ui/LemonColor/*` → `dataThemeLogic` and HedgehogMode/JSONViewer/LemonColorGlyph → `themeLogic`: both logics (plus `themes.ts`) moved to `lib/logic/` — they're global UI state whose app-zone deps (sceneLogic, userLogic, teamLogic) already resolve to toolbar shims, so the move is placement-only. Old paths re-export for the ~60 app importers; all `src/lib` importers repointed. Cuts 6 baseline edges (props/context seam not needed)- [x] `lib/lemon-ui/LemonMarkdown/index.ts`: the barrel no longer re-exports `LemonMarkdownWithMermaid` (the one product user imports the module directly); the `mermaid` deny in `toolbar-config.mjs` is retired, reintroduction caught by FORBIDDEN_PACKAGES- [x] `HeatmapEventsPanel` → `PersonDisplay`: replaced with a plain span (PersonDisplay renders exactly that for a distinct_id-only person with `noPopover`); `TZLabel` → teamLogic edge now shimmed at resolve time (`~/scenes/teamLogic` matching)diff --git a/frontend/bin/toolbar-graph-baseline.json b/frontend/bin/toolbar-graph-baseline.jsonindex 33a4591811ec..ddbdff196b23 100644--- a/frontend/bin/toolbar-graph-baseline.json+++ b/frontend/bin/toolbar-graph-baseline.json@@ -2,7 +2,6 @@"//": "Toolbar -> app-zone import edges that exist today, enforced by bin/check-toolbar-graph.mjs. Do not add entries; delete them as the migration (.agents/toolbar-migration.md) cuts each edge.","edges": ["src/lib/components/PropertyKeyInfo.tsx -> src/scenes/surveys/surveyQuestionLabelsLogic.ts",- "src/lib/lemon-ui/Link/Link.tsx -> src/scenes/notebooks/AddToNotebook/DraggableToNotebook.tsx","src/lib/utils/eventUsageLogic.ts -> src/scenes/product-tours/constants.ts","src/taxonomy/helpers.ts -> src/scenes/surveys/surveyQuestionLabelsLogic.ts","src/taxonomy/taxonomy.tsx -> src/scenes/web-analytics/tabs/marketing-analytics/utils.ts",diff --git a/frontend/src/lib/lemon-ui/Link/Link.tsx b/frontend/src/lib/lemon-ui/Link/Link.tsxindex fad0bbec0e07..93da949dc569 100644--- a/frontend/src/lib/lemon-ui/Link/Link.tsx+++ b/frontend/src/lib/lemon-ui/Link/Link.tsx@@ -10,10 +10,10 @@ import { cn } from 'lib/utils/css-classes'import { getCurrentTeamId } from 'lib/utils/getAppContext'import { addProjectIdIfMissing, removeProjectIdIfPresent } from 'lib/utils/kea-router'import { isExternalLink } from 'lib/utils/url'-import { useNotebookDrag } from 'scenes/notebooks/AddToNotebook/DraggableToNotebook'import { urlToResource } from 'scenes/urls'import { Tooltip, TooltipProps } from '../Tooltip'+import { useLinkDrag } from './useLinkDrag'type RoutePart = string | Record<string, any>@@ -150,9 +150,7 @@ export const LinkPrimitive: React.FC<LinkPrimitiveProps & React.RefAttributes<HTref) => {const externalLink = isExternalLink(to)- const { elementProps: draggableProps } = useNotebookDrag({- href: typeof to === 'string' ? to : undefined,- })+ const { elementProps: draggableProps } = useLinkDrag(typeof to === 'string' ? to : undefined)const onClick = (event: React.MouseEvent<HTMLElement>): void => {if (event.metaKey || event.ctrlKey) {diff --git a/frontend/src/lib/lemon-ui/Link/useLinkDrag.ts b/frontend/src/lib/lemon-ui/Link/useLinkDrag.tsnew file mode 100644index 000000000000..c1e0ed949f3e--- /dev/null+++ b/frontend/src/lib/lemon-ui/Link/useLinkDrag.ts@@ -0,0 +1,31 @@+import type React from 'react'++export interface LinkDragProps {+ elementProps: Pick<React.HTMLAttributes<HTMLElement>, 'onDragStart' | 'onDragEnd'>+}++export type UseLinkDragHook = (href: string | undefined) => LinkDragProps++const useNoopLinkDrag: UseLinkDragHook = () => ({ elementProps: {} })++let useLinkDragHook: UseLinkDragHook = useNoopLinkDrag++/**+ * Replaces the hook `Link` uses to make anchors draggable. The app registers the+ * drag-to-notebook implementation in `bootApp()`; bundles without notebooks (toolbar,+ * exporter) keep the inert default. Must be called before the first `Link` renders:+ * the implementation is read during render, and swapping it while Links are mounted+ * would violate the rules of hooks.+ */+export function setLinkDragHook(hook: UseLinkDragHook): void {+ useLinkDragHook = hook+}++/** Restores the inert default. Test-only: keeps a registered hook from leaking across tests. */+export function resetLinkDragHook(): void {+ useLinkDragHook = useNoopLinkDrag+}++export function useLinkDrag(href: string | undefined): LinkDragProps {+ return useLinkDragHook(href)+}diff --git a/frontend/src/scenes/App.tsx b/frontend/src/scenes/App.tsxindex 05a45b501420..58be93600a2b 100644--- a/frontend/src/scenes/App.tsx+++ b/frontend/src/scenes/App.tsx@@ -17,6 +17,7 @@ import { oauthLogic } from 'lib/oauth/oauthLogic'import { retryImport } from 'lib/utils/retryImport'import { appLogic } from 'scenes/appLogic'import { appScenes } from 'scenes/appScenes'+import { registerNotebookLinkDrag } from 'scenes/notebooks/AddToNotebook/registerNotebookLinkDrag'import { sceneLogic } from 'scenes/sceneLogic'import { userLogic } from 'scenes/userLogic'@@ -49,6 +50,9 @@ export function bootApp(): void {loadPostHogJS()// Kea must initialize before any component mountsinitKea()+ // Link resolves its drag-to-notebook behavior through a seam so bundles without+ // notebooks (toolbar, exporter) don't ship them; the app opts in here+ registerNotebookLinkDrag()const idle =typeof window.requestIdleCallback === 'function'diff --git a/frontend/src/scenes/notebooks/AddToNotebook/registerNotebookLinkDrag.test.tsx b/frontend/src/scenes/notebooks/AddToNotebook/registerNotebookLinkDrag.test.tsxnew file mode 100644index 000000000000..aca019a6c133--- /dev/null+++ b/frontend/src/scenes/notebooks/AddToNotebook/registerNotebookLinkDrag.test.tsx@@ -0,0 +1,30 @@+import { fireEvent, render } from '@testing-library/react'++import { Link } from 'lib/lemon-ui/Link'+import { resetLinkDragHook } from 'lib/lemon-ui/Link/useLinkDrag'++import { initKeaTests } from '~/test/init'++import { registerNotebookLinkDrag } from './registerNotebookLinkDrag'++describe('registerNotebookLinkDrag', () => {+ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => {+ resetLinkDragHook()+ })++ it('wires notebook drag into Link so dragging an internal link carries its url', () => {+ registerNotebookLinkDrag()+ const { container } = render(<Link to="/insights">Insights</Link>)+ const anchor = container.querySelector('a')+ expect(anchor).toBeTruthy()++ const dataTransfer = { setData: jest.fn() }+ fireEvent.dragStart(anchor!, { dataTransfer })++ expect(dataTransfer.setData).toHaveBeenCalledWith('text/uri-list', `${window.location.origin}/insights`)+ })+})diff --git a/frontend/src/scenes/notebooks/AddToNotebook/registerNotebookLinkDrag.ts b/frontend/src/scenes/notebooks/AddToNotebook/registerNotebookLinkDrag.tsnew file mode 100644index 000000000000..31adaf4a1506--- /dev/null+++ b/frontend/src/scenes/notebooks/AddToNotebook/registerNotebookLinkDrag.ts@@ -0,0 +1,12 @@+import { LinkDragProps, setLinkDragHook } from 'lib/lemon-ui/Link/useLinkDrag'++import { useNotebookDrag } from './DraggableToNotebook'++function useNotebookLinkDrag(href: string | undefined): LinkDragProps {+ return useNotebookDrag({ href })+}++/** Makes every `Link` with an internal href draggable into the notebook panel. */+export function registerNotebookLinkDrag(): void {+ setLinkDragHook(useNotebookLinkDrag)+}diff --git a/frontend/src/scenes/web-analytics/WebTileHeader.test.tsx b/frontend/src/scenes/web-analytics/WebTileHeader.test.tsxindex e786a0249c7a..963fd2e55399 100644--- a/frontend/src/scenes/web-analytics/WebTileHeader.test.tsx+++ b/frontend/src/scenes/web-analytics/WebTileHeader.test.tsx@@ -3,6 +3,7 @@ import { cleanup, fireEvent, render, within } from '@testing-library/react'import { LemonMenuItem } from '@posthog/lemon-ui'import { queryByDataAttr } from '~/test/byDataAttr'+import { initKeaTests } from '~/test/init'import { TileId } from './common'import { WebTileHeader } from './WebTileHeader'@@ -13,6 +14,11 @@ const noopMenuItems: LemonMenuItem[] = []describe('WebTileHeader', () => {+ beforeEach(() => {+ // Clicking a Link pushes to the kea router, so the router logic must be live+ initKeaTests()+ })+afterEach(() => {cleanup()})@@ -98,7 +104,8 @@ describe('WebTileHeader', () => {)const button = queryByDataAttr(container, 'web-analytics-open-insight-SOURCES')expect(button).toBeTruthy()- expect(button?.getAttribute('href')).toBe('/insights/new?web-source')+ // Link prefixes internal hrefs with the current project id from the app context+ expect(button?.getAttribute('href')).toBe('/project/997/insights/new?web-source')fireEvent.click(button!)expect(onClick).toHaveBeenCalledTimes(1)})