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
10 changes: 7 additions & 3 deletions packages/annotate/test/annotate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import { join } from "node:path";
import { promisify } from "node:util";
import { renderHtmlFromDocument } from "@comark/html";
import { parseMarkdown } from "comark";
import { scripts as carouselScripts } from "comark-carousel/html";
import security from "comark/plugins/security";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import annotate, { components } from "../src/html.ts";
import annotate, { components, scripts } from "../src/html.ts";
import xref from "../../xref/src/index.ts";

async function run(markdown: string, options?: Parameters<typeof annotate>[0]) {
Expand All @@ -21,6 +22,9 @@ async function run(markdown: string, options?: Parameters<typeof annotate>[0]) {

// The stylesheet the renderer inlines, so the tests read the CSS a reader's browser gets.
const styles = (html: string) => /<style>([^]*?)<\/style>/.exec(html)?.[1] ?? "";
// How many times the page carries comark-annotate's own script, apart from the carousel's and zoom's it lists too.
const ownScript = scripts.find((script) => !carouselScripts.includes(script));
const ownScripts = (html: string) => html.split(`<script>${ownScript}</script>`).length - 1;

const compare = `
::compare
Expand Down Expand Up @@ -109,7 +113,7 @@ describe("comark-annotate", () => {
const slider = compare.replace("::compare", '::compare{mode="slider"}');
const { html } = await run(`${slider}\n${slider.replaceAll(".png", "-2.png")}`);
expect(html.match(/<div class="ca-swipe"/g)).toHaveLength(2);
expect(html.match(/<script>\(function start\(\) \{/g)).toHaveLength(1);
expect(ownScripts(html)).toBe(1);
});

it("inlines the styles once per render and keeps ids stable and unique", async () => {
Expand Down Expand Up @@ -306,7 +310,7 @@ describe("comark-annotate", () => {
expect(html).toMatch(
/<div class="ca-frame"><img src="a.png"[^>]*><span class="ca-mark[^]*?<\/span><label class="ca-hide"[^]*?<\/label><button type="button" class="ca-copy"[^]*?<\/button><span class="ca-copy-status" role="status"><\/span><\/div>/,
);
expect(html.match(/<script>\(function start\(\) \{/g)).toHaveLength(1);
expect(ownScripts(html)).toBe(1);
expect(styles(html)).toContain(".ca-copy{display:none}");
expect(styles(html)).toContain("[data-annotate-copy] .ca-copy{");
expect(styles(html)).toContain(
Expand Down
52 changes: 33 additions & 19 deletions packages/annotate/test/tour.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { createCanvas, loadImage } from "@napi-rs/canvas";
import { describe, expect, it, vi } from "vite-plus/test";
import { describe, expect, it } from "vite-plus/test";
import { plan, toScreen, cameraAt, type TourNote } from "../src/tour/plan.ts";
import * as marks from "../src/marks.ts";
import { tour } from "../src/tour.ts";

// A light page with a dark bar where the change is, as a data URI.
Expand Down Expand Up @@ -70,23 +69,38 @@ describe("tour", () => {
expect(video.duration).toBeGreaterThan(video.shots.at(-1)!.end);
});

it.each([
['x=10 y=20 w=70 h=5 side="top"', "top"],
['x=10 y=20 w=70 h=5 side="left" at=80', "bottom"],
])("preserves bracket orientation: %s", async (attributes, edge) => {
const source = page({ x: 90, y: 72 });
const annotation = `::::annotation{${attributes} mark="bracket"}\nBracket\n::::`;
const screenshot = `:::screenshot{src="${source}" alt="Page" viewport="900x360"}\n${annotation}\n:::`;
const video = await tour(`::compare\n${screenshot}\n${screenshot}\n::`);
const draw = vi.spyOn(marks, "draw");
try {
for (const shot of video.shots) await video.frame(shot.end - 0.1);
await video.frame(video.duration - 1);
expect(draw.mock.calls.length).toBeGreaterThanOrEqual(3);
expect(draw.mock.calls.every((call) => call[4] === edge)).toBe(true);
} finally {
draw.mockRestore();
}
it("draws a bracket across the edge that faces its note, as the page does", async () => {
const canvas = createCanvas(900, 360);
const context = canvas.getContext("2d");
context.fillStyle = "#fff";
context.fillRect(0, 0, 900, 360);
const source = canvas.toDataURL();
// The rows of each shot's last frame that the bracket's spine crosses: blue for more than half the width.
const spines = async (attributes: string) => {
const annotation = `::::annotation{x=10 y=20 w=70 h=5 ${attributes} mark="bracket" color="#0000ff"}\nBracket\n::::`;
const screenshot = `:::screenshot{src="${source}" alt="Page" viewport="900x360"}\n${annotation}\n:::`;
const video = await tour(`::compare\n${screenshot}\n${screenshot}\n::`);
const rows: number[] = [];
for (const shot of video.shots) {
const frame = await loadImage(await video.frame(shot.end - 0.1));
const canvas = createCanvas(frame.width, frame.height);
const context = canvas.getContext("2d");
context.drawImage(frame, 0, 0);
const { data, width, height } = context.getImageData(0, 0, frame.width, frame.height);
for (let y = 0; y < height; y++) {
let blue = 0;
for (let i = y * width * 4; i < (y + 1) * width * 4; i += 4)
if (data[i + 2]! - Math.max(data[i]!, data[i + 1]!) > 60) blue++;
if (blue > width / 2) rows.push(y);
}
}
return rows;
};
const top = await spines('side="top"');
const bottom = await spines('side="left" at=80');
expect(top).not.toEqual([]);
expect(bottom).not.toEqual([]);
expect(Math.max(...top)).toBeLessThan(Math.min(...bottom));
Comment thread
vite-hub[bot] marked this conversation as resolved.
Resolved
});

it.each(["before", "after"])("shows both states for %s-only changes", async (side) => {
Expand Down
11 changes: 9 additions & 2 deletions packages/links/test/frameworks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,20 @@ describe("comark-links renderers", () => {
expect(normalize(renderers.react(value))).toContain(expected);
});

it("ships Svelte components that compile", async () => {
it("ships Svelte components that compile, and every component they import", async () => {
const folder = new URL("../src/svelte/", import.meta.url);
const files = (await readdir(folder)).filter((file) => file.endsWith(".svelte"));
expect(files).toHaveLength(8);
for (const file of files) {
const source = await readFile(new URL(file, folder), "utf8");
expect(() => compile(source, { filename: file, generate: "server" })).not.toThrow();
}
const imported = new Set<string>();
for (const file of [...files, "index.js"])
for (const [, name = ""] of (await readFile(new URL(file, folder), "utf8")).matchAll(
/from "\.\/(\w+\.svelte)"/g,
Comment thread
vite-hub[bot] marked this conversation as resolved.
Resolved
))
imported.add(name);
expect(imported.size).toBeGreaterThan(0);
expect([...imported].filter((name) => !files.includes(name))).toEqual([]);
});
});
39 changes: 14 additions & 25 deletions packages/lint/test/lint.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -493,37 +493,26 @@ describe("lint()", () => {
},
};
const found = await lint("::compare\n", { plugins: [broken] });
// Each crash names its rule, then the error it threw.
const crashed = (rule: string) => [
rule,
expect.stringMatching(new RegExp(`^lint-comark crashed while checking \`${rule}\`: .+`)),
];
expect(found.map(({ rule, message }) => [rule, message])).toEqual([
[
"comark/broken-anchor",
"lint-comark crashed while checking `comark/broken-anchor`: Cannot read properties of null (reading 'id').",
],
[
"comark/unsafe-url",
"lint-comark crashed while checking `comark/unsafe-url`: Cannot read properties of null (reading 'href').",
],
[
"comark/duplicate-id",
"lint-comark crashed while checking `comark/duplicate-id`: Cannot read properties of null (reading 'id').",
],
[
"comark/missing-alt",
"lint-comark crashed while checking `comark/missing-alt`: Cannot read properties of null (reading 'src').",
],
[
"comark/empty-link",
"lint-comark crashed while checking `comark/empty-link`: Cannot read properties of null (reading 'href').",
],
[
"comark/broken-link",
"lint-comark crashed while checking `comark/broken-link`: Cannot read properties of null (reading 'href').",
],
crashed("comark/broken-anchor"),
crashed("comark/unsafe-url"),
crashed("comark/duplicate-id"),
crashed("comark/missing-alt"),
crashed("comark/empty-link"),
crashed("comark/broken-link"),
["comark/unclosed-block", "`::compare` opened on line 1 is never closed."],
]);
for (const diagnostic of found.filter(({ message }) =>
message.startsWith("lint-comark crashed"),
))
)) {
expect(diagnostic.cause).toBeInstanceOf(TypeError);
expect(diagnostic.message).toContain((diagnostic.cause as TypeError).message);
}
});
});

