Skip to content

Commit f03cee9

Browse files
karancs06claude
andcommitted
fix(discussions): pull comment highlights after iframe DOM settles (REQUEST_DISCUSSION_HIGHLIGHTS)
When the user switches variants, the iframe's CSR app re-renders asynchronously and mutates every data-cslp attribute. If the visual editor pushes comment-icon highlights before those mutations settle, icons anchor to stale CSLP elements and drift permanently, or the SDK's internal retry window (900 ms) expires before the correct element appears and no icon is mounted. This change inverts the coordination: the SDK's existing variant-class MutationObserver now ALSO emits REQUEST_DISCUSSION_HIGHLIGHTS (debounced 200 ms) whenever data-cslp attributes mutate. The visual editor treats that as a pull request and re-sends the highlight payload against the now-final DOM. Because the payload already contains both base and variant CSLP rows, whichever one matches the current DOM wins. Changes in this repo: - postMessage.types.ts: add REQUEST_DISCUSSION_HIGHLIGHTS event. - useRecalculateVariantDataCSLPValues.ts: debounce-emit the event from the existing per-element MutationObserver callback. - useVariantsPostMessageEvent.ts: for SSR apps the DOM is already final so emit immediately; for CSR apps the observer handles it. - generateHighlightedComment.tsx: updateHighlightedCommentIconPosition now removes orphaned icons whose target [data-cslp] has disappeared, instead of silently leaving them drifted. Tests: 3 new SSR-path tests plus a 5-test file for the orphan cleanup in generateHighlightedComment. The MutationObserver → debounce → postMessage path is an integration guarantee — jsdom does not fire attribute mutations reliably, so it is verified in the visual-editor DiscussionPage tests where the listener is driven directly. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 69fea25 commit f03cee9

6 files changed

Lines changed: 199 additions & 1 deletion

File tree

src/visualBuilder/eventManager/__test__/useVariantsPostMessageEvent.spec.ts

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -669,4 +669,62 @@ describe("useVariantFieldsPostMessageEvent SSR handling", () => {
669669
expect(mockQuerySelectorAll).not.toHaveBeenCalled();
670670
expect(updateVariantClasses).not.toHaveBeenCalled();
671671
});
672+
673+
it("sends REQUEST_DISCUSSION_HIGHLIGHTS immediately when isSSR is true and variant is provided", () => {
674+
useVariantFieldsPostMessageEvent({ isSSR: true });
675+
676+
const call = mockVisualBuilderPostMessage.on.mock.calls.find(
677+
(call: any[]) =>
678+
call[0] === VisualBuilderPostMessageEvents.GET_VARIANT_ID
679+
);
680+
const handler = call ? call[1] : null;
681+
682+
vi.clearAllMocks();
683+
handler!({ data: { variant: "variant-123" } });
684+
685+
// SSR DOM is already in its final state — the observer would never
686+
// fire, so we must ask the visual editor for a fresh highlight list.
687+
expect(mockVisualBuilderPostMessage.send).toHaveBeenCalledWith(
688+
VisualBuilderPostMessageEvents.REQUEST_DISCUSSION_HIGHLIGHTS
689+
);
690+
});
691+
692+
it("sends REQUEST_DISCUSSION_HIGHLIGHTS immediately when isSSR is true even if variant is null", () => {
693+
useVariantFieldsPostMessageEvent({ isSSR: true });
694+
695+
const call = mockVisualBuilderPostMessage.on.mock.calls.find(
696+
(call: any[]) =>
697+
call[0] === VisualBuilderPostMessageEvents.GET_VARIANT_ID
698+
);
699+
const handler = call ? call[1] : null;
700+
701+
vi.clearAllMocks();
702+
handler!({ data: { variant: null } });
703+
704+
// Switching back to base is still a CSLP-relevant change — VB needs to
705+
// re-compute and re-send highlights against the new (base) CSLPs.
706+
expect(mockVisualBuilderPostMessage.send).toHaveBeenCalledWith(
707+
VisualBuilderPostMessageEvents.REQUEST_DISCUSSION_HIGHLIGHTS
708+
);
709+
});
710+
711+
it("does not send REQUEST_DISCUSSION_HIGHLIGHTS directly when isSSR is false (observer handles it)", () => {
712+
useVariantFieldsPostMessageEvent({ isSSR: false });
713+
714+
const call = mockVisualBuilderPostMessage.on.mock.calls.find(
715+
(call: any[]) =>
716+
call[0] === VisualBuilderPostMessageEvents.GET_VARIANT_ID
717+
);
718+
const handler = call ? call[1] : null;
719+
720+
vi.clearAllMocks();
721+
handler!({ data: { variant: "variant-123" } });
722+
723+
// For CSR apps the event is emitted by the MutationObserver inside
724+
// updateVariantClasses, not synchronously from the handler.
725+
expect(mockVisualBuilderPostMessage.send).not.toHaveBeenCalledWith(
726+
VisualBuilderPostMessageEvents.REQUEST_DISCUSSION_HIGHLIGHTS
727+
);
728+
expect(updateVariantClasses).toHaveBeenCalled();
729+
});
672730
});

