Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
40 lines
1.9 KiB
TypeScript
40 lines
1.9 KiB
TypeScript
// @vitest-environment jsdom
|
|
import { describe, it, expect, vi, afterEach } from "vitest";
|
|
import { frameDocument } from "./frameHtml";
|
|
|
|
// add-page-anchor-links: the injected frame script turns clicks on #name links into requests to the page.
|
|
function runFrameScript(body: string) {
|
|
document.body.innerHTML = body;
|
|
const code = frameDocument("").match(/<script>([\s\S]*)<\/script>/)![1];
|
|
new Function(code)();
|
|
}
|
|
|
|
afterEach(() => vi.restoreAllMocks());
|
|
|
|
describe("frame script: same-page links", () => {
|
|
it("asks the page to scroll, with the in-frame target's offset when the frame has it, and never navigates the frame", () => {
|
|
const post = vi.spyOn(window.parent, "postMessage").mockImplementation(() => {});
|
|
runFrameScript('<div id="top">Top</div><a href="#top">Back</a><a href="#signup"><span>Join</span></a>');
|
|
const back = new MouseEvent("click", { bubbles: true, cancelable: true });
|
|
document.querySelector('a[href="#top"]')!.dispatchEvent(back);
|
|
expect(back.defaultPrevented).toBe(true);
|
|
expect(post).toHaveBeenCalledWith({ type: "colite-frame-anchor", name: "top", y: 0 }, "*");
|
|
const join = new MouseEvent("click", { bubbles: true, cancelable: true });
|
|
document.querySelector("span")!.dispatchEvent(join);
|
|
expect(join.defaultPrevented).toBe(true);
|
|
expect(post).toHaveBeenCalledWith({ type: "colite-frame-anchor", name: "signup", y: null }, "*");
|
|
});
|
|
|
|
it("leaves other links alone", () => {
|
|
const post = vi.spyOn(window.parent, "postMessage").mockImplementation(() => {});
|
|
runFrameScript('<a href="https://wa.me/1">WA</a><a href="#Bad Name">Bad</a>');
|
|
post.mockClear();
|
|
for (const a of document.querySelectorAll("a")) {
|
|
const click = new MouseEvent("click", { bubbles: true, cancelable: true });
|
|
a.dispatchEvent(click);
|
|
expect(click.defaultPrevented).toBe(false);
|
|
}
|
|
expect(post.mock.calls.filter(([d]) => (d as { type: string }).type === "colite-frame-anchor")).toHaveLength(0);
|
|
});
|
|
});
|