: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(canvas): report the clicked line with comment-activate (#110829)
Shy Alter2798afcba8ba
diff --git a/products/canvas/backend/sandbox/sandbox_document.html b/products/canvas/backend/sandbox/sandbox_document.htmlindex 1cb4b268e94f..8e5a888c136a 100644--- a/products/canvas/backend/sandbox/sandbox_document.html+++ b/products/canvas/backend/sandbox/sandbox_document.html@@ -586,7 +586,7 @@if (event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom) {event.preventDefault();event.stopPropagation();- post({ type: "comment-activate", id: item.id });+ post({ type: "comment-activate", id: item.id, rect: { top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left } });return;}}diff --git a/products/canvas/frontend/host/BuiltCanvas.tsx b/products/canvas/frontend/host/BuiltCanvas.tsxindex 1703ff09445c..0772eececc31 100644--- a/products/canvas/frontend/host/BuiltCanvas.tsx+++ b/products/canvas/frontend/host/BuiltCanvas.tsx@@ -1,7 +1,7 @@import { useEffect, useLayoutEffect, useMemo, useRef } from 'react'import type { CanvasCapabilitiesApi } from '../generated/api.schemas'-import { translateCanvasTextSelection } from '../sidePanel/comments/canvasCommentThreads'+import { translateCanvasRect, translateCanvasTextSelection } from '../sidePanel/comments/canvasCommentThreads'import { assertCanvasCapability } from './canvasCapabilities'import { CanvasHostCallbacks, createCanvasHostMessageRouter } from './canvasHostMessageRouter'import {@@ -75,6 +75,11 @@ export function BuiltCanvas({latest.current.callbacks.onTextSelection?.(translateCanvasTextSelection(selection, iframe?.getBoundingClientRect() ?? null)),+ onCommentActivate: (id, rect) =>+ latest.current.callbacks.onCommentActivate?.(+ id,+ rect ? translateCanvasRect(rect, iframe?.getBoundingClientRect() ?? null) : null+ ),}),hasUserActivation: () => latest.current.hasUserActivation(),openExternal: (url) => latest.current.onOpenExternal(url),diff --git a/products/canvas/frontend/host/DraftCanvas.tsx b/products/canvas/frontend/host/DraftCanvas.tsxindex c21efaad6e7d..0b5c7d5cf812 100644--- a/products/canvas/frontend/host/DraftCanvas.tsx+++ b/products/canvas/frontend/host/DraftCanvas.tsx@@ -1,7 +1,7 @@import { useEffect, useLayoutEffect, useRef } from 'react'import type { CanvasCapabilitiesApi } from '../generated/api.schemas'-import { translateCanvasTextSelection } from '../sidePanel/comments/canvasCommentThreads'+import { translateCanvasRect, translateCanvasTextSelection } from '../sidePanel/comments/canvasCommentThreads'import { assertCanvasCapability } from './canvasCapabilities'import { CanvasDocumentBridge } from './canvasDocumentBridge'import { CanvasHostCallbacks, createCanvasHostMessageRouter } from './canvasHostMessageRouter'@@ -107,6 +107,11 @@ export function DraftCanvas({latest.current.callbacks.onTextSelection?.(translateCanvasTextSelection(selection, iframeRef.current?.getBoundingClientRect() ?? null)),+ onCommentActivate: (id, rect) =>+ latest.current.callbacks.onCommentActivate?.(+ id,+ rect ? translateCanvasRect(rect, iframeRef.current?.getBoundingClientRect() ?? null) : null+ ),}),hasUserActivation: () => latest.current.hasUserActivation(),openExternal: (url) => latest.current.onOpenExternal(url),diff --git a/products/canvas/frontend/host/canvasHostMessageRouter.test.ts b/products/canvas/frontend/host/canvasHostMessageRouter.test.tsindex 9546f87c8cd6..f1deef3738e9 100644--- a/products/canvas/frontend/host/canvasHostMessageRouter.test.ts+++ b/products/canvas/frontend/host/canvasHostMessageRouter.test.ts@@ -11,6 +11,7 @@ function setup(options: { activated?: boolean; onDataRequest?: () => Promise<unkposted: HostToCanvasMessage[]onDataRequest: jest.MockonNavigate: jest.Mock+ onCommentActivate: jest.MockopenExternal: jest.MockonExternalOpenBlocked: jest.Mockclock: { now: number }@@ -18,18 +19,19 @@ function setup(options: { activated?: boolean; onDataRequest?: () => Promise<unkconst posted: HostToCanvasMessage[] = []const onDataRequest = jest.fn(options.onDataRequest ?? (async () => ({ ok: true })))const onNavigate = jest.fn()+ const onCommentActivate = jest.fn()const openExternal = jest.fn()const onExternalOpenBlocked = jest.fn()const clock = { now: 10_000 }const route = createCanvasHostMessageRouter({post: (message) => posted.push(message),- callbacks: () => ({ onDataRequest, onNavigate }),+ callbacks: () => ({ onDataRequest, onNavigate, onCommentActivate }),hasUserActivation: () => options.activated ?? false,openExternal,onExternalOpenBlocked,now: () => clock.now,})- return { route, posted, onDataRequest, onNavigate, openExternal, onExternalOpenBlocked, clock }+ return { route, posted, onDataRequest, onNavigate, onCommentActivate, openExternal, onExternalOpenBlocked, clock }}const dataRequest = (method: string, payload: unknown = {}): CanvasToHostMessage =>@@ -138,6 +140,23 @@ describe('createCanvasHostMessageRouter', () => {expect(onNavigate).toHaveBeenCalledTimes(forwarded ? 1 : 0)})+ test.each([+ ['with the clicked line', { top: 10, right: 90, bottom: 30, left: 20 }],+ ['from a build that reports no line', undefined],+ ])('comment-activate %s reaches the host', async (_, rect) => {+ const { route, onCommentActivate } = setup()+ const message = canvasToHostMessageSchema.parse({+ channel: 'posthog-canvas',+ type: 'comment-activate',+ id: 'thread-1',+ ...(rect ? { rect } : {}),+ })++ await route(message)++ expect(onCommentActivate).toHaveBeenCalledWith('thread-1', rect ?? null)+ })+test('open-external needs a gesture and is throttled', async () => {const blocked = setup({ activated: false })await blocked.route({ channel: 'posthog-canvas', type: 'open-external', url: 'https://posthog.com/docs' })diff --git a/products/canvas/frontend/host/canvasHostMessageRouter.ts b/products/canvas/frontend/host/canvasHostMessageRouter.tsindex 7efc962d66ed..d3631f492b7a 100644--- a/products/canvas/frontend/host/canvasHostMessageRouter.ts+++ b/products/canvas/frontend/host/canvasHostMessageRouter.ts@@ -1,6 +1,7 @@import {CANVAS_CHANNEL,CanvasNavIntent,+ CanvasRect,CanvasTextSelection,CanvasToHostMessage,HostToCanvasMessage,@@ -70,7 +71,7 @@ export interface CanvasHostCallbacks {onTextSelection?: (selection: CanvasTextSelection) => voidonTextSelectionCleared?: () => void/** The viewer clicked a highlighted comment anchor. */- onCommentActivate?: (id: string) => void+ onCommentActivate?: (id: string, rect: CanvasRect | null) => void}export type ExternalOpenBlockReason = 'unsafe-url' | 'no-interaction' | 'throttled'@@ -215,7 +216,7 @@ export function createCanvasHostMessageRouter(options.callbacks().onTextSelectionCleared?.()breakcase 'comment-activate':- options.callbacks().onCommentActivate?.(message.id)+ options.callbacks().onCommentActivate?.(message.id, message.rect ?? null)break}}diff --git a/products/canvas/frontend/host/canvasProtocol.ts b/products/canvas/frontend/host/canvasProtocol.tsindex abcd99d2e308..b6925dd34977 100644--- a/products/canvas/frontend/host/canvasProtocol.ts+++ b/products/canvas/frontend/host/canvasProtocol.ts@@ -94,6 +94,14 @@ export const CANVAS_DATA_METHODS = [] as constexport type CanvasDataMethod = (typeof CANVAS_DATA_METHODS)[number]+const canvasRectSchema = z.object({+ top: z.number().finite(),+ right: z.number().finite(),+ bottom: z.number().finite(),+ left: z.number().finite(),+})+export type CanvasRect = z.infer<typeof canvasRectSchema>+const canvasTextSelectionSchema = z.object({quote: z.string(),@@ -101,12 +109,7 @@ const canvasTextSelectionSchema = zsuffix: z.string(),start: z.number().int().min(0),end: z.number().int().min(0),- rect: z.object({- top: z.number().finite(),- right: z.number().finite(),- bottom: z.number().finite(),- left: z.number().finite(),- }),+ rect: canvasRectSchema,}).refine(({ start, end }) => end > start)/** A selection the canvas reported, in the frame's own coordinates. */@@ -145,7 +148,12 @@ export const canvasToHostMessageSchema = z.discriminatedUnion('type', [}),z.object({ channel, type: z.literal('text-selection'), selection: canvasTextSelectionSchema }),z.object({ channel, type: z.literal('text-selection-cleared') }),- z.object({ channel, type: z.literal('comment-activate'), id: z.string().min(1).max(128) }),+ z.object({+ channel,+ type: z.literal('comment-activate'),+ id: z.string().min(1).max(128),+ rect: canvasRectSchema.optional(),+ }),z.object({channel,type: z.literal('keydown'),diff --git a/products/canvas/frontend/sidePanel/comments/canvasCommentThreads.ts b/products/canvas/frontend/sidePanel/comments/canvasCommentThreads.tsindex d3cd101316b4..27b612507df3 100644--- a/products/canvas/frontend/sidePanel/comments/canvasCommentThreads.ts+++ b/products/canvas/frontend/sidePanel/comments/canvasCommentThreads.ts@@ -1,6 +1,6 @@import type { CommentType } from '~/types'-import type { CanvasCommentHighlight, CanvasTextSelection } from '../../host/canvasProtocol'+import type { CanvasCommentHighlight, CanvasRect, CanvasTextSelection } from '../../host/canvasProtocol'// Canvas comments are ordinary PostHog comments with scope "canvas" and the canvas id as// item_id. The item_context shape is shared with PostHog Desktop, which writes the same@@ -132,22 +132,23 @@ export function canvasCommentHighlights(return highlights}+export function translateCanvasRect(rect: CanvasRect, frame: Pick<DOMRect, 'left' | 'top'> | null): CanvasRect {+ const left = frame?.left ?? 0+ const top = frame?.top ?? 0+ return {+ top: rect.top + top,+ right: rect.right + left,+ bottom: rect.bottom + top,+ left: rect.left + left,+ }+}+/** Moves a selection rect from the frame's coordinates into the page's, so the host can anchor UI to it. */export function translateCanvasTextSelection(selection: CanvasTextSelection,frame: Pick<DOMRect, 'left' | 'top'> | null): CanvasTextSelection {- const left = frame?.left ?? 0- const top = frame?.top ?? 0- return {- ...selection,- rect: {- top: selection.rect.top + top,- right: selection.rect.right + left,- bottom: selection.rect.bottom + top,- left: selection.rect.left + left,- },- }+ return { ...selection, rect: translateCanvasRect(selection.rect, frame) }}/** The anchor stored on a comment made from a selection. */diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.tsindex 09d9417b8f29..51c6896450b5 100644--- a/products/desktop/packages/core/src/canvas/freeformSchemas.ts+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.ts@@ -187,13 +187,15 @@ export type CanvasAnalyticsConfig = z.infer<typeof canvasAnalyticsConfigSchema>;export const canvasThemeSchema = z.enum(["light", "dark"]);export type CanvasTheme = z.infer<typeof canvasThemeSchema>;+const canvasRectSchema = z.object({+ top: z.number().finite(),+ right: z.number().finite(),+ bottom: z.number().finite(),+ left: z.number().finite(),+});+const canvasTextSelectionDataSchema = textCommentAnchorDataSchema.extend({- rect: z.object({- top: z.number().finite(),- right: z.number().finite(),- bottom: z.number().finite(),- left: z.number().finite(),- }),+ rect: canvasRectSchema,});export const canvasTextSelectionSchema = canvasTextSelectionDataSchema.refine(({ start, end }) => end > start,@@ -392,6 +394,7 @@ export const canvasToHostMessageSchema = z.discriminatedUnion("type", [channel: z.literal(CANVAS_CHANNEL),type: z.literal("comment-activate"),id: z.string().min(1).max(128),+ rect: canvasRectSchema.optional(),}),z.object({channel: z.literal(CANVAS_CHANNEL),diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.tsindex 7768dcf12461..42b9011c7d9e 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts@@ -527,7 +527,7 @@ export function buildSandboxDocument(if (event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom) {event.preventDefault();event.stopPropagation();- post({ type: "comment-activate", id: item.id });+ post({ type: "comment-activate", id: item.id, rect: { top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left } });return;}}