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(desktop): isolate artifact comment action styles (#80243)

Shy Alter25142c05d603
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.test.ts b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.test.ts
index 52b2ebe53821..df6fd99646ac 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.test.ts
@@ -60,9 +60,33 @@ function releaseOn(dom: JSDOM, selector: string): void {
);
}
-function actionButton(dom: JSDOM): HTMLElement | null {
+function actionHost(dom: JSDOM): HTMLElement | null {
return dom.window.document.querySelector<HTMLElement>(
- ".ph-comment-action-button",
+ "[data-selection-comment-overlay]",
+ );
+}
+
+function actionButton(dom: JSDOM): HTMLElement | null {
+ return (
+ actionHost(dom)?.shadowRoot?.querySelector<HTMLElement>(
+ ".ph-comment-action-button",
+ ) ?? null
+ );
+}
+
+function pressAction(dom: JSDOM): void {
+ const element = actionButton(dom);
+ if (!element) throw new Error("missing comment action");
+ element.dispatchEvent(
+ new dom.window.MouseEvent("pointerdown", { bubbles: true, composed: true }),
+ );
+}
+
+function activateAction(dom: JSDOM): void {
+ const element = actionButton(dom);
+ if (!element) throw new Error("missing comment action");
+ element.dispatchEvent(
+ new dom.window.MouseEvent("mousedown", { bubbles: true, composed: true }),
);
}
@@ -87,6 +111,27 @@ describe("artifactHtmlCommentBridge", () => {
dom.window.close();
});
+ it("keeps artifact styles from targeting the comment action or its host", () => {
+ const dom = loadBridgeDocument(
+ '<html><head><style>button,posthog-comment-action{all:unset!important;display:none!important}</style></head><body><button id="artifact-button">Artifact</button><p>some selectable text here</p></body></html>',
+ );
+
+ pressOn(dom, "p");
+ selectParagraph(dom);
+ releaseOn(dom, "p");
+
+ const host = actionHost(dom);
+ const button = actionButton(dom);
+ if (!host || !button) throw new Error("missing isolated comment action");
+ expect(button.getRootNode()).toBe(host.shadowRoot);
+ expect(dom.window.getComputedStyle(host).display).toBe("block");
+ expect(dom.window.document.querySelectorAll("button")).toHaveLength(1);
+ expect(host.shadowRoot?.querySelector("style")?.textContent).toContain(
+ ".ph-comment-action-button",
+ );
+ dom.window.close();
+ });
+
it("ignores presses on the action button itself", () => {
const dom = loadBridgeDocument(
"<html><body><p>some selectable text here</p></body></html>",
@@ -97,50 +142,119 @@ describe("artifactHtmlCommentBridge", () => {
releaseOn(dom, "p");
expect(actionButton(dom)?.style.display).toBe("flex");
- pressOn(dom, ".ph-comment-action-button");
+ pressAction(dom);
expect(actionButton(dom)?.style.display).toBe("flex");
dom.window.close();
});
- it("bakes the requested theme into the bridge styles", () => {
- const dark = injectArtifactHtmlCommentBridge("<html><body></body></html>", {
+ it("posts the selected anchor and action position when activated", () => {
+ const dom = loadBridgeDocument(
+ "<html><body><p>some selectable text here</p></body></html>",
+ );
+ const messages: unknown[] = [];
+ dom.window.postMessage = ((message: unknown) => {
+ messages.push(message);
+ }) as typeof dom.window.postMessage;
+
+ pressOn(dom, "p");
+ selectParagraph(dom);
+ releaseOn(dom, "p");
+ const button = actionButton(dom);
+ if (!button) throw new Error("missing comment action");
+ button.getBoundingClientRect = () =>
+ ({
+ top: 32,
+ left: 118,
+ right: 222,
+ bottom: 60,
+ width: 104,
+ height: 28,
+ }) as DOMRect;
+
+ activateAction(dom);
+
+ expect(messages).toHaveLength(1);
+ expect(messages[0]).toMatchObject({
+ marker: BRIDGE_MARKER,
channel: CHANNEL,
- theme: "dark",
+ type: "selection",
+ anchor: {
+ kind: "text",
+ quote: "some selectable text here",
+ start: 0,
+ end: 25,
+ },
+ rect: {
+ top: 40,
+ left: 10,
+ right: 110,
+ bottom: 60,
+ width: 100,
+ height: 20,
+ },
+ triggerRect: {
+ top: 32,
+ left: 118,
+ right: 222,
+ bottom: 60,
+ width: 104,
+ height: 28,
+ },
});
- const light = injectArtifactHtmlCommentBridge(
- "<html><body></body></html>",
- { channel: CHANNEL, theme: "light" },
- );
- expect(dark).toContain(
- `--ph-comment-action-bg:${COMMENT_ACTION_BUTTON_THEMES.dark.background}`,
- );
- expect(light).toContain(
- `--ph-comment-action-bg:${COMMENT_ACTION_BUTTON_THEMES.light.background}`,
- );
+ expect(actionButton(dom)?.style.display).toBe("none");
+ dom.window.close();
});
- it("re-themes a running document from a host theme message", () => {
+ it.each(["light", "dark"] as const)(
+ "applies the %s theme to the isolated comment action",
+ (theme) => {
+ const dom = loadBridgeDocument(
+ "<html><body><p>text</p></body></html>",
+ theme,
+ );
+ pressOn(dom, "p");
+ selectParagraph(dom);
+ releaseOn(dom, "p");
+
+ expect(
+ actionButton(dom)?.style.getPropertyValue("--ph-comment-action-bg"),
+ ).toBe(COMMENT_ACTION_BUTTON_THEMES[theme].background);
+ dom.window.close();
+ },
+ );
+
+ it("uses host theme changes before and after the action is created", () => {
const dom = loadBridgeDocument(
"<html><body><p>text</p></body></html>",
"light",
);
- // jsdom's postMessage leaves event.source null; the bridge ignores those.
- dom.window.dispatchEvent(
- new dom.window.MessageEvent("message", {
- data: {
- marker: BRIDGE_MARKER,
- channel: CHANNEL,
- type: "theme",
- theme: "dark",
- },
- source: dom.window,
- }),
- );
+ const sendTheme = (theme: "light" | "dark") => {
+ // jsdom's postMessage leaves event.source null; the bridge ignores those.
+ dom.window.dispatchEvent(
+ new dom.window.MessageEvent("message", {
+ data: {
+ marker: BRIDGE_MARKER,
+ channel: CHANNEL,
+ type: "theme",
+ theme,
+ },
+ source: dom.window,
+ }),
+ );
+ };
+
+ sendTheme("dark");
+ pressOn(dom, "p");
+ selectParagraph(dom);
+ releaseOn(dom, "p");
expect(
- dom.window.document.documentElement.style.getPropertyValue(
- "--ph-comment-action-bg",
- ),
+ actionButton(dom)?.style.getPropertyValue("--ph-comment-action-bg"),
).toBe(COMMENT_ACTION_BUTTON_THEMES.dark.background);
+
+ sendTheme("light");
+ expect(
+ actionButton(dom)?.style.getPropertyValue("--ph-comment-action-bg"),
+ ).toBe(COMMENT_ACTION_BUTTON_THEMES.light.background);
dom.window.close();
});
});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts
index 644465d3d11b..336ebdfeb2fa 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts
@@ -5,7 +5,6 @@ import {
type CommentSurfaceTheme,
commentActionAnchorRect,
commentActionButtonCss,
- commentActionButtonCssVars,
computeCommentActionPlacement,
installSelectionSettleGate,
setCommentActionTheme,
@@ -28,7 +27,7 @@ function artifactHtmlCommentBridge(
"use strict";
var CHANNEL=${safeChannel};
var MARKER=${JSON.stringify(BRIDGE_MARKER)};
-var state={button:null,timer:0,renderTimer:0,entries:[],items:[]};
+var state={button:null,timer:0,renderTimer:0,entries:[],items:[],theme:${JSON.stringify(theme)}};
var supportsHighlights=!!(window.Highlight&&window.CSS&&CSS.highlights);
var current=document.currentScript;if(current)current.remove();
function send(type,payload){parent.postMessage(Object.assign({marker:MARKER,channel:CHANNEL,type:type},payload||{}),"*");}
@@ -44,9 +43,9 @@ var placeAction=${computeCommentActionPlacement.toString()};
var anchorRect=${commentActionAnchorRect.toString()};
var resolveAnchor=${resolveTextCommentAnchor.toString()};
function resolve(all,a){return resolveAnchor(all,a)}
-function style(){var s=document.createElement("style");s.setAttribute("data-posthog-artifact-comments","");s.textContent="::highlight(posthog-artifact-comment){background:rgba(250,204,21,.32);color:inherit}::highlight(posthog-artifact-comment-active){background:rgba(250,204,21,.48);color:inherit}:root{${commentActionButtonCssVars(theme)}}${commentActionButtonCss()}";(document.head||document.documentElement).appendChild(s)}
+function style(){var s=document.createElement("style");s.setAttribute("data-posthog-artifact-comments","");s.textContent="::highlight(posthog-artifact-comment){background:rgba(250,204,21,.32);color:inherit}::highlight(posthog-artifact-comment-active){background:rgba(250,204,21,.48);color:inherit}";(document.head||document.documentElement).appendChild(s)}
function hide(){if(state.button)state.button.style.display="none"}
-function button(){if(state.button&&state.button.isConnected)return state.button;var b=document.createElement("button");b.type="button";b.className="ph-comment-action-button";b.setAttribute("data-selection-comment-overlay","");b.setAttribute("aria-label","Comment");b.innerHTML=ACTION_ICON+"<span>Comment</span>";b.style.display="none";b.addEventListener("mousedown",function(e){e.preventDefault();e.stopPropagation();var sel=window.getSelection();if(!sel||sel.isCollapsed||!sel.rangeCount)return hide();var range=sel.getRangeAt(0),anchor=makeAnchor(range);if(!anchor)return hide();var r=range.getBoundingClientRect(),br=b.getBoundingClientRect();send("selection",{anchor:anchor,rect:{top:r.top,left:r.left,right:r.right,bottom:r.bottom,width:r.width,height:r.height},triggerRect:{top:br.top,left:br.left,right:br.right,bottom:br.bottom,width:br.width,height:br.height}});hide();sel.removeAllRanges()});document.documentElement.appendChild(b);state.button=b;return b;}
+function button(){if(state.button&&state.button.isConnected)return state.button;var host=document.createElement("posthog-comment-action");host.setAttribute("data-selection-comment-overlay","");host.style.cssText="all:initial!important;display:block!important;position:fixed!important;top:0!important;left:0!important;width:0!important;height:0!important;overflow:visible!important;z-index:2147483647!important";var root=host.attachShadow({mode:"open"});var s=document.createElement("style");s.textContent=${JSON.stringify(commentActionButtonCss())};root.appendChild(s);var b=document.createElement("button");b.type="button";b.className="ph-comment-action-button";b.setAttribute("aria-label","Comment");b.innerHTML=ACTION_ICON+"<span>Comment</span>";setActionTheme(state.theme,THEMES,b);b.style.display="none";b.addEventListener("mousedown",function(e){e.preventDefault();e.stopPropagation();var sel=window.getSelection();if(!sel||sel.isCollapsed||!sel.rangeCount)return hide();var range=sel.getRangeAt(0),anchor=makeAnchor(range);if(!anchor)return hide();var r=range.getBoundingClientRect(),br=b.getBoundingClientRect();send("selection",{anchor:anchor,rect:{top:r.top,left:r.left,right:r.right,bottom:r.bottom,width:r.width,height:r.height},triggerRect:{top:br.top,left:br.left,right:br.right,bottom:br.bottom,width:br.width,height:br.height}});hide();sel.removeAllRanges()});root.appendChild(b);document.documentElement.appendChild(host);state.button=b;return b;}
function positionButton(){var sel=window.getSelection();if(!sel||sel.isCollapsed||!sel.rangeCount)return hide();var value=sel.toString().trim();if(value.length<2||value.length>10000)return hide();var range=sel.getRangeAt(0);var r=anchorRect(range.getClientRects?range.getClientRects():[],range.getBoundingClientRect());if(!r||(r.width===0&&r.height===0))return hide();var b=button();var box=b.getBoundingClientRect();var pos=placeAction({top:r.top,right:r.right,bottom:r.bottom},{width:innerWidth,height:innerHeight},{width:box.width||104,height:box.height||28});b.style.left=pos.left+"px";b.style.top=pos.top+"px";b.style.display="flex"}
function selectionChanged(){clearTimeout(state.timer);state.timer=setTimeout(positionButton,80)}
function render(items){state.items=items||[];state.entries=[];var normal=supportsHighlights?new Highlight():null,active=supportsHighlights?new Highlight():null,resolutions=[],index=textIndex();state.items.forEach(function(item){var hit=resolve(index.text,item.anchor);if(!hit){resolutions.push({id:item.id,status:"orphaned"});return}var range=rangeAt(index,hit.start,hit.end);if(!range){resolutions.push({id:item.id,status:"orphaned"});return}state.entries.push({id:item.id,range:range,active:!!item.active});resolutions.push({id:item.id,status:hit.status});if(supportsHighlights){if(item.active)active.add(range);else normal.add(range)}});if(supportsHighlights){CSS.highlights.set("posthog-artifact-comment",normal);CSS.highlights.set("posthog-artifact-comment-active",active)}send("resolutions",{items:resolutions})}
@@ -59,7 +58,7 @@ selectionSettleGate(document,{onGestureStart:hide,onSelectionSettled:positionBut
document.addEventListener("scroll",hide,true);
document.addEventListener("click",function(e){var target=e.target,link=target&&target.closest?target.closest("a[href]"):null;if(link){e.preventDefault();e.stopPropagation();send("open-external",{href:link.href});return}for(var i=0;i<state.entries.length;i++){var rects=state.entries[i].range.getClientRects();for(var j=0;j<rects.length;j++){var r=rects[j];if(e.clientX>=r.left&&e.clientX<=r.right&&e.clientY>=r.top&&e.clientY<=r.bottom){e.preventDefault();e.stopPropagation();send("activate",{id:state.entries[i].id});return}}}},true);
new MutationObserver(function(){if(!state.items.length||state.renderTimer)return;state.renderTimer=setTimeout(function(){state.renderTimer=0;render(state.items)},500)}).observe(document.body,{childList:true,characterData:true,subtree:true});
-window.addEventListener("message",function(e){if(e.source!==parent)return;var d=e.data;if(!d||d.marker!==MARKER||d.channel!==CHANNEL)return;if(d.type==="comments")render(d.items);else if(d.type==="locate"&&typeof d.id==="string")locate(d.id);else if(d.type==="theme"&&(d.theme==="light"||d.theme==="dark"))setActionTheme(d.theme,THEMES)});
+window.addEventListener("message",function(e){if(e.source!==parent)return;var d=e.data;if(!d||d.marker!==MARKER||d.channel!==CHANNEL)return;if(d.type==="comments")render(d.items);else if(d.type==="locate"&&typeof d.id==="string")locate(d.id);else if(d.type==="theme"&&(d.theme==="light"||d.theme==="dark")){state.theme=d.theme;if(state.button)setActionTheme(d.theme,THEMES,state.button)}});
style();send("ready");
})();</script>`;
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/selectionCommentAction.test.ts b/products/desktop/packages/ui/src/features/sessions/components/selectionCommentAction.test.ts
index a09da6dc1879..7fb8a26b6a51 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/selectionCommentAction.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/selectionCommentAction.test.ts
@@ -3,7 +3,6 @@ import {
COMMENT_ACTION_BUTTON_THEMES,
commentActionAnchorRect,
commentActionButtonCss,
- commentActionButtonCssVars,
computeCommentActionPlacement,
installSelectionSettleGate,
type SelectionSettleGateCallbacks,
@@ -207,34 +206,25 @@ describe("selectionCommentAction", () => {
});
it("applies every theme variable the action button styles reference", () => {
+ const target = document.createElement("button");
for (const theme of ["light", "dark"] as const) {
- setCommentActionTheme(theme, COMMENT_ACTION_BUTTON_THEMES);
+ setCommentActionTheme(theme, COMMENT_ACTION_BUTTON_THEMES, target);
const css = commentActionButtonCss();
for (const match of css.matchAll(
/var\((--ph-comment-action-[a-z-]+)\)/g,
)) {
expect(
- document.documentElement.style.getPropertyValue(match[1]),
+ target.style.getPropertyValue(match[1]),
`${theme} sets ${match[1]}`,
).toBe(COMMENT_ACTION_BUTTON_THEMES[theme][cssVarField(match[1])]);
}
}
- document.documentElement.style.cssText = "";
});
it("falls back to the light palette for an unknown theme name", () => {
- setCommentActionTheme("solarized", COMMENT_ACTION_BUTTON_THEMES);
- expect(
- document.documentElement.style.getPropertyValue("--ph-comment-action-bg"),
- ).toBe(COMMENT_ACTION_BUTTON_THEMES.light.background);
- document.documentElement.style.cssText = "";
- });
-
- it("bakes the requested theme into the :root variable declarations", () => {
- expect(commentActionButtonCssVars("dark")).toContain(
- COMMENT_ACTION_BUTTON_THEMES.dark.background,
- );
- expect(commentActionButtonCssVars("light")).toContain(
+ const target = document.createElement("button");
+ setCommentActionTheme("solarized", COMMENT_ACTION_BUTTON_THEMES, target);
+ expect(target.style.getPropertyValue("--ph-comment-action-bg")).toBe(
COMMENT_ACTION_BUTTON_THEMES.light.background,
);
});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/selectionCommentAction.ts b/products/desktop/packages/ui/src/features/sessions/components/selectionCommentAction.ts
index 0818d0ba9ee8..d6354cf0a391 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/selectionCommentAction.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/selectionCommentAction.ts
@@ -44,13 +44,6 @@ export const COMMENT_ACTION_BUTTON_THEMES: Record<
export const COMMENT_ACTION_ICON_SVG =
'<svg width="14" height="14" viewBox="0 0 256 256" fill="currentColor" aria-hidden="true"><path d="M128,20A108,108,0,0,0,31.85,177.23L21,209.66A20,20,0,0,0,46.34,235l32.43-10.81A108,108,0,1,0,128,20Zm0,192a84,84,0,0,1-42.06-11.27,12,12,0,0,0-6-1.62,12.1,12.1,0,0,0-3.8.62l-29.79,9.93,9.93-29.79a12,12,0,0,0-1-9.81A84,84,0,1,1,128,212Z"/></svg>';
-// CSS variables let the host flip the theme of an already-running iframe
-// document with a `theme` message instead of rebuilding (and reloading) it.
-export function commentActionButtonCssVars(theme: CommentSurfaceTheme): string {
- const palette = COMMENT_ACTION_BUTTON_THEMES[theme];
- return `--ph-comment-action-bg:${palette.background};--ph-comment-action-fg:${palette.color};--ph-comment-action-border:${palette.border};--ph-comment-action-hover:${palette.hoverBackground};--ph-comment-action-shadow:${palette.shadow};`;
-}
-
// The one comment action look, shared by every surface: the app renders this
// class directly and the sandboxed iframes inject the same rules, so a markdown
// artifact, an HTML artifact and a canvas cannot drift apart. Solid themed
@@ -65,10 +58,11 @@ export function commentActionButtonCss(): string {
export function setCommentActionTheme(
theme: string,
themes: Record<string, CommentActionButtonTheme>,
+ target: HTMLElement,
): void {
const palette = themes[theme] || themes.light;
if (!palette) return;
- const style = document.documentElement.style;
+ const style = target.style;
style.setProperty("--ph-comment-action-bg", palette.background);
style.setProperty("--ph-comment-action-fg", palette.color);
style.setProperty("--ph-comment-action-border", palette.border);