diff --git a/docs/guides/05-events-and-input.md b/docs/guides/05-events-and-input.md index d005f3d3..cb443c6b 100644 --- a/docs/guides/05-events-and-input.md +++ b/docs/guides/05-events-and-input.md @@ -100,6 +100,12 @@ cells. `mousedown` moves focus, and `wheel` scrolls. Each wheel notch scrolls three lines. There's no context menu; the right button is an ordinary press. +A link's text is painted as a terminal hyperlink (OSC 8) when its `href` +resolves to an absolute `http`, `https` or `mailto` URL, so a terminal +that supports them opens it on its own modifier-click or hover, whether +or not the page has the mouse. The engine never follows a link itself; a +`click` listener is where an app acts on one. + ```ts row.addEventListener("click", () => open(row.dataset.path!)); ``` diff --git a/src/internal/cssom.ts b/src/internal/cssom.ts index 60b21717..cf4ca148 100644 --- a/src/internal/cssom.ts +++ b/src/internal/cssom.ts @@ -7795,6 +7795,17 @@ const LIST_NUMBERING_ATTRIBUTES = new Set([ "type", ]); +// Past the cap a restyle keeps, the next frame repaints whole. +function repaintLink(cascade: Cascade, element: Element): void { + const restyled = cascade.layout.restyledForPaint; + if (restyled.size >= 256) { + restyled.clear(); + cascade.layout.invalidateFrame(); + return; + } + restyled.set(element, null); +} + // What one batch of records has done, for the work that waits until // the batch ends. interface MutationBatch { @@ -8187,6 +8198,14 @@ function handleAttributeMutation( noteCounterChange(cascade, element); cascade.layout.invalidateFrame(); } + // A link paints its URL into its cells apart from its style, so its + // rows repaint whatever the sheets make of the change. + if ( + mutation.attributeName === "href" && + (getLocalName(element) === "a" || getLocalName(element) === "area") + ) { + repaintLink(cascade, element); + } // A change to keys whose rules declare only paint properties // leaves every box where it was. The styles are dropped so the // next read resolves them, and layout is not told. diff --git a/src/internal/framebuffer.ts b/src/internal/framebuffer.ts index 977c9dde..88d35e04 100644 --- a/src/internal/framebuffer.ts +++ b/src/internal/framebuffer.ts @@ -137,6 +137,11 @@ class FrameWriter { out: string; + // The OSC 8 hyperlink the emitted text is inside, by id, or 0. A + // cursor move ends it: what the terminal links is the text between the + // open and the close, wherever the cursor went in between. + openLink: number; + // The style escapes this writer has written, as getStyleDiff keys them. escapes: Map>>; escapeCount: number; @@ -144,6 +149,7 @@ class FrameWriter { constructor(colorDepth: ColorDepth) { this.colorDepth = colorDepth; this.out = ""; + this.openLink = 0; this.escapes = new Map(); this.escapeCount = 0; } @@ -154,37 +160,61 @@ class FrameWriter { return taken; } + hyperlink(id: number, url: string): this { + if (this.openLink === id) { + return this; + } + this.openLink = id; + this.out += `\x1b]8;id=${id};${url}\x1b\\`; + return this; + } + + endHyperlink(): this { + if (this.openLink !== 0) { + this.openLink = 0; + this.out += "\x1b]8;;\x1b\\"; + } + return this; + } + carriageReturn(): this { + this.endHyperlink(); this.out += "\r"; return this; } newLine(rows = 1): this { + this.endHyperlink(); this.out += "\r\n".repeat(rows); return this; } cursorTo(row: number, col: number): this { + this.endHyperlink(); this.out += `\x1b[${row};${col}H`; return this; } cursorForward(columns: number): this { + this.endHyperlink(); this.out += `\x1b[${columns}C`; return this; } cursorDown(rows: number): this { + this.endHyperlink(); this.out += `\x1b[${rows}B`; return this; } saveCursor(): this { + this.endHyperlink(); this.out += "\x1b7"; return this; } restoreCursor(): this { + this.endHyperlink(); this.out += "\x1b8"; return this; } @@ -224,6 +254,7 @@ class FrameWriter { } resetStyle(): this { + this.endHyperlink(); this.out += "\x1b[0m"; return this; } @@ -320,6 +351,8 @@ export interface CellStyle { dim?: boolean; blink?: boolean; overline?: boolean; + // An absolute URL the cell's text links to (OSC 8), or nothing. + link?: string | null; } interface TextMetrics { @@ -758,6 +791,53 @@ function getBorderChar(borderEncoding: number): string { return " "; } +// The URLs a grid's cells link to, by id. A framebuffer keeps one for +// its life, so a link that repaints keeps its id and a terminal treats +// its pieces as one link. +class LinkTable { + readonly urls: Map; + readonly ids: Map; + last: number; + + constructor() { + this.urls = new Map(); + this.ids = new Map(); + this.last = 0; + } + + intern(url: string): number { + let id = this.ids.get(url); + if (id === undefined) { + id = ++this.last; + this.urls.set(id, url); + this.ids.set(url, id); + } + return id; + } +} + +const KEPT_LINKS = 1024; + +/** Forget the URLs no cell of the grid links to, once there are many. */ +export function sweepLinks(grid: CellGrid): void { + const {urls, ids} = grid.links; + if (ids.size <= KEPT_LINKS) { + return; + } + const used = new Set(); + for (let index = 0; index < grid.link.length; index++) { + if (grid.link[index] !== 0) { + used.add(grid.link[index]); + } + } + for (const [id, url] of urls) { + if (!used.has(id)) { + urls.delete(id); + ids.delete(url); + } + } +} + /** * Parallel typed-array planes indexed by `row * cols + col`. A color of * 0 is the terminal's default, not black. It is the sentinel the diff @@ -773,8 +853,10 @@ export class CellGrid { readonly bg: Uint32Array; readonly attrs: Uint16Array; readonly border: Uint32Array; + readonly link: Uint32Array; + readonly links: LinkTable; - constructor(rows: number, cols: number) { + constructor(rows: number, cols: number, links = new LinkTable()) { this.rows = rows; this.cols = cols; const size = rows * cols; @@ -783,6 +865,8 @@ export class CellGrid { this.bg = new Uint32Array(size); this.attrs = new Uint16Array(size); this.border = new Uint32Array(size); + this.link = new Uint32Array(size); + this.links = links; } setCell( @@ -801,6 +885,7 @@ export class CellGrid { packAttrs(style) | ((width < ATTR.WidthWide ? width : ATTR.WidthWide) << ATTR.WidthShift); this.border[index] = 0; + this.link[index] = style?.link ? this.links.intern(style.link) : 0; if (width > 1) { settleWide(this, index, width); } @@ -818,6 +903,7 @@ export class CellGrid { this.bg[index] = (style.bg ?? 0) & COLOR_MASK; this.attrs[index] = packAttrs(style) | (1 << ATTR.WidthShift); this.border[index] = 0; + this.link[index] = 0; } setBorderCell(index: number, border: number, style?: CellStyle): void { @@ -830,6 +916,7 @@ export class CellGrid { this.attrs[index] = (packAttrs(style) & ~ATTR.DoubleUnderline) | (1 << ATTR.WidthShift); this.border[index] = border; + this.link[index] = 0; } } @@ -839,6 +926,7 @@ export function clearGrid(grid: CellGrid): void { grid.bg.fill(0); grid.attrs.fill(0); grid.border.fill(0); + grid.link.fill(0); } export function clearRange(grid: CellGrid, start: number, end: number): void { @@ -850,6 +938,7 @@ export function clearRange(grid: CellGrid, start: number, end: number): void { grid.bg.fill(0, start, end); grid.attrs.fill(0, start, end); grid.border.fill(0, start, end); + grid.link.fill(0, start, end); } function moveRange( @@ -863,6 +952,7 @@ function moveRange( grid.bg.copyWithin(dest, srcStart, srcEnd); grid.attrs.copyWithin(dest, srcStart, srcEnd); grid.border.copyWithin(dest, srcStart, srcEnd); + grid.link.copyWithin(dest, srcStart, srcEnd); } function copyGridFrom( @@ -875,16 +965,17 @@ function copyGridFrom( grid.bg.set(source.bg.subarray(start, end), to); grid.attrs.set(source.attrs.subarray(start, end), to); grid.border.set(source.border.subarray(start, end), to); + grid.link.set(source.link.subarray(start, end), to); } export function cloneGrid(grid: CellGrid): CellGrid { - const copy = new CellGrid(grid.rows, grid.cols); + const copy = new CellGrid(grid.rows, grid.cols, grid.links); copyGridFrom(copy, grid, {to: 0, start: 0, end: grid.rows * grid.cols}); return copy; } function bottomRows(grid: CellGrid, rows: number): CellGrid { - const kept = new CellGrid(rows, grid.cols); + const kept = new CellGrid(rows, grid.cols, grid.links); copyGridFrom(kept, grid, { to: 0, start: (grid.rows - rows) * grid.cols, @@ -905,6 +996,7 @@ function settleWide(grid: CellGrid, index: number, width: number): void { for (let covered = index + 1; covered < end; covered++) { grid.cluster[covered] = 0; grid.border[covered] = 0; + grid.link[covered] = 0; } } @@ -914,6 +1006,7 @@ function setBlank(grid: CellGrid, index: number): void { grid.bg[index] = 0; grid.attrs[index] = 1 << ATTR.WidthShift; grid.border[index] = 0; + grid.link[index] = 0; } function setFrom( @@ -927,6 +1020,13 @@ function setFrom( grid.bg[index] = source.bg[sourceIndex]; grid.attrs[index] = source.attrs[sourceIndex]; grid.border[index] = source.border[sourceIndex]; + const link = source.link[sourceIndex]; + if (link === 0 || source.links === grid.links) { + grid.link[index] = link; + } else { + const url = source.links.urls.get(link); + grid.link[index] = url === undefined ? 0 : grid.links.intern(url); + } } function widthAt(grid: CellGrid, index: number): number { @@ -948,7 +1048,8 @@ function equalCells( grid.bg[index] === other.bg[otherIndex] && (grid.attrs[index] & ATTR.StyleMask) === (other.attrs[otherIndex] & ATTR.StyleMask) && - grid.border[index] === other.border[otherIndex] + grid.border[index] === other.border[otherIndex] && + grid.link[index] === other.link[otherIndex] ); } @@ -1369,6 +1470,7 @@ export function drawRect( grid.bg[index] = bg; grid.attrs[index] = attrs; grid.border[index] = 0; + grid.link[index] = 0; } } return; @@ -1520,6 +1622,7 @@ export function drawDecoration( grid.bg[index] = 0; grid.attrs[index] = edgeBit | (style.dim ? ATTR.Dim : 0) | (1 << ATTR.WidthShift); + grid.link[index] = 0; } } } @@ -1794,11 +1897,29 @@ const TO_DEFAULT = -2; const ATTR_KEY = 1 << ATTR.WidthShift; const KEPT_ESCAPES = 4096; +// The style escape, then the link, so a reset the style writes cannot +// close a link the cell opens. function getStyleDiff( grid: CellGrid, index: number, prev: number, writer: FrameWriter, +): void { + writeStyleDiff(grid, index, prev, writer); + const link = grid.link[index]; + const url = link === 0 ? undefined : grid.links.urls.get(link); + if (url === undefined) { + writer.endHyperlink(); + } else { + writer.hyperlink(link, url); + } +} + +function writeStyleDiff( + grid: CellGrid, + index: number, + prev: number, + writer: FrameWriter, ): void { const fg = grid.fg[index]; const bg = grid.bg[index]; @@ -1979,6 +2100,7 @@ function moveCursor( } if (rowDiff > 0) { + const close = writer.endHyperlink().take(); if (startRow < 0 || rowDiff <= 2) { writer.newLine(rowDiff); } else { @@ -1989,12 +2111,12 @@ function moveCursor( } const relative = writer.take(); if (startRow < 0) { - return relative; + return close + relative; } const absolute = writer .cursorTo(startRow + targetRow + 1, targetCol + 1) .take(); - return absolute.length < relative.length ? absolute : relative; + return close + (absolute.length < relative.length ? absolute : relative); } if (targetCol === currentCol) { return ""; @@ -2421,6 +2543,8 @@ export class Framebuffer { // reports and kept, so a font zoom is not taken for another screen. pixelRatio: number | null; writer: FrameWriter; + // The URLs the grids' cells link to, for the life of the framebuffer. + links: LinkTable; frameScroll: number; dirty: boolean; // Whether the next frame repaints every row, because something changed @@ -2463,6 +2587,7 @@ export class Framebuffer { this.wholeDamage = true; this.graphics = null; this.writer = new FrameWriter(colorDepth); + this.links = new LinkTable(); } /** Width probes go out over the exchange, once there is one. */ @@ -2540,7 +2665,7 @@ export class Framebuffer { const lines: string[] = []; for (let top = 0; top < rows; top += STATIC_BAND_ROWS) { const height = Math.min(STATIC_BAND_ROWS, rows - top); - const grid = new CellGrid(height, cols); + const grid = new CellGrid(height, cols, this.links); paint(new CellContext(grid, height, cols, -top)); for (let row = 0; row < height; row++) { lines.push(getGridLine(grid, row, this.writer)); @@ -2866,6 +2991,7 @@ export function beginFrame( next.bg.set(prev.bg); next.attrs.set(prev.attrs); next.border.set(prevBorders); + next.link.set(prev.link); context.bands = []; for (const [top, end] of bands) { const from = Math.max(0, top); @@ -2917,7 +3043,7 @@ export function beginFrame( // there is nothing to diff against. Print all of it. let diff = framebuffer.diff; if (diff === null || diff.rows !== frameRows || diff.cols !== cols) { - diff = new CellGrid(frameRows, cols); + diff = new CellGrid(frameRows, cols, framebuffer.links); framebuffer.diff = diff; } else { clearGrid(diff); @@ -3252,7 +3378,8 @@ function diffRows( next.bg[n] !== prev.bg[p] || (next.attrs[n] & ATTR.StyleMask) !== (prev.attrs[p] & ATTR.StyleMask) || - next.border[n] !== prev.border[p] + next.border[n] !== prev.border[p] || + next.link[n] !== prev.link[p] ) { break; } @@ -3386,6 +3513,9 @@ export function endFrame(framebuffer: Framebuffer): string { framebuffer.frameScroll = 0; framebuffer.dirty = false; framebuffer.wholeDamage = false; + if (framebuffer.prev !== null) { + sweepLinks(framebuffer.prev); + } return ansi; } @@ -3421,7 +3551,7 @@ function takeGrid(screen: Framebuffer, rows: number, cols: number): CellGrid { clearGrid(spare); return spare; } - return new CellGrid(rows, cols); + return new CellGrid(rows, cols, screen.links); } function isProbingUseful(exchange: Exchange): boolean { diff --git a/src/internal/frames.ts b/src/internal/frames.ts index dd9a0150..ac541ef4 100644 --- a/src/internal/frames.ts +++ b/src/internal/frames.ts @@ -34,6 +34,7 @@ import { Framebuffer, resize, settleBorders, + sweepLinks, } from "./framebuffer.ts"; import {framePainted, Layout} from "./layout.ts"; import {paint, Painter} from "./painter.ts"; @@ -177,6 +178,7 @@ setFrameEngineFactory((document, window, parent, changed) => { paint(painter, context); // Joined here, since the layers do not leave with the grid. settleBorders(grid, layers); + sweepLinks(grid); framePainted(layout); painted++; // The painter puts the caret in document rows. The grid's rows are diff --git a/src/internal/painter.ts b/src/internal/painter.ts index 8fe04f35..1fcce50c 100644 --- a/src/internal/painter.ts +++ b/src/internal/painter.ts @@ -960,7 +960,7 @@ export function checkPartialFrame( previousCaret: Caret | null, ): void { const whole = new CellContext( - new CellGrid(ctx.rows, ctx.cols), + new CellGrid(ctx.rows, ctx.cols, ctx.grid.links), ctx.rows, ctx.cols, ctx.viewportOffset, @@ -981,6 +981,7 @@ export function checkPartialFrame( a.bg[index] !== b.bg[index] || a.attrs[index] !== b.attrs[index] || a.border[index] !== b.border[index] || + a.link[index] !== b.link[index] || (a.border[index] !== 0 && ctx.layers !== null && ctx.layers[index] !== whole.layers![index]) @@ -1038,6 +1039,36 @@ const PAINT_STYLE: StyleGroup = { read: readPaintStyle, }; +// The absolute URL of the nearest enclosing link, for the terminal to +// open (OSC 8). A fragment or a relative URL means nothing outside the +// document, and an anchor without href is not a link. No file: URLs: +// the page may not be from the machine the terminal is on. +const LINK_SCHEMES = /^(?:https?|mailto):/i; +const MAX_LINK_LENGTH = 2083; +// Bytes that would end the escape the URL is written in. +const LINK_UNSAFE = /[\x00-\x20\x7f-\x9f]/; + +function getLinkURL(element: Element): string | null { + for ( + let node: Element | null = element; + node !== null; + node = flatParentElement(node) + ) { + if ( + (node.localName === "a" || node.localName === "area") && + node.hasAttribute("href") + ) { + const url = (node as HTMLAnchorElement).href; + return LINK_SCHEMES.test(url) && + url.length <= MAX_LINK_LENGTH && + !LINK_UNSAFE.test(url) + ? url + : null; + } + } + return null; +} + function getPaintStyle(painter: Painter, element: Element): PaintStyle { const key = painter.cascade.getStyleKey(element); const known = key === null ? undefined : paintStyles.get(key); @@ -2276,6 +2307,10 @@ function paintText( if (!style.visible) { return; } + // Elements whose values match share one paint style, and a link is not + // one of those values, so it joins per text node. + const link = getLinkURL(parentElement); + const cell = link === null ? style.cell : {...style.cell, link}; let painted = false; for (let index = 0; index < fragments.length; index++) { const fragment = fragments[index]; @@ -2300,17 +2335,11 @@ function paintText( applyTextTransform(text, style.textTransform), Math.round(fragment.rect.left), Math.round(fragment.rect.top), - style.cell, + cell, ); } if (painted) { - renderTextHighlights( - painter, - textNode, - style.cell, - style.textTransform, - ctx, - ); + renderTextHighlights(painter, textNode, cell, style.textTransform, ctx); } } diff --git a/tests/hyperlinks.test.ts b/tests/hyperlinks.test.ts new file mode 100644 index 00000000..87979711 --- /dev/null +++ b/tests/hyperlinks.test.ts @@ -0,0 +1,119 @@ +import {expect, test} from "@b9g/libuild/test"; + +import {TermDOM} from "../src/index.ts"; +import {CellGrid, sweepLinks} from "../src/internal/framebuffer.ts"; +import {captureRawOutput, MockProcess, nextFrame} from "./test-utils.js"; + +const OPEN = (id: number, url: string) => `\x1b]8;id=${id};${url}\x1b\\`; +const CLOSE = "\x1b]8;;\x1b\\"; + +function makeApp( + html: string, + cols = 40, +): {terminal: MockProcess; written: () => string; dom: TermDOM} { + const terminal = new MockProcess({cols, rows: 6}); + const written = captureRawOutput(terminal); + const dom = new TermDOM({transport: terminal.transport}); + dom.document.body.innerHTML = html; + return {terminal, written, dom}; +} + +test("a link's text is wrapped in an OSC 8 hyperlink", async () => { + const {written, dom} = + makeApp("see the docs now"); + await nextFrame(dom); + const output = written(); + expect(output).toContain(OPEN(1, "https://example.com/docs")); + const open = output.indexOf(OPEN(1, "https://example.com/docs")); + const close = output.indexOf(CLOSE, open); + expect(close).toBeGreaterThan(open); + expect(output.slice(open, close)).toContain("the docs"); + expect(output.slice(open, close)).not.toContain("now"); + dom.dispose(); +}); + +test("a link wrapped across lines keeps one id", async () => { + const {written, dom} = makeApp( + "one two three four five six", + 12, + ); + await nextFrame(dom); + const output = written(); + const opens = output.match(/\x1b\]8;id=(\d+);/g) ?? []; + expect(opens.length).toBeGreaterThanOrEqual(2); + expect(new Set(opens).size).toBe(1); + dom.dispose(); +}); + +test("a placeholder anchor, a fragment and a relative URL link nothing", async () => { + const {written, dom} = makeApp( + "plain frag rel", + ); + await nextFrame(dom); + expect(written()).not.toContain("\x1b]8;"); + dom.dispose(); +}); + +test("a file, a script and an overlong URL link nothing", async () => { + const long = `https://example.com/${"a".repeat(2100)}`; + const {written, dom} = makeApp( + "file " + + "ftp " + + "js " + + `long`, + ); + await nextFrame(dom); + expect(written()).not.toContain("\x1b]8;"); + dom.dispose(); +}); + +test("URLs no cell links to are forgotten once there are many", () => { + const grid = new CellGrid(1, 2); + for (let index = 0; index < 2000; index++) { + grid.setCell(0, "x", {link: `https://example.com/${index}`}); + } + grid.setCell(1, "y", {link: "https://example.com/0"}); + sweepLinks(grid); + expect([...grid.links.urls.values()].sort()).toEqual([ + "https://example.com/0", + "https://example.com/1999", + ]); + expect(grid.links.urls.get(grid.link[0])).toBe("https://example.com/1999"); +}); + +test("a relative URL resolves against the document URL", async () => { + const terminal = new MockProcess({cols: 40, rows: 6}); + const written = captureRawOutput(terminal); + const dom = new TermDOM({ + transport: terminal.transport, + url: "https://example.com/a/b.html", + }); + dom.document.body.innerHTML = "c"; + await nextFrame(dom); + expect(written()).toContain(OPEN(1, "https://example.com/c.html")); + dom.dispose(); +}); + +test("changing only the href repaints the link", async () => { + const {written, dom} = makeApp("x"); + await nextFrame(dom); + const start = written().length; + dom.document.querySelector("a")!.setAttribute( + "href", + "https://example.com/2", + ); + await nextFrame(dom); + expect(written().slice(start)).toContain(OPEN(2, "https://example.com/2")); + dom.dispose(); +}); + +test("the document printed on exit keeps its links", async () => { + const {written, dom} = + makeApp("
a
"); + await nextFrame(dom); + const start = written().length; + await dom.dispose(); + const printed = written().slice(start); + expect(printed).toContain(OPEN(1, "https://example.com/")); + expect(printed).toContain(CLOSE); +});