Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -669,4 +669,62 @@ describe("useVariantFieldsPostMessageEvent SSR handling", () => {
expect(mockQuerySelectorAll).not.toHaveBeenCalled();
expect(updateVariantClasses).not.toHaveBeenCalled();
});

it("sends REQUEST_DISCUSSION_HIGHLIGHTS immediately when isSSR is true and variant is provided", () => {
useVariantFieldsPostMessageEvent({ isSSR: true });

const call = mockVisualBuilderPostMessage.on.mock.calls.find(
(call: any[]) =>
call[0] === VisualBuilderPostMessageEvents.GET_VARIANT_ID
);
const handler = call ? call[1] : null;

vi.clearAllMocks();
handler!({ data: { variant: "variant-123" } });

// SSR DOM is already in its final state — the observer would never
// fire, so we must ask the visual editor for a fresh highlight list.
expect(mockVisualBuilderPostMessage.send).toHaveBeenCalledWith(
VisualBuilderPostMessageEvents.REQUEST_DISCUSSION_HIGHLIGHTS
);
});

it("sends REQUEST_DISCUSSION_HIGHLIGHTS immediately when isSSR is true even if variant is null", () => {
useVariantFieldsPostMessageEvent({ isSSR: true });

const call = mockVisualBuilderPostMessage.on.mock.calls.find(
(call: any[]) =>
call[0] === VisualBuilderPostMessageEvents.GET_VARIANT_ID
);
const handler = call ? call[1] : null;

vi.clearAllMocks();
handler!({ data: { variant: null } });

// Switching back to base is still a CSLP-relevant change — VB needs to
// re-compute and re-send highlights against the new (base) CSLPs.
expect(mockVisualBuilderPostMessage.send).toHaveBeenCalledWith(
VisualBuilderPostMessageEvents.REQUEST_DISCUSSION_HIGHLIGHTS
);
});

