Skip to content
1 change: 1 addition & 0 deletions docs/pages/guide/typeset.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ comark-ui styles a document's plain Markdown: headings, paragraphs, links, lists
- **On by default.** Every `comark-ui` renderer writes them.
- **Scoped to the document.** A `<style>` inside the document uses `@scope`, so it styles only the element the document renders into.
- **In the server's HTML.** Vue, React, and Svelte render the `<style>` with the document, so a server-rendered page arrives styled and doesn't shift.
- **Images that fit the screen.** A Markdown image is at most 70% of the window's height (40rem at most), so a tall one never fills the screen as you scroll, and a click zooms it whole. A captioned one is centered over its caption. Blocks' own images, such as a screenshot's, keep their size.
- **With a grain.** A faint noise covers the background. `--comark-grain: none` turns it off.
- **Under the blocks.** The rules sit in a `typeset` layer inside the `comark` layer, so block rules win over them, and your plain rules win over both.

Expand Down
30 changes: 30 additions & 0 deletions e2e/annotate.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,36 @@ Extra filters collapse into **+2 filters**.
await expect(page.locator(`.cz-item ${plain}`).first()).toHaveCSS("color", "rgb(1, 2, 3)");
});

test("on a narrow screen, notes above a screenshot off to one side of their points stack under it", async ({
page,
}) => {
await page.setViewportSize({ width: 400, height: 700 });
await open(
page,
`::screenshot{src="/dashboard.png" alt="Dashboard" viewport="1440x860"}
:::annotation{x=24 y=15 w=50 h=70 mark="none" side="top" at=0 to="24,30"}
Reads away from its point.
:::

:::annotation{x=60 y=15 w=20 h=20 mark="none" side="top" at=95 to="60,30"}
Reads the other way.
:::
::`,
);
await page.addStyleTag({ content: "main{width:auto;margin:1rem}" });
const stage = (await page.locator("main .ca-stage").boundingBox())!;
const notes = page.locator("main .ca-callout");
await expect(notes).toHaveCount(2);
expect(
await page.locator("main .ca-callout-west, main .ca-callout-east").count(),
).toBeGreaterThan(0);
for (const note of await notes.all()) {
const box = (await note.boundingBox())!;
expect(box.x).toBeGreaterThanOrEqual(stage.x - 1);
expect(box.x + box.width).toBeLessThanOrEqual(stage.x + stage.width + 1);
}
});

