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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ How most packages work, so the bullets below don't repeat it:
- Its output is plain elements, so it has no renderers and ships no styles.
- Pandoc's `@fig-x` isn't read, since `@name` is a mention in comark-chips and comark-github.
- `packages/zoom` is `comark-zoom`.
- `src/index.ts` is the parse plugin. It marks content images and adds one `zoom-runtime` node to a document with anything to zoom. It leaves the images inside `::zoom` alone, and inside carousel's and annotate's blocks when `state.options.plugins` registers that plugin, so an app's own `::carousel` still zooms its images. Unless `size` is `false`, it gives every image without both sides its `width` and `height` from `measure()`, so the page keeps the image's room before it loads.
- `src/index.ts` is the parse plugin. It marks content images and adds one `zoom-runtime` node to a document with anything to zoom. It leaves the images inside `::zoom` alone, and inside carousel's and annotate's blocks when `state.options.plugins` registers that plugin, so an app's own `::carousel` still zooms its images. An image in a table cell is a thumbnail unless `thumbnails` is `false`, whatever `images` says: it gets `data-zoom-thumb`, `loading="lazy"`, and its ratio as `--cz-ratio`, which the styles fit into `--comark-thumb-height` by `--comark-thumb-width`. An image's `link` becomes `data-zoom-href`, which the zoomed view shows as a link in its header. Unless `size` is `false`, it gives every image without both sides its `width` and `height` from `measure()`, so the page keeps the image's room before it loads.
- `src/size.ts` is `comark-zoom/size`. `measure()` reads a picture's or a video's size from the first 64 KB of a URL (a range request) or from a data URI, cached per URL. `sizeOf()` reads it from bytes (PNG, JPEG, GIF, WebP, SVG, AVIF, MP4, MOV, WebM), turned by EXIF orientation or the track's matrix. A relative path, a format it doesn't know, or a file that doesn't answer within 5 seconds gets nothing.
- comark-media and comark-annotate bundle `size` the way they bundle the theme, so every block that loads a picture or a video keeps its room.
- `src/script.ts` is the browser script. `script()` is self-contained because the HTML renderer inlines its source. `src/client.ts` exports `start()`, which runs it with the bundled styles. The Vue, React, and Svelte components call it on mount and stop it on unmount.
Expand Down
8 changes: 7 additions & 1 deletion e2e/typeset.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ Portrait

| Portrait |
| --- |
| ![Cell](/portrait.svg) |
| ![Cell](/portrait.svg){zoom=false} |
| ![Thumbnail](/portrait.svg) |

![Unwrapped](/portrait.svg)

Expand All @@ -124,6 +125,11 @@ Portrait
await expect(image).toHaveCSS("max-height", "560px");
expect((await image.boundingBox())!.height).toBeLessThanOrEqual(560);
}
// A cell's image is comark-zoom's thumbnail unless it opts out, and the typeset's cap leaves it alone.
expect((await page.locator('td > img[alt="Thumbnail"]').boundingBox())!.height).toBeCloseTo(
64,
0,
);
});