it("does not send REQUEST_DISCUSSION_HIGHLIGHTS directly when isSSR is false (observer handles it)", () => {
useVariantFieldsPostMessageEvent({ isSSR: false });

const call = mockVisualBuilderPostMessage.on.mock.calls.find(
(call: any[]) =>
call[0] === VisualBuilderPostMessageEvents.GET_VARIANT_ID
);
const handler = call ? call[1] : null;

vi.clearAllMocks();
handler!({ data: { variant: "variant-123" } });

// For CSR apps the event is emitted by the MutationObserver inside
// updateVariantClasses, not synchronously from the handler.
expect(mockVisualBuilderPostMessage.send).not.toHaveBeenCalledWith(
VisualBuilderPostMessageEvents.REQUEST_DISCUSSION_HIGHLIGHTS
);
expect(updateVariantClasses).toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,20 @@ import { DATA_CSLP_ATTR_SELECTOR } from "../utils/constants";
import { visualBuilderStyles } from "../visualBuilder.style";
import { isValidCslp } from "../../cslp/cslpdata";
import { setHighlightVariantFields } from "./useVariantsPostMessageEvent";
import visualBuilderPostMessage from "../utils/visualBuilderPostMessage";
import { VisualBuilderPostMessageEvents } from "../utils/types/postMessage.types";
import { debounce } from "lodash-es";

const VARIANT_UPDATE_DELAY_MS: Readonly<number> = 8000;

// Coalesce a burst of data-cslp mutations into a single request to the
// visual editor.
const requestDiscussionHighlights = debounce(() => {
visualBuilderPostMessage?.send(
VisualBuilderPostMessageEvents.REQUEST_DISCUSSION_HIGHLIGHTS
);
}, 200);

type OnAudienceModeVariantPatchUpdate = {
highlightVariantFields: boolean;
expectedCSLPValues: Record<"variant" | "base", string>;
Expand Down Expand Up @@ -156,6 +167,7 @@ export function updateVariantClasses(): void {
DATA_CSLP_ATTR_SELECTOR
);
updateElementClasses(element, dataCslp || "", observer);
requestDiscussionHighlights();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can debounce it right? I don't want us to spam, postmessages from LP SDK through mutation observer

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's already debounced — requestDiscussionHighlights schedules a single 200ms timer (DISCUSSION_HIGHLIGHTS_DEBOUNCE_MS) and resets it on every observed mutation, so a burst of data-cslp mutations from a CSR re-render coalesces into exactly one postMessage. See lines 14–17 (constant) and 47–57 (debounce wrapper) in this file.

If you'd prefer a longer window (say 300ms or 500ms) for extra safety against very chunky React renders, easy to bump.

}
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,12 @@ export function useVariantFieldsPostMessageEvent({ isSSR }: { isSSR: boolean }):
if (selectedVariant) {
addVariantFieldClass(selectedVariant);
}
// SSR DOM is final; observer never fires, request directly.
visualBuilderPostMessage?.send(
VisualBuilderPostMessageEvents.REQUEST_DISCUSSION_HIGHLIGHTS
);
} else {
// recalculate and apply classes
// CSR: observer in updateVariantClasses requests on settle.
updateVariantClasses();
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import {
updateHighlightedCommentIconPosition,
removeAllHighlightedCommentIcons,
} from "../generateHighlightedComment";

describe("updateHighlightedCommentIconPosition", () => {
let container: HTMLDivElement;

beforeEach(() => {
container = document.createElement("div");
container.className = "visual-builder__container";
document.body.appendChild(container);
});

afterEach(() => {
document.body.removeChild(container);
});

const makeIcon = (fieldPath: string): HTMLDivElement => {
const icon = document.createElement("div");
icon.className = "highlighted-comment collab-icon";
icon.setAttribute("field-path", fieldPath);
icon.style.position = "fixed";
icon.style.top = "100px";
icon.style.left = "200px";
container.appendChild(icon);
return icon;
};

const makeTarget = (cslpValue: string): HTMLDivElement => {
const el = document.createElement("div");
el.setAttribute("data-cslp", cslpValue);
container.appendChild(el);
return el;
};

it("keeps an icon whose target element is still present", () => {
const cslp = "content.entry.en-us.field";
makeTarget(cslp);
makeIcon(cslp);

updateHighlightedCommentIconPosition();

expect(
document.querySelector(`.highlighted-comment[field-path="${cslp}"]`),
).not.toBeNull();
});

it("removes an orphaned icon when its target element is no longer found", () => {
// Stale CSLP with no matching element — simulates the element having
// been mutated to a variant CSLP value.
const staleCslp = "content.entry.en-us.old_field";
makeIcon(staleCslp);

updateHighlightedCommentIconPosition();

expect(
document.querySelector(`.highlighted-comment[field-path="${staleCslp}"]`),
).toBeNull();
});

it("removes only orphaned icons and keeps valid ones", () => {
const validCslp = "content.entry.en-us.valid";
const staleCslp = "content.entry.en-us.stale";

makeTarget(validCslp);
makeIcon(validCslp);
makeIcon(staleCslp);

updateHighlightedCommentIconPosition();

expect(
document.querySelector(`.highlighted-comment[field-path="${validCslp}"]`),
).not.toBeNull();
expect(
document.querySelector(`.highlighted-comment[field-path="${staleCslp}"]`),
).toBeNull();
});

it("does not throw when there are no icons", () => {
expect(() => updateHighlightedCommentIconPosition()).not.toThrow();
});
});

describe("removeAllHighlightedCommentIcons", () => {
it("removes every .highlighted-comment element", () => {
["a", "b", "c"].forEach((cslp) => {
const icon = document.createElement("div");
icon.className = "highlighted-comment collab-icon";
icon.setAttribute("field-path", cslp);
document.body.appendChild(icon);
});

expect(document.querySelectorAll(".highlighted-comment").length).toBe(3);

removeAllHighlightedCommentIcons();

expect(document.querySelectorAll(".highlighted-comment").length).toBe(0);
});
});
3 changes: 3 additions & 0 deletions src/visualBuilder/generators/generateHighlightedComment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,9 @@ export function updateHighlightedCommentIconPosition() {
// Update the position of the icon container
icon.style.top = `${top - highlighCommentOffset}px`; // Adjust based on the target element's top
icon.style.left = `${left - highlighCommentOffset}px`; // Adjust based on the target element's left
} else {
// Target gone — drop the orphan icon.
icon.remove();
}
}
}
Expand Down
1 change: 1 addition & 0 deletions src/visualBuilder/utils/types/postMessage.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,5 @@ export enum VisualBuilderPostMessageEvents {
COLLAB_THREAD_REOPEN = "collab-thread-reopen",
COLLAB_THREAD_HIGHLIGHT = "collab-thread-highlight",
TOGGLE_SCROLL = "toggle-scroll",
REQUEST_DISCUSSION_HIGHLIGHTS = "request-discussion-highlights",
}
Loading