src/visualBuilder/eventManager/useRecalculateVariantDataCSLPValues.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,14 @@ import { DATA_CSLP_ATTR_SELECTOR } from "../utils/constants";
55
import { visualBuilderStyles } from "../visualBuilder.style";
66
import { isValidCslp } from "../../cslp/cslpdata";
77
import { setHighlightVariantFields } from "./useVariantsPostMessageEvent";
8+
import visualBuilderPostMessage from "../utils/visualBuilderPostMessage";
9+
import { VisualBuilderPostMessageEvents } from "../utils/types/postMessage.types";
810

911
const VARIANT_UPDATE_DELAY_MS: Readonly<number> = 8000;
12+
// Debounce window after the last observed mutation before asking the visual
13+
// editor to re-send discussion highlights. Short enough to feel responsive;
14+
// long enough to coalesce a burst of mutations into a single request.
15+
const DISCUSSION_HIGHLIGHTS_DEBOUNCE_MS: Readonly<number> = 200;
1016

1117
type OnAudienceModeVariantPatchUpdate = {
1218
highlightVariantFields: boolean;
@@ -32,6 +38,21 @@ export function updateVariantClasses(): void {
3238
const variant = VisualBuilder.VisualBuilderGlobalState.value.variant;
3339
const observers: MutationObserver[] = [];
3440

41+
// Ask the visual editor to re-send discussion highlights once the current
42+
// burst of data-cslp mutations has settled. The VB owns the field-path list
43+
// (it can be per-variant) so the iframe cannot re-mount comment icons on
44+
// its own — it can only request a refresh.
45+
let highlightsRequestTimer: ReturnType<typeof setTimeout> | null = null;
46+
const requestDiscussionHighlights = () => {
47+
if (highlightsRequestTimer !== null) clearTimeout(highlightsRequestTimer);
48+
highlightsRequestTimer = setTimeout(() => {
49+
highlightsRequestTimer = null;
50+
visualBuilderPostMessage?.send(
51+
VisualBuilderPostMessageEvents.REQUEST_DISCUSSION_HIGHLIGHTS
52+
);
53+
}, DISCUSSION_HIGHLIGHTS_DEBOUNCE_MS);
54+
};
55+
3556
// Helper function to update element classes
3657
const updateElementClasses = (
3758
element: HTMLElement,
@@ -156,6 +177,7 @@ export function updateVariantClasses(): void {
156177
DATA_CSLP_ATTR_SELECTOR
157178
);
158179
updateElementClasses(element, dataCslp || "", observer);
180+
requestDiscussionHighlights();
159181
}
160182
});
161183
});