test("a box frames its area 6px out on a host that sets every element's box-sizing", async ({
page,
}) => {
Expand Down
4 changes: 3 additions & 1 deletion e2e/motion-zoom.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,9 @@ test("a zoomed picture travels from its place in the page to the dialog, and bac
await expect(page.locator(".cz-stage[data-flying]")).toHaveCount(0);
const zoomed = await box(page, ".cz-item > img");
// The frame keeps its own scale; the travel only adds to it.
expect(await frame.evaluate((node: HTMLElement) => node.style.transform)).toMatch(/^scale\(/);
expect(await frame.evaluate((node: HTMLElement) => node.style.transform)).toMatch(
/^translate\([^)]*\) scale\(/,
);
expect(zoomed.width).toBeGreaterThan(picture.width * 1.3);

const opening = (await frames(page)).filter((sample) => sample.box);
Expand Down
137 changes: 137 additions & 0 deletions e2e/typeset.e2e.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,157 @@
import { createHtmlRenderer } from "@comark/html";
import { expect, test } from "@playwright/test";
import comarkUi from "../packages/ui/src/html.ts";
import { fixture } from "./helpers.ts";

const render = createHtmlRenderer(
comarkUi({
chips: { download: false },
badge: { download: false },
icon: { fetch: false },
diagrams: { draw: false },
figure: { unwrap: true },
}),
);

const portrait =
'<svg xmlns="http://www.w3.org/2000/svg" width="400" height="1000"><rect width="400" height="1000"/></svg>';

test("the first block adds no space above, with the typeset styles before it", async ({ page }) => {
const html = await render("## Plan\n\nThe first step.");
expect(html.trimStart()).toMatch(/^<style data-comark-typeset>/);
await page.setContent(`<!doctype html><main style="width:40rem">${html}</main>`);
await expect(page.getByRole("heading", { name: "Plan" })).toHaveCSS("margin-top", "0px");
await expect(page.getByText("The first step.")).not.toHaveCSS("margin-top", "0px");
});

for (const typedAttr of [true, false]) {
test(`a tall image fits over its caption without capping a screenshot (${typedAttr ? "native CSS" : "without typed attr"})`, async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 800 });
const paintingReady = Promise.withResolvers<void>();
await page.route("**/painting.svg", async (route) => {
await paintingReady.promise;
await route.fulfill({ contentType: "image/svg+xml", body: portrait });
});
await page.route("**/shot.svg", (route) =>
route.fulfill({ contentType: "image/svg+xml", body: portrait }),
);
await page.route("**/landscape.svg", (route) =>
route.fulfill({
contentType: "image/svg+xml",
body: '<svg xmlns="http://www.w3.org/2000/svg" width="400" height="250"></svg>',
}),
);
let html = await render(
'![A tall painting](/painting.svg "A tall painting"){width="400" height="1000"}\n\n' +
'![A half-width painting](/landscape.svg){width="50%" height="250"}\n\n' +
'::screenshot{src="/shot.svg" alt="A tall screenshot"}\n::',
);
if (typedAttr) {
const dimensions = ' style="--_ty-image-w:400;--_ty-image-h:1000"';
expect(html).toContain(dimensions);
html = html.replace(dimensions, "");
} else {
const query = "@supports(opacity:attr(width type(<number>)))";
expect(html).toContain(query);
html = html.replace(query, "@supports (width: unsupported)");
}
const painting = page.locator('figure > img[alt="A tall painting"]');
await Promise.all([
fixture(page, html, "main{width:40rem;margin:auto}"),
(async () => {
try {
await expect(painting).toHaveAttribute("width", "400");
await expect(painting).toHaveAttribute("height", "1000");
await expect(painting).toHaveJSProperty("naturalWidth", 0);
await expect(painting).toHaveCSS("width", "224px");
await expect(painting).toHaveCSS("height", "560px");
} finally {
paintingReady.resolve();
}
})(),
]);
await expect(painting).toHaveJSProperty("naturalWidth", 400);
const box = (await painting.boundingBox())!;
const column = (await page.locator("main").boundingBox())!;
// 70% of the 800px window, at the picture's own 2:5.
expect(box.height).toBeCloseTo(560, 0);
expect(box.width).toBeCloseTo(224, 0);
expect(box.x - column.x).toBeCloseTo((column.width - box.width) / 2, 0);
const halfWidth = page.getByRole("img", { name: "A half-width painting" });
await expect(halfWidth).toHaveAttribute("width", "50%");
await expect(halfWidth).toHaveJSProperty("naturalWidth", 400);
await expect(halfWidth).toHaveCSS("width", "320px");
// The screenshot's marks sit on its image, so the image keeps the column's width and its full height.
const shot = page.locator('img[alt="A tall screenshot"]');
await expect(shot).toHaveJSProperty("complete", true);
expect((await shot.boundingBox())!.height).toBeCloseTo(column.width * 2.5, 0);
});
}

test("ordinary Markdown images fit inside links, inline markup, tables, and the comments wrapper", async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 800 });
await page.route("**/portrait.svg", (route) =>
route.fulfill({ contentType: "image/svg+xml", body: portrait }),
);
const html = await render(`> [![Quote](/portrait.svg)](/full)

Portrait
: [![Definition](/portrait.svg)](/full)

**![Emphasis](/portrait.svg)**

| Portrait |
| --- |
| ![Cell](/portrait.svg) |

![Unwrapped](/portrait.svg)

:comment[Margin comment]{note="A note"}`);
await fixture(page, html, "main{width:40rem;margin:auto}");
for (const selector of [
'blockquote > a > img[alt="Quote"]',
'dd > a > img[alt="Definition"]',
'strong > img[alt="Emphasis"]',
'td > img[alt="Cell"]',
'.cr > img[alt="Unwrapped"]',
]) {
const image = page.locator(selector);
await expect(image).toHaveJSProperty("naturalWidth", 400);
await expect(image).toHaveCSS("max-height", "560px");
expect((await image.boundingBox())!.height).toBeLessThanOrEqual(560);
}
});