Expand Down
7 changes: 0 additions & 7 deletions packages/lint/test/mermaid.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { readFile } from "node:fs/promises";
import { createHtmlRenderer } from "@comark/html";
import html from "comark-ui/html";
import { describe, expect, it } from "vite-plus/test";
Expand Down Expand Up @@ -50,12 +49,6 @@ describe("Mermaid limit diagnostics", () => {
}),
}),
]);
const page = await readFile(
new URL(`../../../docs/pages/doctor/${path}.md`, import.meta.url),
"utf8",
);
expect(page).toContain(Object.keys(options)[0]);
expect(page).toContain("comark-ui/html");
});
}
});
11 changes: 9 additions & 2 deletions packages/mark/test/frameworks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,20 @@ describe("comark-mark renderers", () => {
expect(html).toContain("@layer comark{");
});

it("ships Svelte components that compile", async () => {
it("ships Svelte components that compile, and every component they import", async () => {
const folder = new URL("../src/svelte/", import.meta.url);
const files = (await readdir(folder)).filter((file) => file.endsWith(".svelte"));
expect(files).toHaveLength(3);
for (const file of files) {
const source = await readFile(new URL(file, folder), "utf8");
expect(() => compile(source, { filename: file, generate: "server" })).not.toThrow();
}
const imported = new Set<string>();
for (const file of [...files, "index.js"])
for (const [, name = ""] of (await readFile(new URL(file, folder), "utf8")).matchAll(
/from "\.\/(\w+\.svelte)"/g,
))
imported.add(name);
expect(imported.size).toBeGreaterThan(0);
expect([...imported].filter((name) => !files.includes(name))).toEqual([]);
});
});
3 changes: 2 additions & 1 deletion packages/outline/test/toc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@ describe("comark-outline", () => {
expect(html.trimEnd().endsWith(`<script>${railScript}</script>`)).toBe(true);
expect(html.split(railScript)).toHaveLength(2);
expect(html.match(/<style data-comark-outline>/g)).toHaveLength(1);
expect(railScript).toMatch(/^\(function start\(\)/);
// A function that calls itself, so the script runs where the page inlines it.
expect(railScript).toMatch(/^\(function\b[^(]*\(\) \{[\s\S]*\}\)\(\)$/);
});

it("needs the option and two headings to list", async () => {
Expand Down
6 changes: 4 additions & 2 deletions packages/properties/test/properties.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createHtmlRenderer } from "@comark/html";
import { parseMarkdown } from "comark";
import { describeTime } from "comark-time/client";
import { describe, expect, it } from "vite-plus/test";
import properties, { components, scripts } from "../src/html.ts";

Expand Down Expand Up @@ -92,8 +93,9 @@ describe("comark-properties", () => {
expect(html.match(/<style data-comark-time>/g)).toHaveLength(1);
expect(html.split(`<script>${escape}</script>`)).toHaveLength(2);
expect(html.split(`</dl><script>${relativize}</script>`)).toHaveLength(2);
expect(relativize).toMatch(/^\(function relativize\(/);
expect(relativize).toContain("function describeTime(");
expect(relativize).toMatch(/^\(function\b[^(]*\(/);
// An inlined script can't import, so comark-time's describeTime goes in whole.
expect(relativize.replaceAll("\u2028", "\n")).toContain(describeTime.toString());
expect(await renderer("---\nstatus: Draft\n---\n")).not.toContain("<script>");

const fixed = await render(review, { locale: "de-DE" });
Expand Down
3 changes: 2 additions & 1 deletion packages/ui/test/editor-upload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,8 @@ describe("chooseFiles", () => {
multiple: true,
accept: "image/*,video/*,audio/*",
});
await Promise.resolve();
// WebKit needs the input attached for as long as the picker is open, not just for a microtask.
await new Promise((resolve) => setTimeout(resolve, 20));
expect(input.isConnected).toBe(true);
input.dispatchEvent(new Event("change"));
expect(input.isConnected).toBe(false);
Expand Down
2 changes: 1 addition & 1 deletion packages/ui/test/ui.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ describe("comark-ui", () => {
expect(out.split(`<script>${mermaidScript}</script>`)).toHaveLength(2);
expect(out.match(/<style data-comark-zoom>/g)).toHaveLength(1);
expect(await renderHtml(markdown)).toContain(`<script>${mermaidScript}</script>`);
expect(mermaidScript).toMatch(/^\(function start\(\) \{[\s\S]*\}\)\(\)$/);
expect(mermaidScript).toMatch(/^\(function\b[^(]*\(\) \{[\s\S]*\}\)\(\)$/);
expect(mermaidScript).not.toContain("</");

const still = await renderHtml(markdown, { zoom: false });
Expand Down
Loading