src/visualBuilder/eventManager/useVariantsPostMessageEvent.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,8 +167,18 @@ export function useVariantFieldsPostMessageEvent({ isSSR }: { isSSR: boolean }):
167167
if (selectedVariant) {
168168
addVariantFieldClass(selectedVariant);
169169
}
170+
// SSR DOM is already in its final state (no async re-render) —
171+
// the MutationObserver in updateVariantClasses will never fire,
172+
// so ask the visual editor to re-send discussion highlights now
173+
// that the classes are applied against the final CSLP values.
174+
visualBuilderPostMessage?.send(
175+
VisualBuilderPostMessageEvents.REQUEST_DISCUSSION_HIGHLIGHTS
176+
);
170177
} else {
171-
// recalculate and apply classes
178+
// For CSR apps the framework re-renders asynchronously after
179+
// receiving the new variant, mutating data-cslp attributes.
180+
// updateVariantClasses installs a MutationObserver that emits
181+
// REQUEST_DISCUSSION_HIGHLIGHTS once those mutations settle.
172182
updateVariantClasses();
173183
}
174184
}
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import { describe, it, expect, beforeEach, afterEach } from "vitest";
2+
import {
3+
updateHighlightedCommentIconPosition,
4+
removeAllHighlightedCommentIcons,
5+
} from "../generateHighlightedComment";
6+
7+
describe("updateHighlightedCommentIconPosition", () => {
8+
let container: HTMLDivElement;
9+
10+
beforeEach(() => {
11+
container = document.createElement("div");
12+
container.className = "visual-builder__container";
13+
document.body.appendChild(container);
14+
});
15+
16+
afterEach(() => {
17+
document.body.removeChild(container);
18+
});
19+
20+
const makeIcon = (fieldPath: string): HTMLDivElement => {
21+
const icon = document.createElement("div");
22+
icon.className = "highlighted-comment collab-icon";
23+
icon.setAttribute("field-path", fieldPath);
24+
icon.style.position = "fixed";
25+
icon.style.top = "100px";
26+
icon.style.left = "200px";
27+
container.appendChild(icon);
28+
return icon;
29+
};
30+
31+
const makeTarget = (cslpValue: string): HTMLDivElement => {
32+
const el = document.createElement("div");
33+
el.setAttribute("data-cslp", cslpValue);
34+
container.appendChild(el);
35+
return el;
36+
};
37+
38+
it("keeps an icon whose target element is still present", () => {
39+
const cslp = "content.entry.en-us.field";
40+
makeTarget(cslp);
41+
makeIcon(cslp);
42+
43+
updateHighlightedCommentIconPosition();
44+
45+
expect(
46+
document.querySelector(`.highlighted-comment[field-path="${cslp}"]`),
47+
).not.toBeNull();
48+
});
49+
50+
it("removes an orphaned icon when its target element is no longer found", () => {
51+
// Stale CSLP with no matching element — simulates the element having
52+
// been mutated to a variant CSLP value.
53+
const staleCslp = "content.entry.en-us.old_field";
54+
makeIcon(staleCslp);
55+
56+
updateHighlightedCommentIconPosition();
57+
58+
expect(
59+
document.querySelector(`.highlighted-comment[field-path="${staleCslp}"]`),
60+
).toBeNull();
61+
});
62+
63+
it("removes only orphaned icons and keeps valid ones", () => {
64+
const validCslp = "content.entry.en-us.valid";
65+
const staleCslp = "content.entry.en-us.stale";
66+
67+
makeTarget(validCslp);
68+
makeIcon(validCslp);
69+
makeIcon(staleCslp);
70+
71+
updateHighlightedCommentIconPosition();
72+
73+
expect(
74+
document.querySelector(`.highlighted-comment[field-path="${validCslp}"]`),
75+
).not.toBeNull();
76+
expect(
77+
document.querySelector(`.highlighted-comment[field-path="${staleCslp}"]`),
78+
).toBeNull();
79+
});
80+
81+
it("does not throw when there are no icons", () => {
82+
expect(() => updateHighlightedCommentIconPosition()).not.toThrow();
83+
});
84+
});
85+
86+
describe("removeAllHighlightedCommentIcons", () => {
87+
it("removes every .highlighted-comment element", () => {
88+
["a", "b", "c"].forEach((cslp) => {
89+
const icon = document.createElement("div");
90+
icon.className = "highlighted-comment collab-icon";
91+
icon.setAttribute("field-path", cslp);
92+
document.body.appendChild(icon);
93+
});
94+
95+
expect(document.querySelectorAll(".highlighted-comment").length).toBe(3);
96+
97+
removeAllHighlightedCommentIcons();
98+
99+
expect(document.querySelectorAll(".highlighted-comment").length).toBe(0);
100+
});
101+
});

src/visualBuilder/generators/generateHighlightedComment.tsx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,12 @@ export function updateHighlightedCommentIconPosition() {
9595
// Update the position of the icon container
9696
icon.style.top = `${top - highlighCommentOffset}px`; // Adjust based on the target element's top
9797
icon.style.left = `${left - highlighCommentOffset}px`; // Adjust based on the target element's left
98+
} else {
99+
// Target element is gone (e.g. data-cslp mutated after a
100+
// variant switch). Remove the orphaned icon instead of
101+
// silently leaving it drifted — the visual editor will
102+
// re-mount a fresh set via REQUEST_DISCUSSION_HIGHLIGHTS.
103+
icon.remove();
98104
}
99105
}
100106
}

src/visualBuilder/utils/types/postMessage.types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,4 +59,5 @@ export enum VisualBuilderPostMessageEvents {
5959
COLLAB_THREAD_REOPEN = "collab-thread-reopen",
6060
COLLAB_THREAD_HIGHLIGHT = "collab-thread-highlight",
6161
TOGGLE_SCROLL = "toggle-scroll",
62+
REQUEST_DISCUSSION_HIGHLIGHTS = "request-discussion-highlights",
6263
}

0 commit comments

Comments
 (0)