test("a native Markdown table sizes its columns from the fitted image widths", async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 800 });
await page.route("**/tall.svg", (route) =>
route.fulfill({
contentType: "image/svg+xml",
body: '<svg xmlns="http://www.w3.org/2000/svg" width="960" height="3840"></svg>',
}),
);
const table = (width: number, height: number) => {
const dimensions = `{width="${width}" height="${height}"}`;
return `| Before | After | Notes |
| --- | --- | --- |
| ![Before](/tall.svg)${dimensions} | ![After](/tall.svg)${dimensions} | The painting keeps its proportions while the notes next to it stay readable in a narrow column. |`;
};
await fixture(
page,
await render(`${table(960, 3840)}\n\n${table(140, 560)}`),
"main{width:40rem;margin:auto}",
);
const [fitted, control] = await page.locator("table").all();
for (const name of ["Before", "After"]) {
const image = (await fitted!.getByRole("img", { name }).boundingBox())!;
const controlImage = (await control!.getByRole("img", { name }).boundingBox())!;
expect(image.width).toBeCloseTo(controlImage.width, 0);
}
const notes = (await fitted!.locator("tbody td").last().boundingBox())!;
const controlNotes = (await control!.locator("tbody td").last().boundingBox())!;
expect(notes.width).toBeCloseTo(controlNotes.width, 0);
});
118 changes: 116 additions & 2 deletions e2e/zoom.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,18 @@ import { createHtmlRenderer } from "@comark/html";
import { expect, type Page, test } from "@playwright/test";
import annotate, { components as annotateComponents } from "../packages/annotate/src/html.ts";
import carousel, { components as carouselComponents } from "../packages/carousel/src/html.ts";
import details, { components as detailsComponents } from "../packages/details/src/html.ts";
import zoom, { components as zoomComponents } from "../packages/zoom/src/html.ts";
import { fixture } from "./helpers.ts";

const render = createHtmlRenderer({
plugins: [annotate(), carousel(), zoom()],
components: { ...annotateComponents, ...carouselComponents, ...zoomComponents },
plugins: [annotate(), carousel(), details(), zoom()],
components: {
...annotateComponents,
...carouselComponents,
...detailsComponents,
...zoomComponents,
},
});

const image = "![Office correlations dashboard](/dashboard.png)";
Expand Down Expand Up @@ -422,6 +428,114 @@ test("an item taller than the stage fills its width and scrolls instead of shrin
await expect(page.locator(".cz-dialog")).toHaveCount(0);
});

test("an item a little taller than the stage shrinks a little and shows whole", async ({
page,
}) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await page.setViewportSize({ width: 1000, height: 800 });
await page.route("**/portrait.svg", (route) =>
route.fulfill({
contentType: "image/svg+xml",
body: '<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="1440"><rect width="1200" height="1440"/></svg>',
}),
);
await fixture(page, await render("![Portrait](/portrait.svg)"));
await page.locator("main img").click();
const stage = page.locator(".cz-stage");
await expect(stage).not.toHaveAttribute("data-scroll");
const copy = await rect(page, ".cz-item");
const box = await rect(page, ".cz-stage");
expect(copy.top).toBeGreaterThanOrEqual(box.top);
expect(copy.bottom).toBeLessThanOrEqual(box.bottom);
expect(copy.width).toBeGreaterThan(600 * 0.85);
});

