Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.
TypeScript claude-code-mod
Click targets in pictures: hover tints links, file paths and inline code; a click copies them
razorback16b8aa3985b966
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 19a39d5..2247556 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,17 @@All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Code finds a new version by the `version` in `.claude-plugin/plugin.json`. To get it, refer to [Update](docs/install.md#update).+## Unreleased++### New++- **Links, file paths and commands in the pictures are live** (picture select, fullscreen mode). Move the pointer over one: its cells show on the selection colour. A click copies it: a web link its URL, a file path its full path, a command the full command (toasts "copied the link", "copied the path", "copied the command"). A command is any inline code (for example `` `git status` ``; `` `! cmd` `` copies only `cmd`); a code block is not a target. A drag that starts on one still selects text. Refer to [Click a link, a file or a command](docs/usage.md#click-a-link-a-file-or-a-command).+- `IUI_DEBUG=1` writes a `select: click` line with the target of each click, and a `select: hover` line when the target under the pointer changes.++### Changed++- Where the pages take picture select, the dim link rows under the pictures do not show (the links are in the picture). On the main screen, over ssh, before Claude Code 2.1.298 and with `/iui select off`, they show as before.+## 0.3.1 (2026-10-21)### Newdiff --git a/docs/development.md b/docs/development.mdindex e1084e5..fada61d 100644--- a/docs/development.md+++ b/docs/development.md@@ -30,6 +30,8 @@ Picture select writes trace lines that start with `select:`:- `select: words <id> page <n> <k> words in <ms> (background)`: the background probe of a page's words (`none` when it found no words).- `select: copy <n> chars <ms>ms after the up (text <ms>ms, words cached | words probed for page <n>); native selection seen (...) | no native selection`: the copy at `up`, and whether Claude Code has a selection of its own with picture cells.- `select: native copy seen: ...`: picture cells on the clipboard, or a `$.ui.copy` with picture cells.+- `select: hover <id> page <n> target <i> (<kind>) rows <row>:<x0>-<x1>,...` (or `select: hover none`): the target under the pointer changed (`web`, `file` or `command`, and its cells).+- `select: click <id> page <n> at <x>,<y> target <kind>|none`: one line for each click (a `clear`), with the target that it copies.## Module layoutdiff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 678a86f..f111899 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -10,7 +10,7 @@4. Text size: the mod finds the terminal font (iTerm2 profile, Ghostty, kitty or Rio config; on Linux, else fontconfig's `monospace` font; else the metrics of the theme's code font, Menlo on macOS) and the cell size in pixels. Typst then measures both fonts so that 100% looks as large as the terminal text. Body text and code use the terminal font, so at 100% they are exactly the terminal's size. The mod uses the font that the terminal draws: if the config names a font that is not installed, the terminal draws a different font, and the mod uses that font too (Ghostty and cmux on macOS, and Rio: their own font; Ghostty on Linux and kitty on Linux: the nearest font of fontconfig; kitty on macOS: Menlo; iTerm2: the user's fixed-pitch font, Menlo if you did not change it). If Ghostty's `font-family` is a list, the mod uses the first font of the list that is installed. Ghostty and cmux draw their own JetBrains Mono when their config names no font. Rio draws its own Cascadia Code NF when its config names no font (or `cascadiacode`). These fonts are not files: they are inside the program of the terminal. The first time, the mod copies the font to `~/.cache/cc-intelligent-ui/fonts/` (approximately 0.1 s for Ghostty and 0.5 s for Rio, once for each version of the terminal), so that Typst can draw it. If you set the `TYPST_FONT_PATHS` variable, Typst gets your folders and the copy. If the mod cannot copy Rio's font, it uses Cascadia Code if it is installed. If Typst does not have the terminal font, `/iui details` tells you, and the pictures use the theme's fonts. If the terminal font has no bold face (for example, Monaco), the pictures draw its bold text with a thin outline in the text colour (a fake bold, as a terminal draws it). The mod finds this with `typst fonts --variants` when it measures the fonts. In Ghostty and cmux, the mod also removes the window padding from the cell size, because Ghostty adds the padding to the pixel size that it reports.5. If a compile fails (a bad Typst block or an unknown LaTeX command), the mod compiles once more in safe mode: Typst blocks and math show as code. A dim line under the picture names the error. If that also fails, the normal text shows.6. Pictures are kept in `${TMPDIR}/cc-intelligent-ui-<uid>/` (`/tmp` when `TMPDIR` is not set). Folders older than 2 days are deleted at start. The drawing space of each answer at its first compile is kept in `~/.cache/cc-intelligent-ui/designs`, so that its Typst drawings keep the same share of the screen in later sessions.-7. Links: the mod finds the web links, file paths and commands in the Markdown (not in code blocks or math). It draws one dim row for each under the pages, with a `Link` (an OSC 8 link) for a web link or a file, and a `Button` that copies a command (`$.ui.copy`). It keeps a file row only when the file exists (`$.fs.exists`, kept in memory for 512 paths). Each row is one terminal row, cut at its end. The copy (step 9) counts these rows under the pages, so it still finds the page that you select.+7. Links: the mod finds the web links, file paths and commands in the Markdown (not in code blocks or math). It draws one dim row for each under the pages, with a `Link` (an OSC 8 link) for a web link or a file, and a `Button` that copies a command (`$.ui.copy`). It keeps a file row only when the file exists (`$.fs.exists`, kept in memory for 512 paths). Each row is one terminal row, cut at its end. The copy (step 9) counts these rows under the pages, so it still finds the page that you select. When the pages take picture select, the mod does not draw these rows (the links are live in the picture, refer to [Picture select](#picture-select)), and the copy, the plan and the Markdown files that Claude sent count 0 rows for them.8. The plan: a `ui.render` hook on the ExitPlanMode `ToolUse` row draws the plan through the same steps. Claude Code shows that row above the approval question. The approved result row then shows only its header, so the plan does not show two times. A `tool.call` hook on ExitPlanMode asks the mod's question (`$.ui.ask`) before Claude Code asks for permission. Then a `classic.PermissionRequest` hook gives the answer to Claude Code at once, so the Claude Code dialog does not show. For an approval, the hook sends the plan (`updatedInput`) and the new permission mode (`setMode`). For the person's text, the `tool.call` hook refuses the call with that text.9. Copy: in fullscreen mode, picture select copies the text of a picture (refer to [Picture select](#picture-select)). A copy that still puts picture cells on the clipboard is a native copy: the copy of the terminal itself on the main screen, a selection of Claude Code that starts outside a picture, or a copy of a different session. The mod never writes the clipboard for a native copy.@@ -24,12 +24,13 @@The selection of Claude Code copies picture cells as kitty placeholder characters, not as text (from Claude Code 2.1.305, it skips picture cells). Thus the mod selects pictures itself (`hooks/lib/select.ts`):-1. Each page is in a `Box` of its size. The last child is a `Client` (`hooks/sel.tsx`) in a `Box` with a negative top margin (the page's rows), so it is over the page. The `Client` draws only an empty `Box` (anything that it draws hides the picture cells). It takes the pointer and posts the selection whole: the anchor, the head, the phase (`down`, `move`, `up` or `clear`) and an order. Posts of one frame merge, so a bare event could be lost.+1. Each page is in a `Box` of its size. The last child is a `Client` (`hooks/sel.tsx`) in a `Box` with a negative top margin (the page's rows), so it is over the page. The `Client` draws only an empty `Box` (anything that it draws hides the picture cells). It takes the pointer and posts the selection whole: the anchor, the head, the phase (`down`, `move`, `up` or `clear`; `hover` and `leave` with no button down, refer to item 7 below) and an order. Posts of one frame merge, so a bare event could be lost.2. The `ui.message` hook keeps the newest selection. The selected rows are in stream order, in the rows of the whole drawing, so a drag can go on into the next page.3. The highlight does not change the layout. Each page stays one keyed `Image`, and the mod swaps its picture with `$.ui.blit` (`hooks/lib/blit.ts`). This is one small kitty command with the same image id (`a=T`, `t=f`, the file name), so the terminal replaces the picture in place. The frame is the page with the selected cells changed: in a selected cell, each pixel of the page (straight alpha) over the opaque selection colour; in the other cells, the page as it is. A clear swaps the page's own PNG back. Cell `i` is the pixels from `round(i × pixels / cells)` to `round((i + 1) × pixels / cells)`, so the cells cover the page with no gap at any ratio.4. The hooks runtime has no zlib, so `hooks/lib/png.ts` decodes the page in JavaScript (inflate and unfilter). For each row of cells, the mod makes a deflate piece one time (fixed Huffman codes, matches of one pixel to the left or one pixel up, ended on a byte). A row that is selected whole has a tinted piece, also made one time (in the background, or by a frame: 6 ms of them at most per frame; a row that is not made yet shows plain in that frame, and the next frame continues). A frame makes new pieces only for the first and last selected rows (partly selected), and joins the pieces into one PNG (up to approximately 3 MB for a tall page). The first highlight frame of a ready page takes approximately 2–3 ms to make. The hooks can write only text, so `perl` writes the frame (base64 on its stdin) to `<cache>/select-<id>/f-<n>.png`. The terminal reads the file after the blit. The mod deletes a frame file when 4 newer frames are written and it is 2 s old. The 2-day cleanup of the cache folder deletes the rest.5. A new frame starts at most once in 16 ms, and only after the last one is blitted. The posts between fold into one frame of the newest selection. If Claude Code refuses a blit, the mod writes the reason one time to the debug log and shows no highlight on that page until the next `down`. The copy still works.6. At `up`, the mod reads the words under the selected cells the same way as for a copy of these cells (`textOfRun` on the words of the probe), and copies them with `$.ui.copy`. A toast shows "copied N chars of text".+7. Links, file paths and commands (the click targets, `hooks/lib/targets.ts`): the probe also tags the words of a Markdown link (its URL), and the words of inline code (its text). When the words of a page are known, the mod finds its targets (web links, bare URLs, file paths that exist, and inline code, which is a command when it is not a file that exists; a code block is not a target) and the cells of each, one time for each page and size. With no button down, the `Client` posts `hover` when the pointer goes to a new cell and `leave` when it goes out. The mod then shows the target under the pointer with the same blits as a selection (step 3), and the page's own PNG when the pointer is off the targets. There is no hover highlight while a selection shows, and a `down` removes it. A `clear` (a click) on a target copies it with `$.ui.copy` (a web link's URL, a file's full path, the text of inline code). A later post of one frame replaces an earlier one, so a `hover` or a `leave` also carries the last `up` or `clear` of its `Client`, and the mod reads that one first (by its order, one time).The `Client` is in the flow, not in an absolute `Box`. Claude Code (2.1.306) moves an absolute `Box` whose top is above the screen down to row 0, with its children. Then the pointer `y` of a `Client` in such a `Box` counts from row 0 of the screen, not from the top of the page, so the selection was too high by the rows that were scrolled away. Also, the `Client` took the pointer under the page. A `Box` in the flow has its true position, also when its top is above the screen.diff --git a/docs/limitations.md b/docs/limitations.mdindex a63f624..750bd4c 100644--- a/docs/limitations.md+++ b/docs/limitations.md@@ -29,13 +29,18 @@- When Claude Code draws the page again from the start (for example, a page that scrolled far away and comes back), the page shows without its highlight until the selection changes. The copy is not changed.- The blue background is VS Code's selection colour, not the one of your terminal or Claude Code theme.- A page whose PNG is over 4 MiB (the most that the mod can read) has no highlight.+ - A click on a link, a file path or a command (refer to [Click a link, a file or a command](usage.md#click-a-link-a-file-or-a-command)) has these limits:+ - A click copies. It does not open a link or a file: the terminal does not send cmd+click to Claude Code, and on macOS ctrl+click is the secondary click.+ - A code block is not a target, also a `bash` block. To copy a command in a code block, select its text. The dim rows under the picture (with a copy button for a `bash` block) do not show with picture select.+ - The mod finds the targets from the words of the page. Until they are known (the probe, refer to [The page cache](how-it-works.md#the-page-cache)), a hover shows no highlight, and a click waits for them.+ - A file path is a target only when the file exists when the mod draws the answer. A link to a heading of the same text is not a target. A link, a file path or a command in a Typst drawing, in math or in an image is not a target.- It needs `perl` (with `MIME::Base64`, a core module) to write the frames. With no `perl`, the selection and the copy work with no highlight (the mod tries one time, then writes the reason to the debug log).- **The cache folder:** the mod uses only its private cache folder (`$TMPDIR/cc-intelligent-ui-<uid>`, mode 700, your own and not a link). If that folder is a link, is not a folder or is not yours, the mod draws nothing and picture select is off. `/iui`, `/iui details` and a toast at the start tell you why. Remove or fix that folder, then start Claude Code again.- It copies at the button's up, also when `copyOnSelect` is `false` in `/config`.- **A fake bold** (a terminal font with no bold face, for example Monaco): bold text gets a thin outline in its colour. These limits apply:- A character that the terminal font does not have (for example, CJK text in Monaco) comes from another font. If that font has a bold face, the character gets both the real bold face and the outline, so it is a little bolder than in the terminal.- Bold text in a live Typst drawing (for example, `text(weight: "bold", font: theme.mono)`) does not get the fake bold. It shows as regular text.-- **Links in a picture:** a click on the picture does not open a link, because the mod cannot put a link on a picture. Use the link rows under the picture (refer to [Links, file paths and commands](usage.md#links-file-paths-and-commands)). A click on a command row copies the command only where Claude Code gets mouse clicks (fullscreen mode). A `file://` link opens in the app that the terminal chooses. A file row shows only when the file exists when the mod draws the answer.+- **Links in a picture:** without picture select (the main screen, over ssh, Claude Code before 2.1.298, `/iui select off`), a click on the picture does not open a link, because the mod cannot put a link on a picture. Use the link rows under the picture (refer to [Links, file paths and commands](usage.md#links-file-paths-and-commands)). A click on a command row copies the command only where Claude Code gets mouse clicks (fullscreen mode). A `file://` link opens in the app that the terminal chooses. A file row shows only when the file exists when the mod draws the answer.- **PDF files** (refer to [What it draws](usage.md#what-it-draws)): a click on `‹`, `›` or the page number works only where Claude Code gets mouse clicks (fullscreen mode). The page field gets the keyboard only when the prompt is empty. If the prompt has text, the field opens without the keyboard: click the field to type. Then Esc goes to the prompt, not to the field. To close the field, click it and push Esc, or click its close mark. The mod draws one page at a time, and it does not show the number of pages. You cannot copy text from a PDF page.- **The row grid** (`/iui grid on`, refer to [Selection and the row grid](usage.md#selection-and-the-row-grid)) has these limits:- Inline math that is taller than a row adds 1 row or more to its line. The text stays on the rows. Math that is only a little taller than the row does not add a row, and its ink can come near the line above or below.diff --git a/docs/usage.md b/docs/usage.mdindex 699b6cd..7b5c8e3 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -75,7 +75,7 @@ You can also start the skill yourself: type `/cc-intelligent-ui:intelligent-ui`## Links, file paths and commands-A picture has no text for the terminal, so a click on a link in the picture does not open it. Thus the mod shows the links, file paths and commands of an answer, a plan or a Markdown file that Claude sent in dim rows under its picture. These rows show only when the text has links, file paths or commands. Each item uses one row:+In fullscreen mode, with picture select on, you click the links, file paths and commands in the picture itself. Refer to [Click a link, a file or a command](#click-a-link-a-file-or-a-command). In other conditions (the main screen, over ssh, Claude Code before 2.1.298, or `/iui select off`), a picture has no text for the terminal, so a click on a link in the picture does not open it. Then the mod shows the links, file paths and commands of an answer, a plan or a Markdown file that Claude sent in dim rows under its picture. These rows show only when the text has links, file paths or commands. Each item uses one row:```↗ Typst docs https://typst.app/docs@@ -100,10 +100,20 @@ Picture select works in fullscreen mode only. It is on by default. `/iui select1. Drag over a picture with the left button. Start the drag on the picture. The selected cells show on a blue background (VS Code's selection colour), in the order of the text: the first row from where you started, the rows between, and the last row to the pointer. The layout does not change.2. Release the button. The mod copies the text of the selected cells (the same words that a copy of these cells gives) and shows the toast "copied N chars of text". Then paste.-3. These remove the selection: a click with no drag in a picture, a new selection in a picture, a key typed in the prompt, a new selection of Claude Code (normal text), your next prompt, and `/iui off` or `/iui select off`. A single click on normal text does not (refer to [Limitations](limitations.md)).+3. These remove the selection: a click with no drag in a picture (a click on a link, a file path or a command also copies it, refer to [Click a link, a file or a command](#click-a-link-a-file-or-a-command)), a new selection in a picture, a key typed in the prompt, a new selection of Claude Code (normal text), your next prompt, and `/iui off` or `/iui select off`. A single click on normal text does not (refer to [Limitations](limitations.md)).A selection can go on into the next page of the same answer.+#### Click a link, a file or a command++With picture select, the web links, file paths and commands in a picture are live. The dim link rows do not show under the picture.++- Move the pointer over a link, a file path or a command (no button). Its cells show on the blue background. Move the pointer off it, and the background goes. While a selection shows, there is no such highlight.+- Click it (push and release the button on the same cell). The mod copies it and shows a toast: a web link copies its URL ("copied the link"), a file path copies its full path ("copied the path"), and a command copies the full command ("copied the command").+- A drag that starts on a link, a file path or a command selects text, as on other text.++A web link is a Markdown link to an `http:`, `https:` or `mailto:` URL, or a URL in the text. A file path is in the text or in inline code, and the file must exist (a relative path starts from the session's folder). A command is any inline code that is not a file that exists, for example `` `git status` `` (a click copies its text; for `` `! cmd` `` it copies only `cmd`). A code block is not a target (to copy it, select its text). A link to a heading in the same text is not a link for this.+When a page is drawn or comes on the screen, the mod gets the page ready for the highlight in the background. It also finds the position of each word on the page. Thus the first highlight and the copy are fast. If you push the button on a page that is not ready, the mod gets that page ready first, and the first highlight shows a short time later. If the words of the page are not ready when you release the button, the copy waits for them: approximately 0.05 s for plain text (only ASCII characters, no math, no Typst block and no image), 0.15–0.5 s for other text, and more (2–3 s) for a page with a large Typst drawing. No toast shows while the mod does this. Only the toast of the copy shows. The mod keeps the positions in memory, so the next copy from the same page is fast.### Picture cells on the clipboarddiff --git a/hooks/lib/copy.ts b/hooks/lib/copy.tsindex 1684a73..4c08945 100644--- a/hooks/lib/copy.ts+++ b/hooks/lib/copy.ts@@ -132,13 +132,19 @@ export type Mark = {cx?: numberg?: numberpad?: number+ href?: string+ code?: string}// A word, or a whole code line (`adv`: its character advance), in PNG// pixels: its box, the block it is in, and its place in the document (`i`).// `glued`: a character of a long word or of CJK text after the first (it// joins the one before with no space). A word's `em` is its text size and-// `pad` the padding beside inline code (a word of it), in pixels.-export type Item = { i: number; text: string; x0: number; y0: number; x1: number; y1: number; block: number; adv?: number; glued?: boolean; em?: number; pad?: number }+// `pad` the padding beside inline code (a word of it), in pixels. `href`: the+// URL of the link it is in; `code`: the whole text of the inline code it is in.+export type Item = {+ i: number; text: string; x0: number; y0: number; x1: number; y1: number; block: number; adv?: number; glued?: boolean; em?: number; pad?: number+ href?: string; code?: string+}// A block: paragraph, heading, code, quote, cell (`cx` its column), item// (`prefix`); `first` its first item.export type TextBlock = { kind: string; prefix: string; cx?: number; first: number }@@ -167,7 +173,8 @@ function isMarker(marks: readonly Mark[], j: number): boolean {// The probe's marks (document order) as boxes in pixels at `ppi`. A list's// marker is dropped (isMarker). A block mark with no word since the last one// (an item, then its paragraph) adds to that block. A word of only-// invisible characters is dropped.+// invisible characters is dropped. A link's URL and an inline code's text go+// to its words.export function positionsOf(marks: readonly Mark[], ppi: number): Positions {const k = ppi / 72const blocks: TextBlock[] = []@@ -201,6 +208,7 @@ export function positionsOf(marks: readonly Mark[], ppi: number): Positions {i: count, text: (m.t ?? '').replace(INVISIBLE, ''), block, x0: round(m.x * k), x1: round((m.x + (m.w ?? 0)) * k),y0: round(m.y * k), y1: round((m.y + (m.h ?? m.s ?? 11)) * k), ...(m.g ? { glued: true } : {}),...(m.s ? { em: round(m.s * k) } : {}), ...(m.pad ? { pad: round(m.pad * k) } : {}),+ ...(m.href ? { href: m.href } : {}), ...(m.code ? { code: m.code } : {}),}if (!item.text) returncount++diff --git a/hooks/lib/draw.tsx b/hooks/lib/draw.tsxindex 19cc468..85bc655 100644--- a/hooks/lib/draw.tsx+++ b/hooks/lib/draw.tsx@@ -5,13 +5,13 @@import type { EngineInterface, RenderComponent, RenderSurface, RenderViewport, ResolveInput } from 'claude-code'import type { IuiTheme } from '../../types'-import { BODY_PT, bulletOf, GRID_VERSION, GUTTER, LINK_FILES_KEPT, MARGIN_TOP, TEMPLATE_VERSION } from './settings'+import { BODY_PT, bulletOf, GRID_VERSION, GUTTER, LINK_FILES_KEPT, MARGIN_TOP, RESULTS_KEPT, TEMPLATE_VERSION } from './settings'import { INLINE_KEPT, inlined, keep, linkFiles, S, type Cell, type Look, type Metrics, type Result, type Room } from './state'import { DEFAULT_GRID, gridFirstRow, type GridMetrics } from './grid'import { FENCE, imagePathOf } from './markdown'import { linksOf, type LinkItem } from './links'import { fitBox, fitsInline, roomColumns } from './terminal'-import { selectOn } from './select'+import { clickLinks, selectOn } from './select'import { noteSite } from './blit'import { fsExists, fsRead, uiCopy, uiResolve, uiToast } from './api'@@ -183,9 +183,11 @@ export async function inlineOf($: EngineInterface, result: Result): Promise<stri// How a set of pages sits: `bullet` the reply bullet in the gutter (on the// first line's row), `gutter` its width (0: none), `marginTop` the rows above,// `keys` a prefix for its Images' and Buttons' keys (several sets in one-// tree), `links` the link rows under the pages (one row each), `id` the-// drawing's id in drawnAnswers (its pages take picture select, its Images-// swapped by key under the render's requestId: blit.ts).+// tree), `links` the link rows under the pages (one row each; none drawn+// when the pages take picture select: a click on the picture copies or+// opens them), `id` the drawing's id in drawnAnswers (its pages take+// picture select, its Images swapped by key under the render's requestId:+// blit.ts).export type PagesLayout = { bullet?: boolean; gutter?: number; marginTop?: number; keys?: string; links?: readonly ShownLink[]; id?: string }// The bullet's row when the page is drawn `factor` as wide.@@ -194,6 +196,18 @@ export function scaledBulletRow(bulletRow: number, factor: number): number {return Math.max(0, Math.round((bulletRow + 0.5) * factor - 0.5))}+// Whether pages drawn in this render take picture select (with their+// Client): from files (not `inline`, as bytes over ssh), in an engine with+// the Client element, and selectOn.+export function takesSelect($: EngineInterface, e: ResolveInput<RenderComponent, 'terminal'> & { viewport?: RenderViewport }, inline?: readonly string[]): boolean {+ const table = uiResolve($, e)+ const Client: typeof table.Client | undefined = table.Client+ return !inline && !!Client && selectOn({ hasClient: true, isFullscreen: e.viewport?.isFullscreen })+}++// The link rows drawn under pages (one each): none when they take picture select.+export const linkRowsOf = (links: readonly ShownLink[] | undefined, isSelect: boolean) => (isSelect ? 0 : (links?.length ?? 0))+// `inline`: each page's PNG as base64 (over ssh); else the terminal reads the// file. Each page draws at its own box, never stretched. A page wider than// the room now (an old one in an open epoch) draws smaller to fit, the@@ -217,8 +231,9 @@ export function drawPages(// is above the screen down to row 0, its pointer too). The highlight// swaps the Image's picture (blit.ts); the layout stays.const id = layout.id- const isSelect = !!id && !inline && !!Client && selectOn({ hasClient: true, isFullscreen: e.viewport?.isFullscreen })+ const isSelect = !!id && !!Client && takesSelect($, e, inline)if (isSelect && e.requestId) noteSite(id, e.requestId, keys)+ if (isSelect) keep(clickLinks, id, layout.links ?? [], RESULTS_KEPT)return (<Box flexDirection="row" marginTop={layout.marginTop ?? MARGIN_TOP}>{gutter > 0 ? (@@ -250,7 +265,7 @@ export function drawPages()})}{result.note ? <Text dimColor wrap="truncate-end">Typst error: {result.note}</Text> : null}- {layout.links?.length ? drawLinks($, e, layout.links, keys) : null}+ {layout.links?.length && !isSelect ? drawLinks($, e, layout.links, keys) : null}</Box></Box>)@@ -259,7 +274,8 @@ export function drawPages(// ---- Links ------------------------------------------------------------------// A click on a picture cannot open a link (an Image is a leaf: no Link holds// it, and a press on it gives no cell). So the links, file paths and commands-// of a text are drawn under its pages, one row each.+// of a text are drawn under its pages, one row each; where the pages take+// picture select, its Client finds them on the picture (targets.ts) instead.// A link row: a web link, a file found (`path` its absolute path, `href` its// file:// URL), or a command.diff --git a/hooks/lib/links.ts b/hooks/lib/links.tsindex 99a8235..5b119b1 100644--- a/hooks/lib/links.ts+++ b/hooks/lib/links.ts@@ -40,7 +40,7 @@ const EXTS = new Set()// A path and its label (the path with its `:line:col`), or null.-function fileOf(token: string, bare = false): { path: string; label: string } | null {+export function fileOf(token: string, bare = false): { path: string; label: string } | null {const m = FILE.exec(token)if (!m || token.includes('://')) return nullconst path = m[1]!@@ -77,7 +77,7 @@ const labelOf = (md: string) =>// A bare URL less the punctuation after it: `.,;:!?'"*` and a `)` or `]`// that closes nothing in the URL.-function trimUrl(url: string): string {+export function trimUrl(url: string): string {const count = (c: string) => url.split(c).length - 1for (;;) {const last = url.at(-1)!diff --git a/hooks/lib/pictures.tsx b/hooks/lib/pictures.tsxindex 71e8c15..842bb6e 100644--- a/hooks/lib/pictures.tsx+++ b/hooks/lib/pictures.tsx@@ -17,7 +17,7 @@ import {pictureRowsFor, type PdfFacts, type PixelBox, type SentFile,} from './images'import { imagePathOf } from './markdown'-import { drawPages, hashOf, linksFor, type ShownLink } from './draw'+import { drawPages, hashOf, linkRowsOf, linksFor, type ShownLink } from './draw'import { convertCall, logDebug, parseOd, pngSize } from './typst'import { pagesOf, type Drawing } from './answer'import { HEADERS_SH } from './host'@@ -487,20 +487,22 @@ const boxOf = (frame: Frame, inline: boolean, height: Height): PixelBox =>// error line: its link rows, then all after it (a picture its rows, a// PDF's error line one, each with a PDF's control line; a Markdown file its// pages at their drawn box (fitBox in `room`, as drawPages), a Typst error-// line and its link rows; a blank none).-export function rowsAfter(under: readonly Under[], i: number, room: number): number {+// line and its link rows; a blank none). `isSelect`: the row's pages take+// picture select (takesSelect), so pages drawn from files have no link rows.+export function rowsAfter(under: readonly Under[], i: number, room: number, isSelect = false): number {const own = under[i]- return linkRows(own) + under.slice(i + 1).reduce((sum, u) => {+ return linkRows(own, isSelect) + under.slice(i + 1).reduce((sum, u) => {if ('note' in u) return sum + 1 + (u.pdf ? 1 : 0)if ('source' in u) return sum + u.rows + (u.pdf ? 1 : 0)if (u.drawing.kind !== 'pages') return sumconst { pages, note } = u.drawing.result- return sum + pages.reduce((n, p) => n + fitBox(p, room).rows, 0) + (note ? 1 : 0) + linkRows(u)+ return sum + pages.reduce((n, p) => n + fitBox(p, room).rows, 0) + (note ? 1 : 0) + linkRows(u, isSelect)}, 0)}-// The link rows drawn under a Markdown file's pages (one row each).-const linkRows = (u: Under | undefined) => (u && 'drawing' in u && u.drawing.kind === 'pages' ? (u.links?.length ?? 0) : 0)+// The link rows drawn under a Markdown file's pages (one row each; none where they take picture select).+const linkRows = (u: Under | undefined, isSelect: boolean) =>+ u && 'drawing' in u && u.drawing.kind === 'pages' ? linkRowsOf(u.links, isSelect && !u.drawing.bytes) : 0// The engine's row, then the pictures under it.export function underRow($: EngineInterface, e: RowInput, row: RenderElement, under: readonly Under[]) {diff --git a/hooks/lib/probe.ts b/hooks/lib/probe.tsindex 7fa6b3a..ecc03d7 100644--- a/hooks/lib/probe.ts+++ b/hooks/lib/probe.ts@@ -11,6 +11,8 @@ import { clip, DRAWN_KEPT, drawnAnswers, keep, lastKey, results, type Job, typeimport { fitBox } from './terminal'import { isSafePage, probePage } from './typst'import { screenOf, type Drawn, type DrawnPage, type Item, type TextBlock } from './copy'+import { targetsOf, type PageTarget } from './targets'+import type { ShownLink } from './draw'// Notes the pages of `id` as drawn now, each at fitBox(page, room), as// drawPages draws it, with the Job of the key the row drew last (lastKey:@@ -90,8 +92,26 @@ export async function wordsOf($: EngineInterface, d: Drawn & { job?: Job }, pagereturn got}+// The click targets of the pages whose words are known (targets.ts), by+// page key and box, with the links they were made from.+const targeted = new Map<string, { links: readonly ShownLink[]; targets: PageTarget[] }>()++// A page's click targets once its words are known (undefined: not yet), made once.+export function knownTargets(d: Drawn, page: number, links: readonly ShownLink[]): PageTarget[] | undefined {+ const words = probed.get(pageKey(d, page))+ const box = d.pages[page]+ if (!words || !box) return undefined+ const key = `${pageKey(d, page)}|${box.columns}x${box.rows}`+ const kept = targeted.get(key)+ if (kept?.links === links) return kept.targets+ const targets = targetsOf(words, box, links)+ keep(targeted, key, { links, targets }, PROBED_KEPT)+ return targets+}+// Forgets the pages probed (for tests).export function forgetProbed() {probed.clear()inflight.clear()+ targeted.clear()}diff --git a/hooks/lib/select.ts b/hooks/lib/select.tsindex 566d122..30fb6e6 100644--- a/hooks/lib/select.ts+++ b/hooks/lib/select.ts@@ -13,15 +13,20 @@ import { compareVersions } from './updates'import { joinSegments, pageTopsOf, textOfRun, type Drawn, type Item, type RunLine, type TextBlock } from './copy'import { endFold, foldNew, FRAME_MS, pokeFold, showSelection, startFold } from './blit'import { clockAfter, clockEvery, uiSelection } from './api'+import { targetAt, type PageTarget } from './targets'+import type { ShownLink } from './draw'export type Point = { x: number; y: number }-export type SelectPhase = 'down' | 'move' | 'up' | 'clear'+export type SelectPhase = 'down' | 'move' | 'up' | 'clear' | 'hover' | 'leave'// A post of the Client (hooks/sel.tsx): the drawing's id (drawnAnswers),// the page whose region posted, the anchor (where the button went down)// and the head (the pointer now) in that region's cells, and the post's// order (one count for every instance). `size`: the region's columns and-// rows as the Client has them (for the trace).-export type SelectPost = { id: string; page: number; anchor: Point; head: Point; phase: SelectPhase; seq: number; size?: Box }+// rows as the Client has them (for the trace). A hover (the pointer with no+// button down; anchor and head its cell) or a leave carries the up or clear+// posted before it (`end`): a later post of one frame replaces an earlier+// one.+export type SelectPost = { id: string; page: number; anchor: Point; head: Point; phase: SelectPhase; seq: number; size?: Box; end?: SelectPost }// The selection: anchor and head in the drawing's rows (the page tops// added), `isUp` once the button came up.export type Selection = { id: string; anchor: Point; head: Point; isUp: boolean }@@ -34,6 +39,19 @@ type Box = { columns: number; rows: number }// post taken, and a Client that failed (`isBroken`: no select until a reload).export const picked = { now: null as Selection | null, seq: 0, isBroken: false }+// The hover: the cell under the pointer with no button down (`at`, null:+// off the pictures) and the target tinted now (`lit`: its drawing, page,+// index in the page's targets and cells; null: none). The tint shows only+// while no selection does, through the selection's blits.+export type Hover = { id: string; page: number; x: number; y: number }+export type Lit = { id: string; page: number; index: number; rows: SelRow[] }+export const hovered = { at: null as Hover | null, lit: null as Lit | null }++// Each drawing's links when its pages take picture select (drawPages: its+// link rows are then not drawn), by its id (the RESULTS_KEPT drawn last):+// the files a click copies.+export const clickLinks = new Map<string, readonly ShownLink[]>()+// Shows the selection now on the pages (blit.ts), at most once a frame: the// posts between fold into one, the newest.let fold = foldNew()@@ -51,22 +69,41 @@ async function runSelection($: EngineInterface) {if (endFold(fold) || again) redrawSelection($)}-// The selection's drawing, its pages and their selected rows (none: null).-function selectedNow() {+// The selection's drawing, its pages and their selected rows; with no+// selection, the hovered target's (none: null).+export function selectedNow() {const sel = picked.now- const d = sel ? drawnAnswers.get(sel.id) : undefined- return sel && d ? { id: sel.id, pages: d.pages, rows: selectedRows(sel, d.pages) } : null+ if (sel) {+ const d = drawnAnswers.get(sel.id)+ return d ? { id: sel.id, pages: d.pages, rows: selectedRows(sel, d.pages) } : null+ }+ const lit = hovered.lit+ const d = lit ? drawnAnswers.get(lit.id) : undefined+ return lit && d ? { id: lit.id, pages: d.pages, rows: d.pages.map((_, i) => (i === lit.page ? lit.rows : [])) } : null}-// Forgets the fold, the selection and the native watch (for tests).+// Forgets the fold, the selection, the hover and the native watch (for tests).export function forgetRedraws() {fold = foldNew()stopNative()picked.now = nullpicked.seq = 0picked.isBroken = false+ hovered.at = null+ hovered.lit = null+ clickLinks.clear()}+// The target under a hover, tinted (null: none).+export function litOf(at: Hover, targets: readonly PageTarget[]): Lit | null {+ const index = targetAt(targets, at.x, at.y)+ const t = targets[index]+ return t ? { id: at.id, page: at.page, index, rows: t.rows } : null+}++// Whether two tints are the same target (its cells by reference: one page's targets are kept).+export const sameLit = (a: Lit | null, b: Lit | null) => a === b || (!!a && !!b && a.id === b.id && a.page === b.page && a.index === b.index && a.rows === b.rows)+// A native selection (Claude Code's own) made while a picture selection// shows takes ours down (`clear`): no event says so, so `$.ui.selection()`// is read every NATIVE_POLL_MS while ours shows, one timer at most. Its@@ -111,17 +148,21 @@ const pointOf = (v: unknown): Point | null => {return p && isInt(p.x) && isInt(p.y) ? { x: p.x, y: p.y } : null}+const PHASES: readonly unknown[] = ['down', 'move', 'up', 'clear', 'hover', 'leave'] satisfies SelectPhase[]+// A Client's post as a SelectPost; null when it is not one (data from code).-export function postOf(data: unknown): SelectPost | null {+// Its `end` only as an up or a clear (with no end of its own).+export function postOf(data: unknown, isEnd = false): SelectPost | null {const d = data as Partial<Record<keyof SelectPost, unknown>> | nullif (!d || typeof d !== 'object' || typeof d.id !== 'string' || !isInt(d.page) || d.page < 0 || !isInt(d.seq)) return nullconst anchor = pointOf(d.anchor)const head = pointOf(d.head)- const phase = d.phase- if (!anchor || !head || (phase !== 'down' && phase !== 'move' && phase !== 'up' && phase !== 'clear')) return null+ const phase = d.phase as SelectPhase+ if (!anchor || !head || !PHASES.includes(phase) || (isEnd && phase !== 'up' && phase !== 'clear')) return nullconst size = d.size as Partial<Box> | null | undefinedconst known = size && isInt(size.columns) && isInt(size.rows) ? { size: { columns: size.columns, rows: size.rows } } : {}- return { id: d.id, page: d.page, anchor, head, phase, seq: d.seq, ...known }+ const end = !isEnd && (phase === 'hover' || phase === 'leave') && d.end ? postOf(d.end, true) : null+ return { id: d.id, page: d.page, anchor, head, phase, seq: d.seq, ...known, ...(end ? { end } : {}) }}// The row each page starts at in its drawing (the pages one under the other).@@ -132,10 +173,11 @@ export function topsOf(pages: readonly Box[]): number[] {// The selection after a post: a down, a move or an up selects from its// anchor to its head (a down on another picture drops the old one); a-// clear (a click with no drag) leaves none. `tops`: the drawing's page tops.+// clear (a click with no drag) leaves none, and a hover or a leave (no+// drag) none either. `tops`: the drawing's page tops.export function selectionAfter(post: SelectPost, tops: readonly number[]): Selection | null {const top = tops[post.page]- if (post.phase === 'clear' || top === undefined) return null+ if (post.phase === 'clear' || post.phase === 'hover' || post.phase === 'leave' || top === undefined) return nullconst at = (p: Point) => ({ x: p.x, y: p.y + top })return { id: post.id, anchor: at(post.anchor), head: at(post.head), isUp: post.phase === 'up' }}diff --git a/hooks/lib/targets.ts b/hooks/lib/targets.tsnew file mode 100644index 0000000..99aa04d--- /dev/null+++ b/hooks/lib/targets.ts@@ -0,0 +1,104 @@+// Click targets (pure): the web links, files and commands drawn on a page of+// a picture, and the cells each takes, from the page's probed words (copy.ts:+// a word's `href` and `code`) and the drawing's resolved links (only files+// that exist, by their label). Code blocks are no targets: inline code is+// (a command to copy).+import { joinItems, type Item } from './copy'+import type { ShownLink } from './draw'+import { fileOf, trimUrl } from './links'+import type { PageWords } from './probe'+import type { SelRow } from './select'++export type Target = { kind: 'web'; href: string } | { kind: 'file'; path: string } | { kind: 'command'; text: string }+// One target on one page: what it does, and its cells on that page (the cells whose centre test matches+// textOfRun's rule: a word is in a cell when its box centre is in it; a target covers, on each of its rows,+// the columns from its first word's left cell to its last word's right cell).+export type PageTarget = { target: Target; rows: SelRow[] }++type Page = { width: number; height: number; columns: number; rows: number }++const isWeb = (url: string) => /^(https?:\/\/|mailto:)/i.test(url)+// The punctuation a bare word may have around a path or a URL.+const LEAD = /^[([{<"'*_]+/+const TRAIL = /[)\]}>"'*_.,;:!?]+$/++// The cells of some items on a page, row by row (SelRow: inclusive+// columns). A word takes the cells whose centres are in its box (at least+// the one its centre is in).+function rowsOf(items: readonly Item[], page: Page): SelRow[] {+ const colW = page.width / page.columns+ const rowH = page.height / page.rows+ const clamp = (c: number) => Math.min(page.columns - 1, Math.max(0, c))+ const col = (x: number) => clamp(Math.floor(x / colW))+ const rows = new Map<number, SelRow>()+ for (const item of items) {+ const row = Math.floor((item.y0 + item.y1) / 2 / rowH)+ if (row < 0 || row >= page.rows) continue+ const mid = col((item.x0 + item.x1) / 2)+ const x0 = Math.min(mid, clamp(Math.ceil(item.x0 / colW - 0.5)))+ const x1 = Math.max(mid, clamp(Math.floor(item.x1 / colW - 0.5)))+ const had = rows.get(row)+ rows.set(row, had ? { row, x0: Math.min(had.x0, x0), x1: Math.max(had.x1, x1) } : { row, x0, x1 })+ }+ return [...rows.values()].sort((a, b) => a.row - b.row)+}++// A file's target: the ShownLink of kind file with that label (it exists).+function fileTarget(label: string, links: readonly ShownLink[]): Target | null {+ const link = links.find(l => l.kind === 'file' && l.label === label)+ return link?.kind === 'file' ? { kind: 'file', path: link.path } : null+}++// The target of a bare token (words with no space between, not in a link or+// code): a URL (trimmed as links.ts does) or a file path that exists.+function bareTarget(token: string, links: readonly ShownLink[]): Target | null {+ const text = token.replace(LEAD, '')+ if (/^https?:\/\/\S/i.test(text)) return { kind: 'web', href: trimUrl(text) }+ const path = text.replace(TRAIL, '')+ return fileOf(path, true) ? fileTarget(path, links) : null+}++// The page's targets in document order. Consecutive words with the same+// link URL are one web target (a URL only); the words of one inline code a+// file that exists, else a command (its text, less a `! ` before it); a code block none; a bare URL+// or file path one target over its words (pieces with no space between, as+// the copy joins them).+export function targetsOf(words: PageWords, page: Page, links: readonly ShownLink[]): PageTarget[] {+ const { items } = words+ const out: PageTarget[] = []+ const add = (target: Target | null, of: readonly Item[]) => {+ const rows = target ? rowsOf(of, page) : []+ if (target && rows.length) out.push({ target, rows })+ }+ // Whether `b` goes on the same token as `a` (no space between, as joinItems joins them).+ const joins = (a: Item, b: Item) =>+ a.block === b.block && !a.adv && !b.adv && joinItems([{ item: a, text: a.text }, { item: b, text: b.text }], []) === a.text + b.text+ let i = 0+ while (i < items.length) {+ const item = items[i]!+ let j = i + 1+ if (item.adv) {+ while (j < items.length && items[j]!.adv && items[j]!.block === item.block) j+++ } else if (item.href) {+ while (j < items.length && items[j]!.href === item.href) j+++ const href = item.href+ const path = href.replace(/^file:\/\//i, '').replace(/[?#].*$/, '')+ add(isWeb(href) ? { kind: 'web', href } : fileOf(path) ? fileTarget(path, links) : null, items.slice(i, j))+ } else if (item.code) {+ while (j < items.length && !items[j]!.href && items[j]!.code === item.code) j+++ const code = item.code.replace(/\s+/g, ' ').trim()+ add((fileOf(code) && fileTarget(code, links)) || { kind: 'command', text: code.replace(/^!\s+(?=\S)/, '') }, items.slice(i, j))+ } else {+ while (j < items.length && !items[j]!.href && !items[j]!.code && joins(items[j - 1]!, items[j]!)) j+++ const token = items.slice(i, j)+ add(bareTarget(token.map(w => w.text).join(''), links), token)+ }+ i = j+ }+ return out+}++// The index of the target whose cells hold (x, y) in page cells, or -1.+export function targetAt(targets: readonly PageTarget[], x: number, y: number): number {+ return targets.findIndex(t => t.rows.some(r => r.row === y && x >= r.x0 && x <= r.x1))+}diff --git a/hooks/register.tsx b/hooks/register.tsxindex f278dc9..811ee3a 100644--- a/hooks/register.tsx+++ b/hooks/register.tsx@@ -32,15 +32,17 @@ import { commandSuggestions, parseCommand, registerCommand } from './lib/commandimport { runSetup } from './lib/setup'import { pollHost, PROBE_RUNS, probeOsc11, showMode, USE_OSC11, watchHost } from './lib/host'import { measureFonts } from './lib/typst'-import { drawPages, linksFor, type ShownLink } from './lib/draw'+import { drawPages, linkRowsOf, linksFor, takesSelect, type ShownLink } from './lib/draw'import {- needsSelect, picked, postOf, redrawSelection, runsOf, selectedRows, selectionAfter, selectTrace, stopNative, textOfRuns, topsOf, watchNative, type SelectPost, type Selection,+ clickLinks, hovered, litOf, needsSelect, picked, postOf, redrawSelection, runsOf, sameLit, selectedRows, selectionAfter, selectTrace, stopNative, textOfRuns,+ topsOf, watchNative, type Hover, type SelectPost, type Selection,} from './lib/select'+import { targetAt, type Target } from './lib/targets'import { blits, selectColor } from './lib/blit'import { forgetPages, needFrames, notePages } from './lib/pagecache'import { traceDebug } from './lib/log'import { finalizeAll } from './lib/stream'-import { knownWords, noteDrawn, noteDrawnAgain, noteOnScreen, wordsOf, type PageWords } from './lib/probe'+import { knownTargets, knownWords, noteDrawn, noteDrawnAgain, noteOnScreen, wordsOf, type PageWords } from './lib/probe'import { codePointsOf, decodeSelection, hasPlaceholders, joinSegments, pageTopsOf, pickPages, textOfRun, type Drawn, type Pick, type Segment } from './lib/copy'import { pagesOf, type Drawing } from './lib/answer'import { clipboardNow, clipWatchArgs, clipWayReady, hintText } from './lib/clipboard'@@ -91,6 +93,7 @@ export { nextJob } from './lib/stream'export * from './lib/images'export { rowsAfter, type Under } from './lib/pictures'export * from './lib/copy'+export { targetAt, targetsOf, type PageTarget, type Target } from './lib/targets'export { CLIP_TOOLS, clipToolsOf, clipWayOf, FIND_SH, GTK_READ_PY, GTK_WATCH_PY, hintText, WL_WATCH_SH, X11_WATCH_SH, type ClipTool, type ClipWay } from './lib/clipboard'export {agoText, checkedOf, compareVersions, isDue, isNewer, parseVersion, shouldTell, toldOf, UPDATE_EVERY_MS, UPDATE_FETCH_MS, UPDATE_STEPS, UPDATE_TOAST_MS,@@ -162,9 +165,10 @@ const stampOf = (ready: { env: Env; done: number }, view?: RenderViewport) =>// `text` the row's text (a string kept as given, so the compare is mostly// one pointer), `extra` its other inputs.type Memo<T> = { text: string; extra: string; stamp: string; onScreen: boolean | undefined; value: T }-// An answer's tree is kept with its link rows (the copy counts them under-// its pages), a plan's drawing with its link rows.-type AnswerMemo = { tree: RenderElement; links: readonly ShownLink[] }+// An answer's tree is kept with the link rows drawn under its pages (the+// copy counts them; none where they take picture select), a plan's drawing+// with its link rows.+type AnswerMemo = { tree: RenderElement; after: number }const answers = new Map<string, Memo<AnswerMemo>>()const plans = new Map<string, Memo<{ drawing: Drawing; links: ShownLink[] }>>()const unders = new Map<string, Memo<Under[]>>()@@ -440,18 +444,30 @@ async function dump($: EngineInterface, on: boolean): Promise<string> {// A Client's post: the selection after it, shown (once a frame at most, the// newest selection). A down puts its page first in the cache (lib/pagecache.ts)// and probes its words if they are not there, for the drag's frames and the-// copy at the up, and lets a page whose blit was refused try again. A down-// is always taken (a reloaded sel.tsx counts from 0 again).+// copy at the up, lets a page whose blit was refused try again, and takes+// the hover's tint down. A down is always taken (a reloaded sel.tsx counts+// from 0 again). A hover or a leave moves the tint (hoverAt), after the up+// or clear it carries; a clear (a click) on a target copies it.function onSelect($: EngineInterface, post: SelectPost, surface: RenderSurface) {+ if (post.end) onSelect($, post.end, surface)if (post.seq <= picked.seq && post.phase !== 'down') returnpicked.seq = post.seqconst d = drawnAnswers.get(post.id)+ if (post.phase === 'hover' || post.phase === 'leave') {+ // A leave of a page the pointer is no longer on (it is on another page) changes nothing.+ const at = hovered.at+ if (post.phase === 'leave' && at && (at.id !== post.id || at.page !== post.page)) return+ hoverAt($, post.phase === 'hover' && d ? { id: post.id, page: post.page, x: post.head.x, y: post.head.y } : null)+ return+ }const was = picked.nowpicked.now = d ? selectionAfter(post, topsOf(d.pages)) : nullif (S.debug) traceDebug($, selectTrace(post, d, picked.now))const page = d?.pages[post.page]if (post.phase === 'down') {blits.refused.clear()+ hovered.at = null+ hovered.lit = nullif (d && page && S.env) {void needFrames($, page, selectColor(S.theme), { id: d.id, index: post.page, seq: d.seq }).catch(() => undefined)void wordsOf($, d, post.page).catch(() => undefined)@@ -461,6 +477,66 @@ function onSelect($: EngineInterface, post: SelectPost, surface: RenderSurface)watchNative($, () => clearSelection($))// The copy waits for the page's words when they are not there: the next posts do not.if (post.phase === 'up' && d && picked.now) void copySelection($, d, picked.now, surface).catch(() => undefined)+ if (post.phase === 'clear' && d) {+ void clickAt($, d, post, surface).catch(() => undefined)+ // The pointer is still there: its target tinted again.+ hoverAt($, { id: post.id, page: post.page, x: post.head.x, y: post.head.y })+ }+}++// No links of a drawing known (its pages drawn with no picture select yet).+const NO_LINKS: readonly ShownLink[] = []++// The pointer over a page with no button down (null: off it): the target+// under it tinted, while no selection shows. A new page's words are probed+// when they are not known (the tint once they are); the tint's blit asks for+// the page's frames (needFrames), as a down does.+function hoverAt($: EngineInterface, at: Hover | null) {+ const was = hovered.at+ hovered.at = at+ const d = at ? drawnAnswers.get(at.id) : undefined+ if (at && d && (was?.id !== at.id || was.page !== at.page) && !knownWords(d, at.page)) {+ void wordsOf($, d, at.page).then(() => lightHover($), () => undefined)+ }+ lightHover($)+}++// The hover's target tinted (none while a selection shows), redrawn when it changed.+function lightHover($: EngineInterface) {+ const at = hovered.at+ const d = at ? drawnAnswers.get(at.id) : undefined+ const targets = at && d && !picked.now ? knownTargets(d, at.page, clickLinks.get(at.id) ?? NO_LINKS) : undefined+ const lit = at && targets ? litOf(at, targets) : null+ if (sameLit(lit, hovered.lit)) return+ hovered.lit = lit+ if (S.debug) traceDebug($, lit ? `select: hover ${lit.id} page ${lit.page} target ${lit.index} (${targets?.[lit.index]?.target.kind}) rows ${lit.rows.map(r => `${r.row}:${r.x0}-${r.x1}`).join(',')}` : 'select: hover none')+ redrawSelection($)+}++// A click (a clear) on a target of the page copies its text (a link's URL,+// a file's path, a command). The page's words are probed first when they+// are not known.+async function clickAt($: EngineInterface, d: Drawn & { job?: Job }, post: SelectPost, surface: RenderSurface) {+ const links = () => clickLinks.get(d.id) ?? NO_LINKS+ let targets = knownTargets(d, post.page, links())+ if (!targets) {+ await wordsOf($, d, post.page)+ targets = knownTargets(d, post.page, links())+ }+ const target = targets?.[targetAt(targets, post.anchor.x, post.anchor.y)]?.target+ if (S.debug) traceDebug($, `select: click ${d.id} page ${post.page} at ${post.anchor.x},${post.anchor.y} target ${target ? target.kind : 'none'}`)+ if (target) await copyTarget($, target, surface)+}++// A target's text on the clipboard (clickAt), with its toast.+async function copyTarget($: EngineInterface, target: Target, surface: RenderSurface) {+ const text = target.kind === 'web' ? target.href : target.kind === 'file' ? target.path : target.text+ const name = target.kind === 'web' ? 'link' : target.kind === 'file' ? 'path' : 'command'+ // The clipboard change of this text is not read again.+ clip.wrote = text+ clip.seen = text+ const copied = await uiCopy($, { text, surface })+ uiToast($, copied.isCopied ? `Intelligent UI: copied the ${name}` : `Intelligent UI: the copy failed: ${copied.reason}`)}// The text of a selection's cells, page by page, as a copy of those cells@@ -522,12 +598,14 @@ function selectState(): string {return S.isFullscreen === null ? 'on in fullscreen (the screen is not known yet)' : 'on'}-// No selection drawn (a new turn, typing in the prompt, a native-// selection, Intelligent UI or select off).+// No selection drawn, and no hover tint (a new turn, typing in the prompt,+// a native selection, Intelligent UI or select off).function clearSelection($: EngineInterface) {stopNative()- if (!picked.now) return+ hovered.at = null+ if (!picked.now && !hovered.lit) returnpicked.now = null+ hovered.lit = nullredrawSelection($)}@@ -854,7 +932,7 @@ export const register: Register = on => {// under them; the rows on screen at each draw, a memo hit too.if (kept) {noteCopy($, e.requestId, () => {- noteDrawnAgain(e.requestId, roomColumns(e.viewport), { top: MARGIN_TOP, after: kept.links.length })+ noteDrawnAgain(e.requestId, roomColumns(e.viewport), { top: MARGIN_TOP, after: kept.after })noteOnScreen(e.requestId, e.props.onScreen)})return kept.tree@@ -864,11 +942,12 @@ export const register: Register = on => {const links = await linksFor($, e.props.text, ready.env.cwd)const tree = drawPages($, e, drawing.result, drawing.bytes, { bullet, links, id: e.requestId })const { result } = drawing+ const after = linkRowsOf(links, takesSelect($, e, drawing.bytes))noteCopy($, e.requestId, () => {- noteDrawn(e.requestId, result, roomColumns(e.viewport), { top: MARGIN_TOP, after: links.length })+ noteDrawn(e.requestId, result, roomColumns(e.viewport), { top: MARGIN_TOP, after })noteOnScreen(e.requestId, e.props.onScreen)})- memoSet(answers, e.requestId, k, { tree, links })+ memoSet(answers, e.requestId, k, { tree, after })return tree}answers.delete(e.requestId)@@ -896,15 +975,17 @@ export const register: Register = on => {const k = { text: files.map(f => `${f.kind}:${f.path}`).join('\n'), extra: pdfPagesOf(id, files), stamp: stampOf(ready, e.viewport), onScreen }// Its jobs: one per Markdown file (pagesOf's id `file:<id>:<path>`).const kept = memoOf(unders, id, k, requestId => requestId.startsWith(`file:${id}:`))- // Each Markdown file's pages with the rows drawn after them (rowsAfter)- // and the row's rows on screen, at each draw.+ // Each Markdown file's pages with the rows drawn after them (rowsAfter:+ // no link rows where they take picture select) and the row's rows on+ // screen, at each draw.const room = roomColumns(e.viewport)+ const isSelect = takesSelect($, e)if (kept) {under = keptkept.forEach((u, i) => {if (!('drawing' in u)) returnnoteCopy($, u.id, () => {- noteDrawnAgain(u.id, room, { after: rowsAfter(kept, i, room) })+ noteDrawnAgain(u.id, room, { after: rowsAfter(kept, i, room, isSelect) })noteOnScreen(u.id, e.props.onScreen)})})@@ -917,7 +998,7 @@ export const register: Register = on => {if (!('drawing' in u) || u.drawing.kind !== 'pages') returnconst { result } = u.drawingnoteCopy($, u.id, () => {- noteDrawn(u.id, result, room, { after: rowsAfter(drawn, i, room) })+ noteDrawn(u.id, result, room, { after: rowsAfter(drawn, i, room, isSelect) })noteOnScreen(u.id, e.props.onScreen)})})@@ -1001,12 +1082,13 @@ export const register: Register = on => {// Its pages can be copied as an answer's, by the call's id (the row's// requestId can be an answer's own). The engine's row is above them:// their place is read from the bottom (pageTopsOf), under them its- // link rows.+ // link rows (none where they take picture select).if (drawing.kind === 'pages') {const { result } = drawingconst id = `plan:${e.props.tool_use_id}`+ const after = linkRowsOf(links, takesSelect($, e, drawing.bytes))noteCopy($, id, () => {- noteDrawn(id, result, roomColumns(e.viewport), { after: links.length })+ noteDrawn(id, result, roomColumns(e.viewport), { after })noteOnScreen(id, e.props.onScreen)})}diff --git a/hooks/sel.tsx b/hooks/sel.tsxindex b2ae77b..86c6ec3 100644--- a/hooks/sel.tsx+++ b/hooks/sel.tsx@@ -1,45 +1,64 @@// Picture select's Client (lib/select.ts): one over each page of a picture,// in the cells of that page. It takes the pointer and posts the selection// whole (anchor, head, phase and order), never a bare event: posts of one-// frame merge, the last one kept. A click with no drag posts `clear`. It-// draws only an empty Box: anything drawn would blank the picture's cells.-// It sets no key listener: with one, a click would give it the keys (the-// prompt would get none until Escape), and Escape never reaches it.+// frame merge, the last one kept. A click with no drag posts `clear`. With+// no button down, a move to a new cell posts `hover` and a leave `leave`;+// each carries the last up or clear (`end`), which it may replace. It draws+// only an empty Box: anything drawn would blank the picture's cells. It sets+// no key listener: with one, a click would give it the keys (the prompt+// would get none until Escape), and Escape never reaches it.import type { ClientModule, JsonValue } from 'claude-code'type Props = { id: string; page: number }-type Drag = { ax: number; ay: number; hx: number; hy: number; isDown: boolean }+// The drag (anchor, head, the button down), the cell of the last hover post+// ('' none) and the last up or clear posted.+type Drag = { ax: number; ay: number; hx: number; hy: number; isDown: boolean; over?: string; end?: JsonValue }+type Phase = 'down' | 'move' | 'up' | 'clear' | 'hover' | 'leave'// The posts' order, one count for every instance (the module is shared).let seq = 0const Select: ClientModule<Props, Drag> = (props, surface) => {const { Box } = surface.elements- const post = (d: Drag, phase: 'down' | 'move' | 'up' | 'clear') => {+ const dataOf = (d: Drag, phase: Phase): JsonValue => {const size = { columns: surface.columns, rows: surface.rows }- const data: JsonValue = { id: props.id, page: props.page, anchor: { x: d.ax, y: d.ay }, head: { x: d.hx, y: d.hy }, phase, seq: ++seq, size }+ const data: Record<string, JsonValue> = { id: props.id, page: props.page, anchor: { x: d.ax, y: d.ay }, head: { x: d.hx, y: d.hy }, phase, seq: ++seq, size }+ if ((phase === 'hover' || phase === 'leave') && d.end) data.end = d.end+ return data+ }+ // Posts the drag at `phase` and keeps it as the state; an up or a clear is kept with it (`end`).+ const post = (d: Drag, phase: Phase) => {+ const data = dataOf(d, phase)+ surface.setState(phase === 'up' || phase === 'clear' ? { ...d, end: data } : d)surface.post(data)}surface.onPointer(ev => {const now = surface.stateif (ev.type === 'down') {if (ev.button && ev.button !== 'left') return- const next = { ax: ev.x, ay: ev.y, hx: ev.x, hy: ev.y, isDown: true }- surface.setState(next)- post(next, 'down')+ post({ ax: ev.x, ay: ev.y, hx: ev.x, hy: ev.y, isDown: true }, 'down')+ return+ }+ if (!now?.isDown) {+ // No button down: a hover at each new cell, a leave once.+ const idle: Drag = now ?? { ax: ev.x, ay: ev.y, hx: ev.x, hy: ev.y, isDown: false }+ if (ev.type === 'move' && !ev.button) {+ const cell = `${ev.x},${ev.y}`+ if (idle.over === cell) return+ post({ ...idle, ax: ev.x, ay: ev.y, hx: ev.x, hy: ev.y, over: cell }, 'hover')+ } else if (ev.type === 'leave' && idle.over) post({ ...idle, over: '' }, 'leave')return}- if (!now?.isDown || (ev.type !== 'move' && ev.type !== 'up')) return+ if (ev.type !== 'move' && ev.type !== 'up') return// A move with no button while down: its up was lost, so the drag ends where it was.+ // The cell of an end counts as hovered (the hooks tint a click's target again).if (ev.type === 'move' && !ev.button) {- const ended = { ...now, isDown: false }- surface.setState(ended)+ const ended = { ...now, isDown: false, over: `${now.hx},${now.hy}` }post(ended, ended.hx === ended.ax && ended.hy === ended.ay ? 'clear' : 'up')return}- const next = { ...now, hx: ev.x, hy: ev.y, isDown: ev.type === 'move' }+ const next = { ...now, hx: ev.x, hy: ev.y, isDown: ev.type === 'move', ...(ev.type === 'up' ? { over: `${ev.x},${ev.y}` } : {}) }if (ev.type === 'move' && next.hx === now.hx && next.hy === now.hy) return- surface.setState(next)post(next, ev.type === 'move' ? 'move' : next.hx === next.ax && next.hy === next.ay ? 'clear' : 'up')})return <Box width={surface.columns || undefined} height={surface.rows || undefined} />diff --git a/render/md.typ b/render/md.typindex 24848b4..3dfd00c 100644--- a/render/md.typ+++ b/render/md.typ@@ -524,7 +524,8 @@// its characters (clusters) is a word, boxed, `g` on all but the// first (they join with no space).// A word of inline code has `pad`, the theme's padding beside the-// code, when it is not 0.+// code, when it is not 0, and `code`, the whole text of that code.+// A word in a link to a URL (a string) has `href`, the URL.// c: a block code line: x its start, y its baseline, a and d the code// font's ascender and descender, w its width, n its characters.// b: a block starts: paragraph, heading, code block, quote, table cell@@ -552,6 +553,9 @@// (`pad`: a copy takes it off the gap to the text next to it).#let in-inline-code(costs) = costs.orphan == 104%#let cjk = regex("[\\p{Han}\\p{Hiragana}\\p{Katakana}\\p{Hangul}]")+// The URL of the link and the text of the inline code the text is in.+#let probe-href = state("probe-href", none)+#let probe-code = state("probe-code", none)#let probe-rules(body) = {// A word is cut after a hyphen or a slash, where a line may break; a// token of 30+ characters is one word (it breaks anywhere, see above).@@ -560,6 +564,11 @@let t = it.textlet pad = E.inline-code.pad-x-px * pxlet pad = if in-inline-code(text.costs) and pad > 0pt { (pad: pad / 1pt) } else { (:) }+ let tags = pad+ let href = probe-href.get()+ if href != none { tags.insert("href", href) }+ let code = if in-inline-code(text.costs) { probe-code.get() }+ if code != none { tags.insert("code", code) }if t.clusters().len() >= 30 or t.match(cjk) != none {// A long word or CJK text breaks anywhere: a box for each character// (a line may break between boxes, as at the long-word rule's zws).@@ -567,12 +576,12 @@// with all the marks after it.for (i, c) in t.clusters().enumerate() {let one = measure(c)- box({ mark("w", t: c, w: one.width / 1pt, h: one.height / 1pt, ..pad, ..if i > 0 { (g: 1) } else { (:) }); c })+ box({ mark("w", t: c, w: one.width / 1pt, h: one.height / 1pt, ..tags, ..if i > 0 { (g: 1) } else { (:) }); c })}} else {// Boxed, so the mark is where the word is drawn (a bare mark at the// start of a wrapped line stays at the end of the line above).- box({ mark("w", t: t, w: size.width / 1pt, h: size.height / 1pt, ..pad); it })+ box({ mark("w", t: t, w: size.width / 1pt, h: size.height / 1pt, ..tags); it })}}// A code line: a zero-size box at its start (its y is the baseline). An@@ -589,7 +598,8 @@it}show math.equation: set text(costs: (orphan: 102%))- show raw.where(block: false): it => context if no-marks(text.costs) { it } else { set text(costs: (orphan: 104%)); it }+ show raw.where(block: false): it => context if no-marks(text.costs) { it } else { set text(costs: (orphan: 104%)); probe-code.update(it.text); it }+ show link: it => if type(it.dest) != str { it } else { probe-href.update(it.dest); it; probe-href.update(none) }show par: it => { mark("b", kind: "par"); it }show heading: it => { mark("b", kind: "heading"); it }show quote.where(block: true): it => { mark("b", kind: "quote"); it }diff --git a/tests/copy-fixture.ts b/tests/copy-fixture.tsindex 8f61dc6..c5042bd 100644--- a/tests/copy-fixture.ts+++ b/tests/copy-fixture.ts@@ -316,3 +316,80 @@ export const LONG_MARKS = [{"k": "w", "p": 1, "x": 543.5224609375, "y": 74.320859375, "s": 11.0, "t": "x", "w": 5.7685546875, "h": 13.126953125, "g": 1},{"k": "w", "p": 1, "x": 0.0, "y": 91.6278125, "s": 11.0, "t": "end.", "w": 22.72509765625, "h": 13.126953125},] as const++// The same probe (same inputs, page=1) for links, inline code, a bare URL+// and path, and a bash block: the words in a link have `href`, those of+// inline code `code`. Its PNG is 1568 x+// 416 px, 13 rows.+export const TARGETS_MD = "## Targets\n\nSee [the docs](https://example.com) and https://typst.app/docs/reference. Run `! ls -la` here.\n\nOpen `src/a.ts` or the bare path hooks/lib/copy.ts now, and [top](#targets).\n\n```bash\necho hello\nls -la\n```\n"++export const TARGETS_PAGE = { width: 1568, height: 416, columns: 98, rows: 13 }++export const TARGETS_MARKS = [+ {"k": "b", "p": 1, "x": 0.0, "y": 4.36, "s": 13.2, "kind": "heading"},+ {"k": "w", "p": 1, "x": 0.0, "y": 4.36, "s": 19.8, "t": "Targets", "w": 73.11884765625, "h": 23.628515625000002},+ {"k": "b", "p": 1, "x": 0.0, "y": 38.988515625000005, "s": 11.0, "kind": "par"},+ {"k": "w", "p": 1, "x": 0.0, "y": 38.988515625000005, "s": 11.0, "t": "See", "w": 19.57763671875, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 22.67138671875, "y": 38.988515625000005, "s": 11.0, "t": "the", "w": 16.75244140625, "h": 13.126953125, "href": "https://example.com"},+ {"k": "w", "p": 1, "x": 42.517578125, "y": 38.988515625000005, "s": 11.0, "t": "docs", "w": 25.1689453125, "h": 13.126953125, "href": "https://example.com"},+ {"k": "w", "p": 1, "x": 70.7802734375, "y": 38.988515625000005, "s": 11.0, "t": "and", "w": 19.24462890625, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 93.11865234375, "y": 38.988515625000005, "s": 11.0, "t": "h", "w": 6.47216796875, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 99.5908203125, "y": 38.988515625000005, "s": 11.0, "t": "t", "w": 3.99609375, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 103.5869140625, "y": 38.988515625000005, "s": 11.0, "t": "t", "w": 3.99609375, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 107.5830078125, "y": 38.988515625000005, "s": 11.0, "t": "p", "w": 6.7138671875, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 114.296875, "y": 38.988515625000005, "s": 11.0, "t": "s", "w": 5.7578125, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 120.0546875, "y": 38.988515625000005, "s": 11.0, "t": ":", "w": 3.265625, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 123.3203125, "y": 38.988515625000005, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 126.671875, "y": 38.988515625000005, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 130.0234375, "y": 38.988515625000005, "s": 11.0, "t": "t", "w": 3.99609375, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 134.01953125, "y": 38.988515625000005, "s": 11.0, "t": "y", "w": 5.97265625, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 139.9921875, "y": 38.988515625000005, "s": 11.0, "t": "p", "w": 6.7138671875, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 146.7060546875, "y": 38.988515625000005, "s": 11.0, "t": "s", "w": 5.7578125, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 152.4638671875, "y": 38.988515625000005, "s": 11.0, "t": "t", "w": 3.99609375, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 156.4599609375, "y": 38.988515625000005, "s": 11.0, "t": ".", "w": 3.265625, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 159.7255859375, "y": 38.988515625000005, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 165.794921875, "y": 38.988515625000005, "s": 11.0, "t": "p", "w": 6.7138671875, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 172.5087890625, "y": 38.988515625000005, "s": 11.0, "t": "p", "w": 6.7138671875, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 179.22265625, "y": 38.988515625000005, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 182.57421875, "y": 38.988515625000005, "s": 11.0, "t": "d", "w": 6.7568359375, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 189.3310546875, "y": 38.988515625000005, "s": 11.0, "t": "o", "w": 6.4990234375, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 195.830078125, "y": 38.988515625000005, "s": 11.0, "t": "c", "w": 6.1552734375, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 201.9853515625, "y": 38.988515625000005, "s": 11.0, "t": "s", "w": 5.7578125, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 207.7431640625, "y": 38.988515625000005, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 211.0947265625, "y": 38.988515625000005, "s": 11.0, "t": "r", "w": 4.189453125, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 215.2841796875, "y": 38.988515625000005, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 221.568359375, "y": 38.988515625000005, "s": 11.0, "t": "f", "w": 3.97998046875, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 225.54833984375, "y": 38.988515625000005, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 231.83251953125, "y": 38.988515625000005, "s": 11.0, "t": "r", "w": 4.189453125, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 236.02197265625, "y": 38.988515625000005, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 242.30615234375, "y": 38.988515625000005, "s": 11.0, "t": "n", "w": 6.41845703125, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 248.724609375, "y": 38.988515625000005, "s": 11.0, "t": "c", "w": 6.1552734375, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 254.8798828125, "y": 38.988515625000005, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 261.1640625, "y": 38.988515625000005, "s": 11.0, "t": ".", "w": 3.265625, "h": 13.126953125, "g": 1},+ {"k": "w", "p": 1, "x": 267.5234375, "y": 38.988515625000005, "s": 11.0, "t": "Run", "w": 20.0234375, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 290.640625, "y": 38.988515625000005, "s": 11.0, "t": "\u200d", "w": 0.0, "h": 13.126953125, "code": "! ls -la"},+ {"k": "w", "p": 1, "x": 290.640625, "y": 41.104726562500005, "s": 11.0, "t": "!", "w": 6.62255859375, "h": 11.0, "code": "! ls -la"},+ {"k": "w", "p": 1, "x": 303.8857421875, "y": 41.104726562500005, "s": 11.0, "t": "ls", "w": 13.2451171875, "h": 11.0, "code": "! ls -la"},+ {"k": "w", "p": 1, "x": 323.75341796875, "y": 41.104726562500005, "s": 11.0, "t": "-", "w": 6.62255859375, "h": 11.0, "code": "! ls -la"},+ {"k": "w", "p": 1, "x": 330.3759765625, "y": 41.104726562500005, "s": 11.0, "t": "la", "w": 13.2451171875, "h": 11.0, "code": "! ls -la"},+ {"k": "w", "p": 1, "x": 346.71484375, "y": 38.988515625000005, "s": 11.0, "t": "here.", "w": 26.33447265625, "h": 13.126953125},+ {"k": "b", "p": 1, "x": 0.0, "y": 65.31546875, "s": 11.0, "kind": "par"},+ {"k": "w", "p": 1, "x": 0.0, "y": 65.31546875, "s": 11.0, "t": "Open", "w": 27.90283203125, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 30.99658203125, "y": 65.31546875, "s": 11.0, "t": "\u200d", "w": 0.0, "h": 13.126953125, "code": "src/a.ts"},+ {"k": "w", "p": 1, "x": 30.99658203125, "y": 67.4316796875, "s": 11.0, "t": "src/", "w": 26.490234375, "h": 11.0, "code": "src/a.ts"},+ {"k": "w", "p": 1, "x": 57.48681640625, "y": 67.4316796875, "s": 11.0, "t": "a.ts", "w": 26.490234375, "h": 11.0, "code": "src/a.ts"},+ {"k": "w", "p": 1, "x": 87.07080078125, "y": 65.31546875, "s": 11.0, "t": "or", "w": 10.6884765625, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 100.85302734375, "y": 65.31546875, "s": 11.0, "t": "the", "w": 16.75244140625, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 120.69921875, "y": 65.31546875, "s": 11.0, "t": "bare", "w": 23.138671875, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 146.931640625, "y": 65.31546875, "s": 11.0, "t": "path", "w": 23.25146484375, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 173.27685546875, "y": 65.31546875, "s": 11.0, "t": "hooks/", "w": 34.33740234375, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 207.6142578125, "y": 65.31546875, "s": 11.0, "t": "lib/", "w": 15.6083984375, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 223.22265625, "y": 65.31546875, "s": 11.0, "t": "copy.ts", "w": 37.017578125, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 263.333984375, "y": 65.31546875, "s": 11.0, "t": "now,", "w": 23.68115234375, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 290.10888671875, "y": 65.31546875, "s": 11.0, "t": "and", "w": 19.24462890625, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 312.447265625, "y": 65.31546875, "s": 11.0, "t": "top", "w": 17.12841796875, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 329.57568359375, "y": 65.31546875, "s": 11.0, "t": ".", "w": 3.265625, "h": 13.126953125},+ {"k": "b", "p": 1, "x": 0.0, "y": 91.642421875, "s": 11.0, "kind": "code"},+ {"k": "c", "p": 1, "x": 12.571428571428573, "y": 112.57127232142858, "s": 11.0, "t": "echo hello", "w": 66.2255859375, "n": 10, "a": 8.357421875, "d": 2.642578125},+ {"k": "c", "p": 1, "x": 12.571428571428573, "y": 127.49827232142857, "s": 11.0, "t": "ls -la", "w": 39.7353515625, "n": 6, "a": 8.357421875, "d": 2.642578125},+] as constdiff --git a/tests/copy.test.ts b/tests/copy.test.tsindex 553240e..45816b3 100644--- a/tests/copy.test.ts+++ b/tests/copy.test.ts@@ -16,7 +16,7 @@ import { clip, drawnAnswers, lastKey, results, type Job, type Result } from '../import { forgetBlits, over, rgbOf, WRITE_PL } from '../hooks/lib/blit'import { forgetRedraws } from '../hooks/lib/select'import { chunk, concat, decodePng, deflatePiece, fromBase64, headOf, tailOf, toBase64 } from '../hooks/lib/png'-import { LONG_MARKS, LONG_MD, LONG_PAGE, SMALL_MARKS, SMALL_MD, SMALL_PAGE, SMALL_PPI } from './copy-fixture'+import { LONG_MARKS, LONG_MD, LONG_PAGE, SMALL_MARKS, SMALL_MD, SMALL_PAGE, SMALL_PPI, TARGETS_MARKS, TARGETS_MD } from './copy-fixture'// One screen row of a picture as Claude Code draws it: `lead` (the gutter),// then the cells of `row` from `from` to `to`.@@ -86,6 +86,32 @@ test('probe marks become pixel boxes; a list number is dropped and an item takes])})+test("a word keeps its link's URL and its inline code's text", () => {+ const marks: Mark[] = [+ { k: 'b', p: 1, x: 0, y: 0, kind: 'par' },+ { k: 'w', p: 1, x: 0, y: 0, t: 'docs', w: 10, h: 12, href: 'https://x.io' },+ { k: 'w', p: 1, x: 20, y: 0, t: 'a.ts', w: 10, h: 12, code: 'a.ts', pad: 1 },+ { k: 'b', p: 1, x: 0, y: 20, kind: 'item', prefix: '- ' },+ { k: 'b', p: 1, x: 0, y: 20, kind: 'code' },+ { k: 'c', p: 1, x: 0, y: 30, t: 'ls', w: 12, n: 2, a: 8, d: 2 },+ { k: 'b', p: 1, x: 0, y: 40, kind: 'code' },+ { k: 'c', p: 1, x: 0, y: 50, t: 'x', w: 6, n: 1, a: 8, d: 2 },+ ]+ const got = positionsOf(marks, 72)+ expect(got.blocks).toEqual([+ { kind: 'par', prefix: '', first: 0 },+ { kind: 'item', prefix: '- ', first: 2 },+ { kind: 'code', prefix: '', first: 3 },+ ])+ expect(got.pages[0]!.map(w => [w.text, w.href, w.code])).toEqual([+ ['docs', 'https://x.io', undefined],+ ['a.ts', undefined, 'a.ts'],+ ['ls', undefined, undefined],+ ['x', undefined, undefined],+ ])+ expect(got.pages[0]![1]).toEqual({ i: 1, text: 'a.ts', block: 0, x0: 20, x1: 30, y0: 0, y1: 12, pad: 1, code: 'a.ts' })+})+// A hand-made page: 10 columns of 10 px, 4 rows of 20 px.const PAGE = { width: 100, height: 80, columns: 10, rows: 4 }const word = (i: number, text: string, x0: number, row: number, block: number): Item => ({ i, text, x0, x1: x0 + text.length * 6, y0: row * 20 + 2, y1: row * 20 + 18, block })@@ -507,7 +533,10 @@ const inputsOf = (argv: readonly string[]) => Object.fromEntries(argv.flatMap((a// before each frame write; `refused`: the cache folder sweep refuses that folder.function world(on: any,- o: { failFirst?: boolean; noBridge?: boolean; env?: Record<string, string>; tty?: string; version?: string; deny?: string; noPerl?: boolean; beforeWrite?: () => Promise<void>; refused?: string } = {},+ o: {+ failFirst?: boolean; noBridge?: boolean; env?: Record<string, string>; tty?: string; version?: string; deny?: string; noPerl?: boolean; beforeWrite?: () => Promise<void>+ refused?: string; marks?: readonly object[]+ } = {},) {forgetBlits()forgetRedraws()@@ -590,7 +619,7 @@ function world(queries.push(inputs)if (w.gate) await Promise.race([w.gate, dead])if (killed) return { value: { code: null, signal: 'SIGTERM' } }- yield { stream: 'stdout', text: JSON.stringify(SMALL_MARKS.map(m => ({ ...m, p: Number(inputs.page) }))) }+ yield { stream: 'stdout', text: JSON.stringify((o.marks ?? SMALL_MARKS).map(m => ({ ...m, p: Number(inputs.page) }))) }return { value: { code: 0, signal: null } }})on('process.run', async ($: any, e: any) => {@@ -1667,6 +1696,169 @@ test('picture select: with no perl the first frame write fails, is logged once aexpect(w.copies).toEqual([COPIED, COPIED])})+// ---- Picture select: links, files and commands --------------------------------++// TARGETS_MD drawn as `ans-1` (its probe the fixture's TARGETS_MARKS), with+// src/a.ts a file in the session's folder /w. Its targets (targets.test.ts):+// the link "the docs" row 3 columns 4 to 11, the bare URL row 3 16 to 45,+// `! ls -la` row 4 50 to 58, src/a.ts row 6 5 to 13 (the bash block rows 9 and 10: no target).+async function drawTargets($: any, on: any, o: { env?: Record<string, string> } = {}, isFullscreen: boolean | null = true) {+ const w = world(on, { tty: TTY, marks: TARGETS_MARKS, ...o })+ on('session.cwd', async () => ({ value: '/w' }))+ on('fs.exists', async ($: any, e: any) => ({ value: e.path === '/w/src/a.ts' }))+ await $.command.run({ command: 'iui', args: '' } as any)+ const ui = await drawAnswer($, w, 'ans-1', TARGETS_MD, isFullscreen)+ await settle(w)+ return { w, ui }+}+const hover = (ui: any, x: number, y: number) => ui.pointer({ type: 'move', x, y, in: 'sel0' })+const click = async (ui: any, x: number, y: number, o: { button?: 'left' | 'right'; ctrl?: true } = {}) => {+ const ev = { x, y, button: o.button ?? 'left', ...(o.ctrl ? { ctrl: o.ctrl } : {}), in: 'sel0' }+ await ui.pointer({ type: 'down', ...ev })+ await ui.pointer({ type: 'up', ...ev })+}++test('picture select: the link rows are not drawn under pages that take it, and the copy counts none of them', async ($, on) => {+ const { w, ui } = await drawTargets($, on, { env: { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1', IUI_DEBUG: '1' } })+ expect(tree(await ui.drawn()).some(n => n.type === 'Link' || n.type === 'Button')).toBe(false)+ // The message: the top margin and the page's 16 rows, nothing under them: the page's top is row 1.+ await ui.redraw({ ...props(TARGETS_MD), onScreen: { first: 0, last: 16, of: 17 } })+ await settle(w)+ await ui.pointer({ type: 'down', x: 0, y: 1, button: 'left', in: 'sel0' })+ await settle(w)+ expect(w.traces.find(t => t.includes('select: down #'))).toContain(' top 1 above 0 ')+})++test('picture select: on the main screen the link rows are drawn as before', async ($, on) => {+ const { ui } = await drawTargets($, on, {}, false)+ const drawn = await ui.drawn()+ expect(tree(drawn).filter(n => n.type === 'Link').map(n => n.props.href)).toEqual(['https://example.com', 'https://typst.app/docs/reference', 'file:///w/src/a.ts'])+ expect(tree(drawn).filter(n => n.type === 'Button').length).toBe(2)+})++test('picture select: a hover over a link tints its cells; off it, or a leave, puts the page back', async ($, on) => {+ const { w, ui } = await drawTargets($, on)+ expect(w.blits).toEqual([])+ // Over a word that is no target: nothing.+ await hover(ui, 1, 3)+ await settle(w)+ expect(w.blits).toEqual([])+ await hover(ui, 6, 3)+ await settle(w)+ expect(isFrame(w)).toBe(true)+ const png = w.frames.at(-1)!.png+ expect([cellOf(png, 3, 4), cellOf(png, 3, 11)]).toEqual(['selected', 'selected'])+ expect([cellOf(png, 3, 3), cellOf(png, 3, 12), cellOf(png, 2, 6), cellOf(png, 4, 6)]).toEqual(['page', 'page', 'page', 'page'])+ // Within the same target: no new frame.+ const frames = w.frames.length+ await hover(ui, 9, 3)+ await settle(w)+ expect(w.frames.length).toBe(frames)+ await hover(ui, 13, 3)+ await settle(w)+ expect(isPlain(w)).toBe(true)+ await hover(ui, 20, 3)+ await settle(w)+ expect(isFrame(w)).toBe(true)+ await ui.pointer({ type: 'leave', x: 20, y: 3, in: 'sel0' })+ await settle(w)+ expect(isPlain(w)).toBe(true)+})++test('picture select: a down takes the hover tint down, and no hover tints while a selection shows', async ($, on) => {+ const { w, ui } = await drawTargets($, on)+ await hover(ui, 6, 3)+ await settle(w)+ expect(isFrame(w)).toBe(true)+ // A drag that starts on the link selects text.+ await ui.pointer({ type: 'down', x: 6, y: 3, button: 'left', in: 'sel0' })+ await settle(w)+ expect(isPlain(w)).toBe(true)+ await ui.pointer({ type: 'move', x: 20, y: 3, button: 'left', in: 'sel0' })+ await ui.pointer({ type: 'up', x: 30, y: 3, button: 'left', in: 'sel0' })+ await settle(w)+ expect(w.copies.length).toBe(1)+ const blits = w.blits.length+ await hover(ui, 52, 4)+ await settle(w)+ expect(w.blits.length).toBe(blits)+})++test('picture select: a click copies a link, a file\'s path or a command; a click off them clears as before', async ($, on) => {+ const { w, ui } = await drawTargets($, on)+ await click(ui, 6, 3)+ await settle(w)+ await click(ui, 30, 3)+ await settle(w)+ await click(ui, 8, 6)+ await settle(w)+ await click(ui, 52, 4)+ await settle(w)+ expect(w.copies).toEqual(['https://example.com', 'https://typst.app/docs/reference', '/w/src/a.ts', 'ls -la'])+ expect(w.toasts.filter(t => t.startsWith('Intelligent UI: copied the '))).toEqual([+ 'Intelligent UI: copied the link', 'Intelligent UI: copied the link', 'Intelligent UI: copied the path', 'Intelligent UI: copied the command',+ ])+ // No target (a code block is none): nothing copied.+ await click(ui, 1, 3)+ await click(ui, 60, 8)+ await click(ui, 5, 10)+ await settle(w)+ expect(w.copies.length).toBe(4)+})++test('picture select: a ctrl+click copies as a plain click does; a right click is dropped', async ($, on) => {+ const { w, ui } = await drawTargets($, on)+ await click(ui, 6, 3, { button: 'right' })+ await click(ui, 6, 3, { button: 'right', ctrl: true })+ await settle(w)+ expect(w.copies).toEqual([])+ await click(ui, 6, 3, { ctrl: true })+ await settle(w)+ expect(w.copies).toEqual(['https://example.com'])+})++test('picture select: after a click on a target its tint shows again; a leave then takes it down', async ($, on) => {+ const { w, ui } = await drawTargets($, on)+ await click(ui, 6, 3)+ await settle(w)+ expect(isFrame(w)).toBe(true)+ expect(cellOf(w.frames.at(-1)!.png, 3, 4)).toBe('selected')+ // The same cell again: no new post, no new frame.+ const frames = w.frames.length+ await hover(ui, 6, 3)+ await settle(w)+ expect(w.frames.length).toBe(frames)+ await ui.pointer({ type: 'leave', x: 6, y: 3, in: 'sel0' })+ await settle(w)+ expect(isPlain(w)).toBe(true)+})++test('picture select: a hover that replaced an up in its frame carries it: the copy is made', async ($, on) => {+ const { w, ui } = await drawTargets($, on)+ const at = (x: number, y: number) => ({ x, y })+ const up = { id: 'ans-1', page: 0, anchor: at(0, 1), head: at(21, 3), phase: 'up', seq: 102 }+ await ui.post({ id: 'ans-1', page: 0, anchor: at(0, 1), head: at(0, 1), phase: 'down', seq: 101 }, { in: 'sel0' })+ await ui.post({ id: 'ans-1', page: 0, anchor: at(6, 3), head: at(6, 3), phase: 'hover', seq: 103, end: up }, { in: 'sel0' })+ // The same up again (a later hover): not copied twice.+ await ui.post({ id: 'ans-1', page: 0, anchor: at(7, 3), head: at(7, 3), phase: 'hover', seq: 104, end: up }, { in: 'sel0' })+ await settle(w)+ expect(w.copies.length).toBe(1)+ expect(w.copies[0]).toContain('Targets')+})++test('picture select: with IUI_DEBUG, a click writes its target; a hover its target', async ($, on) => {+ const { w, ui } = await drawTargets($, on, { env: { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1', IUI_DEBUG: '1' } })+ await hover(ui, 6, 3)+ await settle(w)+ await click(ui, 6, 3)+ await settle(w)+ await click(ui, 1, 3)+ await settle(w)+ expect(w.traces.some(t => t.includes('select: hover ans-1 page 0 target 0 (web) rows 3:4-11'))).toBe(true)+ expect(w.traces.some(t => t.includes('select: click ans-1 page 0 at 6,3 target web'))).toBe(true)+ expect(w.traces.some(t => t.includes('select: click ans-1 page 0 at 1,3 target none'))).toBe(true)+})+test('no private cache folder: nothing is drawn (no shared folder instead); /iui, its details and a toast say why', async ($, on) => {const refused = '/t/cc-intelligent-ui-501'const w = world(on, { tty: TTY, refused })diff --git a/tests/select.test.ts b/tests/select.test.tsindex 3e250bc..e789720 100644--- a/tests/select.test.ts+++ b/tests/select.test.ts@@ -1,7 +1,14 @@import { expect, test } from 'claude-code/testing'import { decodeSelection, placeholderCell, positionsOf, textOfRun, type Mark } from '../hooks/register'-import { needsSelect, postOf, rowsAbove, runsOf, selectedRows, selectionAfter, selectTrace, textOfRuns, topsOf, type SelectPost } from '../hooks/lib/select'+import {+ forgetRedraws, hovered, litOf, needsSelect, picked, postOf, rowsAbove, runsOf, sameLit, selectedNow, selectedRows, selectionAfter, selectTrace, textOfRuns, topsOf,+ type SelectPost,+} from '../hooks/lib/select'+import type { PageTarget } from '../hooks/lib/targets'+import { linkRowsOf, type ShownLink } from '../hooks/lib/draw'+import { rowsAfter, type Under } from '../hooks/lib/pictures'+import { drawnAnswers } from '../hooks/lib/state'import { SMALL_MARKS, SMALL_PAGE, SMALL_PPI } from './copy-fixture'// ---- The posts --------------------------------------------------------------@@ -40,6 +47,79 @@ test('a post keeps its region\'s size when it is whole cells; a bad one is droppexpect(postOf({ ...post(), size: null })).toEqual(post())})+test('a hover and a leave are posts too; each keeps only an up or a clear as its end', () => {+ const up = post({ phase: 'up', seq: 4 })+ expect(postOf({ ...post({ phase: 'hover', seq: 5 }), end: up })).toEqual(post({ phase: 'hover', seq: 5, end: up }))+ expect(postOf({ ...post({ phase: 'leave', seq: 5 }), end: post({ phase: 'clear', seq: 4 }) })?.end?.phase).toBe('clear')+ // An end that is not an up or a clear, one with an end of its own, or one on a drag phase: dropped, the post kept.+ expect(postOf({ ...post({ phase: 'hover', seq: 5 }), end: post({ phase: 'move', seq: 4 }) })).toEqual(post({ phase: 'hover', seq: 5 }))+ expect(postOf({ ...post({ phase: 'hover', seq: 5 }), end: { ...up, end: up } })?.end).toEqual(up)+ expect(postOf({ ...post({ phase: 'up', seq: 5 }), end: up })).toEqual(post({ phase: 'up', seq: 5 }))+ // A hover or a leave selects nothing.+ expect(selectionAfter(post({ phase: 'hover' }), [0])).toBe(null)+ expect(selectionAfter(post({ phase: 'leave' }), [0])).toBe(null)+})++// ---- Links, files and commands ---------------------------------------------------++const TARGETS: PageTarget[] = [+ { target: { kind: 'web', href: 'https://example.com' }, rows: [{ row: 3, x0: 4, x1: 11 }] },+ { target: { kind: 'command', text: 'echo hello\nls -la' }, rows: [{ row: 9, x0: 2, x1: 12 }, { row: 10, x0: 2, x1: 8 }] },+]++test('a hover tints the target under it: its cells, by reference; none off the targets', () => {+ const at = { id: 'ans-1', page: 1, x: 5, y: 10 }+ const lit = litOf(at, TARGETS)+ expect(lit).toEqual({ id: 'ans-1', page: 1, index: 1, rows: TARGETS[1]!.rows })+ expect(lit?.rows).toBe(TARGETS[1]!.rows)+ expect(litOf({ ...at, x: 9 }, TARGETS)).toBe(null)+ expect(litOf({ ...at, x: 11, y: 3 }, TARGETS)?.index).toBe(0)+ expect(sameLit(lit, litOf({ ...at, x: 2, y: 9 }, TARGETS))).toBe(true)+ expect(sameLit(lit, litOf({ ...at, x: 4, y: 3 }, TARGETS))).toBe(false)+ expect(sameLit(lit, { ...lit!, page: 0 })).toBe(false)+ expect(sameLit(null, null)).toBe(true)+ expect(sameLit(lit, null)).toBe(false)+})++test('the pages show the selection; with none, the hovered target on its page only', () => {+ forgetRedraws()+ const pages = [{ file: '/c/p-1.png', width: 1568, height: 512, columns: 98, rows: 16 }, { file: '/c/p-2.png', width: 1568, height: 512, columns: 98, rows: 16 }]+ drawnAnswers.set('ans-9', { id: 'ans-9', seq: 1, dir: '/c', pages })+ try {+ expect(selectedNow()).toBe(null)+ hovered.lit = { id: 'ans-9', page: 1, index: 0, rows: [{ row: 3, x0: 4, x1: 11 }] }+ expect(selectedNow()).toEqual({ id: 'ans-9', pages, rows: [[], [{ row: 3, x0: 4, x1: 11 }]] })+ // A selection wins over the tint.+ picked.now = { id: 'ans-9', anchor: { x: 0, y: 1 }, head: { x: 3, y: 1 }, isUp: true }+ expect(selectedNow()?.rows).toEqual([[{ row: 1, x0: 0, x1: 3 }], []])+ // A drawing no longer known: nothing.+ picked.now = null+ hovered.lit = { ...hovered.lit, id: 'gone' }+ expect(selectedNow()).toBe(null)+ } finally {+ drawnAnswers.delete('ans-9')+ forgetRedraws()+ }+})++test('the link rows under pages: one a link, none where the pages take picture select', () => {+ const links: ShownLink[] = [{ kind: 'web', label: 'x', href: 'https://x.org' }, { kind: 'command', label: 'ls', text: 'ls' } as ShownLink]+ expect(linkRowsOf(links, false)).toBe(2)+ expect(linkRowsOf(links, true)).toBe(0)+ expect(linkRowsOf(undefined, false)).toBe(0)+ const result = { pages: [{ file: '/c/k/a-1.png', width: 1568, height: 128, columns: 98, rows: 4, alt: '' }], bulletRow: 0 }+ const under: Under[] = [+ { drawing: { kind: 'pages', result }, id: 'file:t:a.md', links },+ { drawing: { kind: 'pages', result }, id: 'file:t:b.md', links },+ ]+ // The first file: its own link rows, the second's pages and link rows.+ expect(rowsAfter(under, 0, 100)).toBe(2 + 4 + 2)+ expect(rowsAfter(under, 0, 100, true)).toBe(4)+ // Pages sent as bytes (over ssh) have no Client: their link rows are drawn.+ const bytes: Under[] = under.map(u => ('drawing' in u && u.drawing.kind === 'pages' ? { ...u, drawing: { ...u.drawing, bytes: [''] } } : u))+ expect(rowsAfter(bytes, 0, 100, true)).toBe(2 + 4 + 2)+})+// ---- Scrolled pages -------------------------------------------------------------test('the rows of a page above the viewport: the message\'s first row on screen less the page\'s top, 0 to its rows', () => {diff --git a/tests/targets.test.ts b/tests/targets.test.tsnew file mode 100644index 0000000..268cd78--- /dev/null+++ b/tests/targets.test.ts@@ -0,0 +1,114 @@+import { expect, test } from 'claude-code/testing'++import { positionsOf, targetAt, targetsOf, textOfRun, type Item, type Mark, type ShownLink, type TextBlock } from '../hooks/register'+import { LONG_MARKS, LONG_MD, LONG_PAGE, SMALL_PPI, TARGETS_MARKS, TARGETS_PAGE } from './copy-fixture'++const file = (label: string, path: string): ShownLink => ({ kind: 'file', label, path, href: `file://${path}` })+const LINKS = [file('src/a.ts', '/w/src/a.ts'), file('hooks/lib/copy.ts', '/w/hooks/lib/copy.ts')]++// ---- A real probe -----------------------------------------------------------++const REAL = positionsOf(TARGETS_MARKS as unknown as Mark[], SMALL_PPI)+const WORDS = { items: REAL.pages[0]!, blocks: REAL.blocks }++test('a real probe: links, a bare URL, inline code, a bare path are targets; a bash block is none', () => {+ // Rows: paragraph 3 (its inline code 4), paragraph 6, code 9 and 10.+ expect(targetsOf(WORDS, TARGETS_PAGE, LINKS)).toEqual([+ { target: { kind: 'web', href: 'https://example.com' }, rows: [{ row: 3, x0: 4, x1: 11 }] },+ { target: { kind: 'web', href: 'https://typst.app/docs/reference' }, rows: [{ row: 3, x0: 16, x1: 45 }] },+ { target: { kind: 'command', text: 'ls -la' }, rows: [{ row: 4, x0: 50, x1: 58 }] },+ { target: { kind: 'file', path: '/w/src/a.ts' }, rows: [{ row: 6, x0: 5, x1: 13 }] },+ { target: { kind: 'file', path: '/w/hooks/lib/copy.ts' }, rows: [{ row: 6, x0: 30, x1: 44 }] },+ ])+})++test("a real probe: a target's cells copy as its words", () => {+ const copied = targetsOf(WORDS, TARGETS_PAGE, LINKS).map(t =>+ textOfRun(t.rows.map(r => ({ row: r.row, colStart: r.x0, colEnd: r.x1 })), WORDS.items, WORDS.blocks, TARGETS_PAGE),+ )+ expect(copied).toEqual(['the docs', 'https://typst.app/docs/reference.', '! ls -la', 'src/a.ts', 'hooks/lib/copy.ts'])+})++test('a real probe: a bare file that does not exist (no ShownLink) is no target, in inline code a command; an anchor link is none', () => {+ const got = targetsOf(WORDS, TARGETS_PAGE, [file('other.ts', '/w/other.ts')]).map(t => t.target)+ expect(got.map(t => t.kind)).toEqual(['web', 'web', 'command', 'command'])+ expect(got[3]).toEqual({ kind: 'command', text: 'src/a.ts' })+})++test('a real probe: a long path and a long URL that wraps (a character a word)', () => {+ const long = positionsOf(LONG_MARKS as unknown as Mark[], SMALL_PPI)+ const path = '/Users/someone/Development/apps/very/long/path/to/file.ts'+ const got = targetsOf({ items: long.pages[0]!, blocks: long.blocks }, LONG_PAGE, [file(path, path)])+ expect(got.map(t => t.target)).toEqual([+ { kind: 'file', path },+ { kind: 'web', href: /https:\S+\/x/.exec(LONG_MD)![0] },+ ])+ expect(got[1]!.rows).toEqual([{ row: 5, x0: 15, x1: 95 }, { row: 6, x0: 0, x1: 93 }])+})++test('targetAt finds the target whose cells hold a cell', () => {+ const targets = targetsOf(WORDS, TARGETS_PAGE, LINKS)+ expect(targetAt(targets, 4, 3)).toBe(0)+ expect(targetAt(targets, 11, 3)).toBe(0)+ expect(targetAt(targets, 12, 3)).toBe(-1)+ expect(targetAt(targets, 30, 6)).toBe(4)+ expect(targetAt(targets, 8, 10)).toBe(-1)+ expect(targetAt([], 0, 0)).toBe(-1)+})++// ---- Hand-made words --------------------------------------------------------++// A page of 10 columns of 10 px, 4 rows of 20 px; a word 6 px a character.+const PAGE = { width: 100, height: 80, columns: 10, rows: 4 }+const word = (i: number, text: string, x0: number, row: number, more: Partial<Item> = {}): Item => ({+ i, text, x0, x1: x0 + text.length * 6, y0: row * 20 + 2, y1: row * 20 + 18, block: 0, em: 20, ...more,+})+const PAR: TextBlock[] = [{ kind: 'par', prefix: '', first: 0 }]+const of = (items: Item[], blocks = PAR, links: readonly ShownLink[] = []) => targetsOf({ items, blocks }, PAGE, links)++test('a link is one target over its words, on each row it is on; a link to a file is that file', () => {+ const href = 'https://x.dev/a'+ const items = [word(0, 'see', 0, 0), word(1, 'the', 30, 0, { href }), word(2, 'long', 60, 0, { href }), word(3, 'guide', 0, 1, { href })]+ expect(of(items)).toEqual([{ target: { kind: 'web', href }, rows: [{ row: 0, x0: 3, x1: 7 }, { row: 1, x0: 0, x1: 2 }] }])+ const docs = [word(0, 'docs', 0, 0, { href: 'docs/usage.md#top' })]+ expect(of(docs, PAR, [file('docs/usage.md', '/w/docs/usage.md')])).toEqual([{ target: { kind: 'file', path: '/w/docs/usage.md' }, rows: [{ row: 0, x0: 0, x1: 1 }] }])+ expect(of(docs)).toEqual([])+})++test('only http, https and mailto links are web targets; links next to each other are two', () => {+ expect(of([word(0, 'mail', 0, 0, { href: 'mailto:[email protected]' })]).map(t => t.target)).toEqual([{ kind: 'web', href: 'mailto:[email protected]' }])+ expect(of([word(0, 'ftp', 0, 0, { href: 'ftp://x.org/a' })])).toEqual([])+ const two = [word(0, 'one', 0, 0, { href: 'https://a.io' }), word(1, 'two', 30, 0, { href: 'https://b.io' })]+ expect(of(two).map(t => t.target)).toEqual([{ kind: 'web', href: 'https://a.io' }, { kind: 'web', href: 'https://b.io' }])+})++test('inline code in a link is the link; other inline code is a command (its text, less a `! ` before it)', () => {+ const href = 'https://x.dev'+ expect(of([word(0, 'api', 0, 0, { href, code: 'api' }), word(1, 'docs', 30, 0, { href })]).map(t => t.target)).toEqual([{ kind: 'web', href }])+ const cmd = [word(0, '!', 0, 0, { code: '! npm test' }), word(1, 'npm', 12, 0, { code: '! npm test' }), word(2, 'test', 40, 0, { code: '! npm test' })]+ expect(of(cmd)).toEqual([{ target: { kind: 'command', text: 'npm test' }, rows: [{ row: 0, x0: 0, x1: 5 }] }])+ expect(of([word(0, 'npm', 0, 0, { code: 'npm' })]).map(t => t.target)).toEqual([{ kind: 'command', text: 'npm' }])+ expect(of([word(0, '!', 0, 0, { code: '!' })]).map(t => t.target)).toEqual([{ kind: 'command', text: '!' }])+})++test('a bare path takes the punctuation around it off; a bare word that is a name is not a path', () => {+ const links = [file('a/b.ts:12', '/w/a/b.ts')]+ // "(a/" "b.ts:12)," with no space between: one token.+ const items = [word(0, '(a/', 0, 0), word(1, 'b.ts:12),', 18, 0)]+ expect(of(items, PAR, links).map(t => t.target)).toEqual([{ kind: 'file', path: '/w/a/b.ts' }])+ expect(of([word(0, 'Node.js', 0, 0)], PAR, [file('Node.js', '/w/Node.js')])).toEqual([])+ // A space between: two tokens, neither a path.+ expect(of([word(0, 'a/', 0, 0), word(1, 'b.ts:12', 30, 0)], PAR, links)).toEqual([])+})++test('a code block is no target, also a shell block', () => {+ const line = (i: number, text: string, row: number): Item => ({ i, text, x0: 10, x1: 10 + text.length * 5, y0: row * 20 + 4, y1: row * 20 + 16, block: 0, adv: 5 })+ expect(of([line(0, '$ make build', 0), line(1, 'https://x.dev', 1)], [{ kind: 'code', prefix: '', first: 0 }])).toEqual([])+})++test('the cells scale with the box the page is drawn at', () => {+ const href = 'https://x.dev'+ const items = [word(0, 'the', 30, 0, { href }), word(1, 'link', 60, 1, { href })]+ // Cells of 20 x 40 px: both words on row 0.+ expect(targetsOf({ items, blocks: PAR }, { ...PAGE, columns: 5, rows: 2 }, [])[0]!.rows).toEqual([{ row: 0, x0: 1, x1: 3 }])+})