test("a native Markdown table sizes its columns from the fitted image widths", async ({ page }) => {
Expand Down
129 changes: 129 additions & 0 deletions e2e/zoom.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -800,3 +800,132 @@ test("on a phone, both ends of a wide thumbnail strip are reachable", async ({ p
await thumbs.last().click();
await expect(page.locator(".cz-title")).toHaveText("Item 7");
});

const glossary = `| Term | Where it shows |
| --- | --- |
${Array.from(
{ length: 60 },
(_, row) =>
`| Term ${row + 1} | ![Dashboard ${row + 1}](/dashboard.png?row=${row}){width=1440 height=860 link="https://example.com/page/${row + 1}"} |`,
).join("\n")}
| Both | ![Before](/before.png) ![After](/after.png) |`;

test("an image in a table cell is a thumbnail that keeps its room, loads lazily, and zooms large", async ({
page,
}) => {
const requested: string[] = [];
page.on("request", (request) => {
const row = new URL(request.url()).searchParams.get("row");
if (row) requested.push(row);
});
await page.setViewportSize({ width: 1000, height: 400 });
// The room is checked before any file arrives.
await page.route("**/dashboard.png?row=*", async (route) => {
await new Promise((resolve) => setTimeout(resolve, 300));
await route.continue();
});
await fixture(page, await render(glossary));
const thumbs = page.locator("main td img[data-zoom-thumb]");
await expect(thumbs).toHaveCount(62);
const first = thumbs.first();
const before = await first.evaluate((node) => node.getBoundingClientRect().toJSON() as DOMRect);
expect(before.height).toBeCloseTo(64, 0);
expect(before.width).toBeCloseTo(107.2, 0);
await expect(first).toHaveJSProperty("complete", true);
await expect.poll(() => first.evaluate((node: HTMLImageElement) => node.naturalWidth)).toBe(1440);
expect(await first.evaluate((node) => node.getBoundingClientRect().toJSON() as DOMRect)).toEqual(
before,
);
// The rows far below the screen haven't asked for their files.
expect(requested).not.toContain("59");

await first.focus();
await page.keyboard.press("Enter");
const dialog = page.locator(".cz-dialog");
await expect(dialog).toBeVisible();
await expect(dialog).toHaveAccessibleName("Dashboard 1");
const link = dialog.locator(".cz-link");
await expect(link).toHaveAttribute("href", "https://example.com/page/1");
await expect(link).toHaveText("example.com");
// Far larger than four times the thumbnail, up to what the stage holds.
await expect
.poll(async () => (await rect(page, ".cz-item img")).width)
.toBeGreaterThan(before.width * 4.5);
await page.keyboard.press("Escape");
await expect(dialog).toHaveCount(0);
await expect(first).toBeFocused();

// A cell's two images sit side by side, and the second has no link to show.
const [left, right] = await Promise.all(
[60, 61].map((at) =>
thumbs.nth(at).evaluate((node) => {
node.scrollIntoView();
return node.getBoundingClientRect().toJSON() as DOMRect;
}),
),
);
expect(right!.left).toBeGreaterThan(left!.right);
expect(right!.top).toBeCloseTo(left!.top, 0);
await thumbs.nth(61).click();
await expect(dialog).toBeVisible();
await expect(dialog.locator(".cz-link")).toBeHidden();
});

const svg = (width: number, height: number) =>
`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"><rect width="${width}" height="${height}" fill="teal"/></svg>`;

test("a thumbnail opens at the size and scroll of its file, whatever the size of its box", async ({
page,
}) => {
await page.setViewportSize({ width: 1000, height: 700 });
await page.route("**/drawn-*.svg", (route) => {
const [, width, height] = /drawn-(\d+)x(\d+)/.exec(route.request().url())!;
return route.fulfill({
contentType: "image/svg+xml",
body: svg(Number(width), Number(height)),
});
});
const table = await render(
'| What | Where |\n| --- | --- |\n| Long | ![Long](/drawn-600x2400.svg){width=600 height=2400} |\n| Icon | ![Icon](/drawn-16x16.svg){width=16 height=16} |\n| Wide | ![Wide](/before.png) |\n| Sized | ![Sized](/before.png){width=1280 height=500 data-zoom-context=".post"} |',
);
await fixture(page, `<div class="post">${table}</div>`);
const thumbs = page.locator("main td img[data-zoom-thumb]");
await expect(thumbs).toHaveCount(4);
const dialog = page.locator(".cz-dialog");
const copy = () => rect(page, ".cz-item img");

// A long screenshot opens as wide as its file and scrolls, as it does outside a table.
await thumbs.nth(0).click();
await expect.poll(async () => (await copy()).width).toBeCloseTo(600, 0);
await expect(dialog.locator(".cz-stage")).toHaveAttribute("data-scroll", "");
await page.keyboard.press("Escape");
await expect(dialog).toHaveCount(0);

// An icon is no larger than its file, on the page or zoomed.
expect((await thumbs.nth(1).boundingBox())!.height).toBeCloseTo(16, 0);
await thumbs.nth(1).click();
await expect.poll(async () => (await copy()).width).toBeCloseTo(16, 0);
await page.keyboard.press("Escape");
await expect(dialog).toHaveCount(0);

// An image with no size written keeps a 3:2 box and shows whole in it once it loads.
const wide = thumbs.nth(2);
await expect.poll(() => wide.evaluate((node: HTMLImageElement) => node.naturalWidth)).toBe(1280);
expect(await wide.evaluate((node) => getComputedStyle(node).objectFit)).toBe("contain");
expect((await wide.boundingBox())!.width).toBeCloseTo(96, 0);
// It shows the focus ring from the keyboard, and a narrower limit shrinks the whole box.
await page.keyboard.press("Tab");
await expect(wide).toBeFocused();
expect(await wide.evaluate((node) => getComputedStyle(node).outlineWidth)).toBe("2px");
await page
.locator("table")
.evaluate((node) => node.style.setProperty("--comark-thumb-width", "2rem"));
const narrow = (await wide.boundingBox())!;
expect(narrow.width).toBeCloseTo(32, 0);
expect(narrow.width / narrow.height).toBeCloseTo(1.5, 1);
await page.locator("table").evaluate((node) => node.style.removeProperty("--comark-thumb-width"));

// A context's shell around the copy doesn't hide the image from its sizing.
await thumbs.nth(3).click();
await expect.poll(async () => (await copy()).width).toBeGreaterThan(128 * 4.5);
});
25 changes: 20 additions & 5 deletions packages/ui/src/table-layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,23 @@ const text = (node: Node): string =>
isElement(node) ? childrenOf(node).map(text).join("") : Array.isArray(node) ? "" : node;
const chipsOf = (node: Node): ElementNode[] =>
isElement(node) ? (node[0] === "chip" ? [node] : childrenOf(node).flatMap(chipsOf)) : [];
// A chip draws an icon and padding beside its label, worth about three characters.
const lengthOf = (cell: ElementNode) => text(cell).trim().length + 3 * chipsOf(cell).length;
// comark-zoom runs first and marks the images it draws as thumbnails. Any other image, such as an icon, is its own size.
const imagesOf = (node: Node): ElementNode[] =>
isElement(node)
? node[0] === "img"
? "data-zoom-thumb" in node[1]
? [node]
: []
: childrenOf(node).flatMap(imagesOf)
: [];
/** What comark-zoom's thumbnail of an image in a cell is worth, in characters: about 6.5em of its 8rem at most. */
const THUMBNAIL = 12;
// A chip draws an icon and padding beside its label, worth about three characters. A cell's images sit side by side
// and may break apart, so the cell is as long as its text and one of them.
const lengthOf = (cell: ElementNode) =>
text(cell).trim().length + 3 * chipsOf(cell).length + (imagesOf(cell).length ? THUMBNAIL : 0);
// A cell that never wraps would hold its chips, or its images, in one row however many they are.
const breaks = (cell: ElementNode) => chipsOf(cell).length > 1 || imagesOf(cell).length > 1;

const rowsOf = (table: ElementNode): ElementNode[] =>
childrenOf(table)
Expand All @@ -45,8 +60,8 @@ const sum = (values: number[]) => values.reduce((total, value) => total + value,
* author writes nothing.
*
* - `data-short` on each body cell of a short column, and on its header when the header is no longer. The cell never
* wraps, so `portal #1596` can't break into `#159` and `6`. One with two chips or more is `data-short="chips"`: it
* may break between them, never inside one.
* wraps, so `portal #1596` can't break into `#159` and `6`. One with two chips or more, or two images, is
* `data-short="chips"`: it may break between them, never inside one.
* - A table wider than a readable column goes in a `div` with `data-wide` and `data-width`, its own width in em rounded
* up to a step, so it grows into the room beside the text like a wide diagram.
* - When two or more of its columns hold more than short values, the table is a grid (`data-cols`): the short columns
Expand Down Expand Up @@ -100,7 +115,7 @@ function layoutTable(table: ElementNode): ElementNode {
cellsOf(row).forEach((cell, index) => {
const column = columns[index];
if (!column?.short) return;
if (row !== head) cell[1]["data-short"] = chipsOf(cell).length > 1 ? "chips" : "";
if (row !== head) cell[1]["data-short"] = breaks(cell) ? "chips" : "";
else if (column.headerShort) cell[1]["data-short"] = "";
});

Expand Down
11 changes: 11 additions & 0 deletions packages/ui/test/table-layout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,17 @@ describe("table layout", () => {
expect(json).toMatch(/"data-short":""[^\]]*\["chip"/);
});

it("lets a cell of two thumbnails break between them, and counts no image that isn't one", async () => {
const table =
"| Id | Kind | Area | Where |\n|---|---|---|---|\n| a1 | page | home | ![One](a.png) ![Two](b.png) |\n| b2 | card | cart | ![Three](c.png) |";
expect(JSON.stringify(await nodes(table))).toContain('"data-short":"chips"');
const plain = JSON.stringify(
await nodes(table, { zoom: { thumbnails: false, images: false } }),
);
expect(plain).not.toContain('"data-short":"chips"');
expect(plain).not.toContain("data-wide");
});

it("keeps a short column's header on one line only when it's no longer than its cells", async () => {
const output = await createHtmlRenderer(html(offline))(
"| Server | Peak memory (megabytes) |\n|---|---|\n| node | 182 |\n| bun | 141 |",
Expand Down
58 changes: 57 additions & 1 deletion packages/zoom/docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ credits: 'Modeled on <a href="https://github.com/francoischalifour/medium-zoom">
```
:::

:::example{label="In a table"}
```md
| Term | Means | Where it shows |
| --- | --- | --- |
| Correlation | How two offices move together | ![Office correlations dashboard](/dashboard.png) |
| Filter | Narrows the dashboard to one team | ![Filter toolbar on one row](/after.png) |
```
:::

:::example{label="Any block"}
```md
::zoom{title="Deploy retry policy"}
Expand Down Expand Up @@ -44,6 +53,7 @@ credits: 'Modeled on <a href="https://github.com/francoischalifour/medium-zoom">
## Features

- Content images zoom with no markup.
- An image in a table cell is a small thumbnail that zooms, so a table holds a screenshot per row.
- `::zoom` zooms any block, such as a table, a code block, or a diagram.
- Items in one group page through one view, with a strip of thumbnails.
- An image never grows past its natural size, so it stays sharp.
Expand All @@ -60,6 +70,42 @@ Content images zoom on their own, titled by their `alt` text.
![Office correlations dashboard](/dashboard.png)
```

### In a table

Put an image in a table cell to show it as a thumbnail. It keeps its ratio inside a box 4rem high and 8rem wide, loads only near the screen, and opens at the size of its file. A cell can hold several, and a table can hold a screenshot in every row.

::example
```md
| App term | Engine term | Means | Where it shows |
| --- | --- | --- | --- |
| Dashboard | `overview` | The first page, with one card per office | ![Office correlations dashboard](/dashboard.png){width=1440 height=860} |
| Filter bar | `query.filters` | Narrows every card to one team or week | ![Filter toolbar wrapping](/before.png){width=1280 height=500} ![Filter toolbar on one row](/after.png){width=1280 height=500} |
| Correlation | `pearson_r` | How closely two offices move together | ![Correlation card](/dashboard.png){width=1440 height=860} |
| Office | `site` | A place with its own headcount | ![Office list](/dashboard.png){width=1440 height=860} |
| Week | `iso_week` | Monday to Sunday, by ISO 8601 | ![Week picker](/after.png){width=1280 height=500} |
| Headcount | `fte` | Full-time equivalents, not people | ![Headcount card](/dashboard.png){width=1440 height=860} |
| Trend | `slope_4w` | The change over the last four weeks | ![Trend arrow](/dashboard.png){width=1440 height=860} |
| Outlier | `z_gt_3` | A week far from its mean | ![Outlier marker](/dashboard.png){width=1440 height=860} |
| Team | `group` | People who share a manager | ![Team filter](/before.png){width=1280 height=500} |
| Region | `geo` | Offices grouped by country | ![Region filter](/after.png){width=1280 height=500} |
| Export | `dump_csv` | Downloads the cards on screen | ![Export button](/dashboard.png){width=1440 height=860} |
| Share link | `permalink` | A URL that restores the filters | ![Share dialog](/dashboard.png){width=1440 height=860} |
```
::

> [!TIP]
> Give each image its `width` and `height`, the size of its file, so the row has its height before the image loads. Without them it shows whole inside a 3:2 box.

### Link to the page shown

Use the `link` attribute to name the page an image shows. The zoomed view links to it beside the title, and a click on the image still zooms.

::example
```md
![Office correlations dashboard](/dashboard.png){link="https://comark-ui.onmax.me/zoom"}
```
::

### Any block

Use `::zoom` to zoom any other block, or several blocks together.
Expand Down Expand Up @@ -161,7 +207,7 @@ In an open or change listener, `event.detail.copyOf(element)` finds a page eleme

## Accessibility

Each item is a tab stop that opens a native modal `<dialog>`, labelled by its title. The dialog sits in the top layer and the page behind it is inert, so focus stays in the dialog while it's open. Focus returns to the item on close. An item inside another one, such as a screenshot in a slide, zooms with it, so only the outer one is a tab stop.
Each item, a thumbnail included, is a tab stop that opens a native modal `<dialog>`, labelled by its title. The dialog sits in the top layer and the page behind it is inert, so focus stays in the dialog while it's open. Focus returns to the item on close. An item inside another one, such as a screenshot in a slide, zooms with it, so only the outer one is a tab stop.

### Keyboard interactions

Expand All @@ -188,6 +234,8 @@ Each item is a tab stop that opens a native modal `<dialog>`, labelled by its ti
| Attribute | Default | Description |
| --- | --- | --- |
| `zoom` | `true` | `false` keeps the image from zooming. |
| `link` | — | The page the image shows, linked from the zoomed view. Web addresses only. |
| `width`, `height` | — | The size of the file in pixels, so the image keeps its room before it loads. |
| `data-zoom` | — | Makes an image zoom when the `images` option is `false`. |
| `data-zoom-src` | — | A larger file to load when the view opens. |
| `data-zoom-aside` | — | A selector for an element to show beside the zoomed item. |
Expand All @@ -200,6 +248,7 @@ The options go under `zoom` in `comarkUi()`, or to `zoom()` when you use it alon
| Option | Default | Description |
| --- | --- | --- |
| `images` | `true` | `false` leaves images alone, so only `::zoom` blocks and images with `data-zoom` zoom. |
| `thumbnails` | `true` | `false` draws an image in a table cell at its own size, like any other image. Otherwise it's a thumbnail that zooms even when `images` is `false`. |
| `size` | Data URIs only | Gives images their `width` and `height` while parsing. `true` also fetches remote URLs with range requests, which follow redirects and can reach private networks, so use it only for trusted documents. An image with one side gets the other from its ratio. One with both sides, or a side like `50%`, stays as it is. `false` turns measuring off. |

### Events
Expand Down Expand Up @@ -283,11 +332,18 @@ The zoomed view sits at the end of `body`, so set these on `:root`, `body`, or `
| `--cz-backdrop` | `--comark-background` at `--cz-backdrop-opacity` | The backdrop's color |
| `--cz-backdrop-opacity` | `96%` | How much of `--comark-background` the backdrop mixes in |

| `--comark-thumb-height` | `4rem` | The height of a thumbnail in a table cell |
| `--comark-thumb-width` | `8rem` | The most a thumbnail is wide; a wider image gets shorter |

Set the two thumbnail variables on the table or any ancestor, not on the dialog.

### Classes and attributes

| Selector | Is |
| --- | --- |
| `[data-zoom]` | An item on the page that zooms |
| `img[data-zoom-thumb]` | A thumbnail in a table cell |
| `.cz-link` | The link to the page an image shows, from its `link` |
| `.cz-dialog` | The zoomed view, with `data-aside` when it shows a caption beside the item |
| `.cz-backdrop` | The layer behind everything else |
| `.cz-header`, `.cz-title`, `.cz-count`, `.cz-place`, `.cz-close` | The top row: title, position in a group, position among the page's figures (hidden on touch screens), and the close button |
Expand Down
Loading
Loading