test("notes that sit outside a screenshot's box zoom onto the stage with it, centered", async ({
page,
}) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await page.setViewportSize({ width: 900, height: 700 });
await fixture(
page,
await render(`::screenshot{src="/dashboard.png" alt="Dashboard" viewport="1440x860"}
:::annotation{x=24 y=15 w=50 h=70 mark="none" side="top" at=0 to="24,30"}
The whole chart fits in the window, and this note runs far past its left edge.
:::
::`),
);
const stage = page.locator(".ca-stage");
const note = page.locator("main .ca-callout");
expect((await note.boundingBox())!.x).toBeLessThan((await stage.boundingBox())!.x);
await stage.click({ position: { x: 200, y: 200 } });
const box = await rect(page, ".cz-stage");
const shown = await rect(page, ".cz-item .ca-callout");
const copy = await rect(page, ".cz-item .ca-stage");
expect(shown.left).toBeGreaterThanOrEqual(box.left);
// The note and the screenshot together sit in the middle of the stage.
expect((shown.left + copy.right) / 2).toBeCloseTo((box.left + box.right) / 2, -1);
});

test("closed details do not add blank scrolling to a zoomed block", async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await page.setViewportSize({ width: 1000, height: 800 });
const paragraphs = Array.from({ length: 55 }, (_, i) => `Hidden paragraph ${i + 1}.`);
await fixture(
page,
await render(`::zoom{title="Release notes"}
Visible introduction.

:::details{summary="More details"}
${paragraphs.join("\n\n")}
:::
::`),
);
await page.getByText("Visible introduction.").click();
const stage = page.locator(".cz-stage");
await expect(stage.locator("summary")).toHaveText("More details");
await expect(stage).not.toHaveAttribute("data-scroll");
});

test("resizing while scrolled into a note above a screenshot keeps the reading position", async ({
page,
}) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await page.setViewportSize({ width: 1000, height: 800 });
const paragraphs = Array(8).fill(
"The note above the screenshot is long enough to keep reading while the viewport changes.",
);
await fixture(
page,
await render(`::screenshot{src="/dashboard.png" alt="Dashboard" viewport="1440x860"}
:::annotation{x=24 y=15 w=50 h=70 mark="none" side="top" at=50 to="24,30"}
${paragraphs.join("\n\n")}
:::
::`),
);
await page.evaluate(() => document.fonts.ready);
await page.locator("main .ca-stage").click({ position: { x: 200, y: 200 } });
const stage = page.locator(".cz-stage");
const item = stage.locator(".cz-item");
const margin = () => item.evaluate((node: HTMLElement) => node.style.marginBlockStart);
await expect(stage).toHaveAttribute("data-scroll");
await stage.evaluate((node) => (node.scrollTop = 150));
const noteTop = async () =>
(await rect(page, ".cz-item .ca-callout")).top - (await rect(page, ".cz-stage")).top;
const before = await noteTop();
expect(before).toBeLessThan(-100);
expect((await rect(page, ".cz-item")).top).toBeGreaterThan((await rect(page, ".cz-stage")).top);

const oldMargin = await margin();
await page.setViewportSize({ width: 1000, height: 820 });
await expect.poll(margin).not.toBe(oldMargin);
await expect.poll(async () => Math.abs((await noteTop()) - before)).toBeLessThan(2);

await stage.evaluate((node) => (node.scrollTop = 0));
const resizedMargin = await margin();
await page.setViewportSize({ width: 1000, height: 840 });
await expect.poll(margin).not.toBe(resizedMargin);
expect(await stage.evaluate((node) => node.scrollTop)).toBe(0);
});

test("resizing a scrolled tall item preserves its content position and clears scrolling when it fits", async ({
page,
}) => {
Expand Down
4 changes: 2 additions & 2 deletions packages/annotate/src/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,8 @@ export const css = `@layer comark{${[
".ca-callout.ca-callout-west{text-align:right;transform:translateX(-100%)}",
".ca-callout>div>:first-child{margin-top:0}",
".ca-callout>div>:last-child{margin-bottom:0}",
// Too narrow for side notes: stack them under the image, drop the arrows, and letter each note and its target instead. Notes on both sides need more room than notes on one.
"@container (max-width:28rem){.ca-stage{padding:0!important}.ca-arrow{display:none}.ca-callout{position:static;display:flex;gap:.6rem;align-items:baseline;width:auto;max-width:none;margin-top:.5rem;padding-left:0;text-align:left;transform:none}.ca-letter{display:inline-grid}.ca-none{outline:1.5px dashed var(--ca-color);outline-offset:3px;border-radius:calc(var(--_comark-radius) - 7px)}}",
// Too narrow for side notes: stack them under the image, drop the arrows, and letter each note and its target instead. Notes on both sides need more room than notes on one. The stacked note outranks .ca-callout-west, whose shift would push it off the image.
"@container (max-width:28rem){.ca-stage{padding:0!important}.ca-arrow{display:none}.ca-stage .ca-callout{position:static;display:flex;gap:.6rem;align-items:baseline;width:auto;max-width:none;margin-top:.5rem;padding-left:0;text-align:left;transform:none}.ca-letter{display:inline-grid}.ca-none{outline:1.5px dashed var(--ca-color);outline-offset:3px;border-radius:calc(var(--_comark-radius) - 7px)}}",
"@container (max-width:40rem){.ca-left.ca-right .ca-stage{padding:0!important}.ca-left.ca-right .ca-arrow{display:none}.ca-left.ca-right .ca-callout{position:static;display:flex;gap:.6rem;align-items:baseline;width:auto;max-width:none;margin-top:.5rem;padding-left:0;text-align:left;transform:none}.ca-left.ca-right .ca-letter{display:inline-grid}.ca-left.ca-right .ca-none{outline:1.5px dashed var(--ca-color);outline-offset:3px;border-radius:calc(var(--_comark-radius) - 7px)}}",
// Host pages often center a figcaption, which suits a one-line caption but not a list of notes.
".ca figcaption{margin-top:.75rem;text-align:start}",
Expand Down
17 changes: 17 additions & 0 deletions packages/ui/src/typeset-css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ export const STACK_ROWS = 3;

// Comments add a document wrapper; nested component/list tables remain outside this scope.
const documentRoot = ":is(:scope, :scope > .cr)";
const imageParent = `:is(${documentRoot}, p, li, blockquote, dt, dd, figure, td, th)`;
const inline = ":is(a, b, del, em, i, mark, s, span, strong, sub, sup)";
const table = `${documentRoot} > div:is([data-width], [data-fit])`;
// A grid of the table's rows, each a subgrid, so its columns line up from row to row.
const grid = (selector: string) => `
Expand Down Expand Up @@ -243,6 +245,21 @@ const rules = `
&:where(img, video) { border-radius: var(--_ty-radius); max-width: 100%; height: auto; margin-block: var(--_ty-flow) 0; }
/* An image in a line of text sits on the text; a block's top margin would push it below. */
&:where(:is(p, li, td, th, a) img) { margin-block-start: 0; }
/* Cap prose images, not the images inside a block's frame. */
&:where(${imageParent} > img, ${imageParent} > ${inline} img) {
--_ty-image-height: min(70svh, 40rem);
max-height: var(--_ty-image-height); object-fit: contain;
&:where([width][height]) {
--_ty-image-width: min(calc(var(--_ty-image-w) * 1px), calc(var(--_ty-image-height) * var(--_ty-image-w) / var(--_ty-image-h)));
width: var(--_ty-image-width, revert-layer);
@supports (opacity: attr(width type(<number>))) {
--_ty-image-w: attr(width type(<number>));
--_ty-image-h: attr(height type(<number>));
}
}
}
/* A captioned image is centered over its caption once it's narrower than the column. */
&:where(figure > img, figure > a > img) { display: block; margin-inline: auto; }
&:where(figure) { margin-block: var(--_ty-flow) 0; margin-inline: 0; }
&:where(figcaption, caption) {
color: var(--_ty-muted); font-size: 0.875em; text-align: center; margin-block-start: calc(0.75em / 0.875);
Expand Down
Loading
Loading