From 2ca7752c9d84294538b7c25555949f0f3f4ea796 Mon Sep 17 00:00:00 2001 From: Knotty Wyvern Date: Sat, 31 Oct 2026 19:41:27 -0700 Subject: [PATCH] Open links and images in new browser tabs - A middle-click on a link opens the link in a new tab. Scrolling starts at once, as before. The new engine command linkAt reads the link under the pointer in an isolated world. When it finds a web link, the tab stops the scroll and opens the link. - The image menu of a page starts with Open image in new tab. A new tab opens in front, like Open link in new tab. The engine smoke test checks linkAt, and the interaction test checks both actions with the real engine. Cards 333909d1 and f7ee842d. --- browser-runtime/src/engine.mjs | 8 ++++++++ browser-runtime/test/engine-smoke.mjs | 8 ++++++++ docs/user-guide.md | 4 ++++ src-tauri/src/browser.rs | 3 ++- src/lib/browser/Browser.svelte | 23 +++++++++++++++++++---- src/lib/i18n/messages.ts | 6 ++++++ tests/smoke/browser/interaction.smoke.mjs | 18 ++++++++++++++++++ 7 files changed, 65 insertions(+), 5 deletions(-) diff --git a/browser-runtime/src/engine.mjs b/browser-runtime/src/engine.mjs index 3aaa910..5bb70bc 100644 --- a/browser-runtime/src/engine.mjs +++ b/browser-runtime/src/engine.mjs @@ -292,6 +292,14 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame = } return null; } + case 'linkAt': { + // A middle-click on a link opens it in a new tab. The isolated world keeps page scripts from changing the answer. + if (![args.x, args.y].every(value => Number.isInteger(value) && value >= 0 && value <= 5120)) throw new Error('Invalid pointer position.'); + const href = await tab(args.tabId).view.webContents.executeJavaScriptInIsolatedWorld(902, [{ + code: `document.elementFromPoint(${args.x}, ${args.y})?.closest('a[href], area[href]')?.href ?? ''`, + }]).catch(() => ''); + try { return { url: href ? webUrl(href, { blank: false }) : null }; } catch { return { url: null }; } + } case 'copiedImage': { // A part stays below the line limit of the host connection. if (!copied || copied.token !== args.token || copied.tabId !== args.tabId || !Number.isSafeInteger(args.offset) || args.offset < 0 || args.offset >= copied.data.length) { diff --git a/browser-runtime/test/engine-smoke.mjs b/browser-runtime/test/engine-smoke.mjs index 3c053ed..8385a47 100644 --- a/browser-runtime/test/engine-smoke.mjs +++ b/browser-runtime/test/engine-smoke.mjs @@ -161,6 +161,13 @@ app.whenReady().then(async () => { assert.equal(whole.subarray(0, 6).toString(), 'GIF89a'); assert.equal(whole.at(-1), 0x3b); await wc.executeJavaScript('document.querySelector("#copy-image").remove();true;'); + // A middle-click asks for the link under the pointer. Only web links count. + await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', 'LinkedScript');true;`); + assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 650, y: 50 }), { url: `${process.env.RS_TEST_URL}linked` }); + assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 650, y: 110 }), { url: null }); + assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 900, y: 600 }), { url: null }); + await assert.rejects(engine.command('linkAt', { tabId: first, x: -1, y: 50 }), /Invalid pointer position/); + await wc.executeJavaScript('document.querySelector("#middle-link").remove(); document.querySelector("#script-link").remove();true;'); // An image that opens as the page itself is the main resource of the tab. const direct = (await engine.command('newTab', { url: `${process.env.RS_TEST_URL}direct.gif` })).tabId; const directContents = engine.tabs.get(direct).view.webContents; @@ -174,6 +181,7 @@ app.whenReady().then(async () => { assert.deepEqual([directCopy.mime, directCopy.size], ['image/gif', large.size]); await engine.command('closeTab', { tabId: direct }); passed.push('Copy image keeps the loaded GIF bytes without a second request, also for an image that opens as the page'); + passed.push('A middle-click finds the web link under the pointer'); await until(async () => await wc.executeJavaScript("getComputedStyle(document.querySelector('.advertisement')).display") === 'none'); assert.equal(await wc.executeJavaScript('typeof window.adExecuted'), 'undefined'); passed.push('network and cosmetic ad blocking remain active'); diff --git a/docs/user-guide.md b/docs/user-guide.md index 4e305d9..a27fe93 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -262,6 +262,10 @@ If a download fails, the tab shows the cause. Select **Retry** to start the down Until the engine is installed, web links in your documents open in your system browser. After a RuneStone update that needs a new engine, a browser tab offers **Update the engine**. +In a page, middle-click a link to open it in a new tab. Middle-click other content to scroll, then move the pointer in the direction to scroll. +Right-click an image for **Open image in new tab**, **Save image as…**, **Copy image**, and **Copy image address**. +**Copy image** keeps the original file. A GIF that you paste into a document or a card keeps its animation. + Use **Settings → Browser** to set the homepage and search engine, manage profiles, block ads, and clear cookies, cache, or history. **Settings → Browser → Browser engine** shows the installed version. **Remove engine** frees the disk space. Your profiles, bookmarks, and history stay. Each profile keeps its own cookies and bookmarks. Web bookmarks show in the Bookmarks pane. diff --git a/src-tauri/src/browser.rs b/src-tauri/src/browser.rs index 274fae0..114691b 100644 --- a/src-tauri/src/browser.rs +++ b/src-tauri/src/browser.rs @@ -35,6 +35,7 @@ const COMMANDS: &[&str] = &[ "edit", "contextAction", "copiedImage", + "linkAt", "frameAck", "createProfile", "renameProfile", @@ -481,7 +482,7 @@ impl BrowserState { let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id })); return Ok(worker.routing.lock()?.snapshot(result, owner)); } - if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "copiedImage", "frameAck", "bookmark", "agentSnapshot"].contains(&command) { + if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "copiedImage", "linkAt", "frameAck", "bookmark", "agentSnapshot"].contains(&command) { let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?; match worker.routing.lock()?.owners.get(id) { Some(window) if window == owner => {}, diff --git a/src/lib/browser/Browser.svelte b/src/lib/browser/Browser.svelte index 44e956c..c171733 100644 --- a/src/lib/browser/Browser.svelte +++ b/src/lib/browser/Browser.svelte @@ -44,7 +44,7 @@ let scrollAnchor = $state<{ x: number; y: number } | null>(null); let scrollFrame = 0, moveFrame = 0, movePending = false; let pendingMove: Record | undefined; - let suppressedRelease = -1; + let suppressedRelease = -1, middlePressed = false; const result = $derived(current?.find?.text === findText ? current.find : null); const documentKey = $derived(`${tabId}:${current?.url}:${!!current?.loading}`); $effect(() => { @@ -117,6 +117,7 @@ { label: $t('Copy link address'), icon: 'copy', run: action('copyLink') }, { label: $t('Save link as…'), icon: 'save', run: action('saveLink') }, { separator: true }); if (context.hasImageContents) items.push( + { label: $t('Open image in new tab'), icon: 'file-plus', disabled: !context.srcURL, run: () => void newTab(current?.profileId || 'user', context.srcURL) }, { label: $t('Save image as…'), icon: 'save', disabled: !context.srcURL, run: action('saveImage') }, { label: $t('Copy image'), icon: 'copy', run: () => copyImage(context) }, { label: $t('Copy image address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true }); @@ -212,23 +213,37 @@ if (mounted && pendingMove) moveFrame = requestAnimationFrame(flushMove); }); } + // The frame has the CSS size of the page viewport. A surface point less the frame offset is the same page point. + function pagePoint(point: { x: number; y: number }) { + return { x: Math.max(0, Math.min(width - 1, Math.round(point.x - imageBox.x))), y: Math.max(0, Math.min(height - 1, Math.round(point.y - imageBox.y))) }; + } + // A middle-click starts scrolling at once. On a link, it stops the scroll and opens the link in a new tab. + async function openLinkAt(input: { x: number; y: number }) { + const owner = tabId; + const found = await request<{ url: string | null }>('linkAt', { tabId: owner, ...input }).catch(() => null); + if (!found?.url || owner !== tabId || !autoScroll.anchor) return; + stopScroll(); + if (middlePressed) suppressedRelease = 1; + void newTab(current?.profileId || 'user', found.url); + } function pointer(event: MouseEvent | WheelEvent, type: string) { event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') textInput.focus({ preventScroll: true }); const rect = surface.getBoundingClientRect(); const point = { x: event.clientX - rect.left, y: event.clientY - rect.top }; + if (event.button === 1) middlePressed = type === 'mouseDown'; if (type === 'mouseUp' && event.button === suppressedRelease) { suppressedRelease = -1; return; } if (type === 'mouseDown' && autoScroll.anchor) { suppressedRelease = event.button; stopScroll(); return; } if (type === 'mouseDown' && event.button === 1 && ready) { pendingMove = undefined; cancelAnimationFrame(moveFrame); moveFrame = 0; - autoScroll.start(point); scrollAnchor = point; scrollFrame = requestAnimationFrame(scrollStep); return; + autoScroll.start(point); scrollAnchor = point; scrollFrame = requestAnimationFrame(scrollStep); + void openLinkAt(pagePoint(point)); return; } if (autoScroll.anchor) { if (type === 'mouseMove') autoScroll.move(point); if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); } if (type === 'mouseWheel') stopScroll(); else return; } - // The frame has the CSS size of the page viewport. A surface point less the frame offset is the same page point. - const input = { type, x: Math.max(0, Math.min(width - 1, Math.round(point.x - imageBox.x))), y: Math.max(0, Math.min(height - 1, Math.round(point.y - imageBox.y))), + const input = { type, ...pagePoint(point), button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event), ...('deltaY' in event ? { deltaY: -event.deltaY * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? height : 1), deltaX: -event.deltaX * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? width : 1) } : {}) }; if (type === 'mouseWheel') { wheels.push(input as Parameters[0]); return; } diff --git a/src/lib/i18n/messages.ts b/src/lib/i18n/messages.ts index 16b9bd4..ea9e4e4 100644 --- a/src/lib/i18n/messages.ts +++ b/src/lib/i18n/messages.ts @@ -1679,6 +1679,12 @@ export const messageRows: [string, string, string, string][] = [ "新しいタブでリンクを開く", "在新标签页中打开链接" ], + [ + "Open image in new tab", + "Ouvrir l’image dans un nouvel onglet", + "新しいタブで画像を開く", + "在新标签页中打开图片" + ], [ "Open link in default browser", "Ouvrir le lien dans le navigateur par défaut", diff --git a/tests/smoke/browser/interaction.smoke.mjs b/tests/smoke/browser/interaction.smoke.mjs index a8c1838..ee85005 100644 --- a/tests/smoke/browser/interaction.smoke.mjs +++ b/tests/smoke/browser/interaction.smoke.mjs @@ -139,6 +139,24 @@ await runSmoke('browser/interaction', async ({ browser }) => { const copied = await page.evaluate(async url => (await import('/src/lib/workspace/copiedImage.ts')).copiedImage(url), gifUrl); assert.equal(copied, `data:image/gif;base64,${onceGif.toString('base64')}`); assert.equal(commands.filter(call => call.command === 'copiedImage').length, 1); + // A new browser tab opens in front. Close it, so that the next steps use the first tab again. + async function expectTab(url) { + for (let attempt = 0; attempt < 100 && !(await rpc('state')).tabs.some(tab => tab.url === url); attempt++) await page.waitForTimeout(50); + assert.ok((await rpc('state')).tabs.some(tab => tab.url === url), `A new browser tab opens ${url}`); + await page.keyboard.press('Control+w'); + for (let attempt = 0; attempt < 100 && (await rpc('state')).tabs.length > 1; attempt++) await page.waitForTimeout(50); + assert.equal((await rpc('state')).tabs.length, 1); + await page.locator('.browser:not(.blank)[data-browser-state="ready"]').waitFor(); + } + await page.mouse.click(initialBox.x + 80, initialBox.y + 340, { button: 'right' }); + await page.getByRole('menuitem', { name: 'Open image in new tab', exact: true }).click(); + await expectTab(gifUrl); + // A middle-click on a link opens the link in a new tab instead of scrolling. + const linked = `${fixture.url}linked`; + await evaluate(`document.body.innerHTML='Linked page';true;`); + await page.mouse.click(initialBox.x + 100, initialBox.y + 320, { button: 'middle' }); + await expectTab(linked); + assert.equal(await page.locator('.scroll-anchor').count(), 0, 'A middle-click on a link does not keep scrolling'); await evaluate(`document.body.innerHTML=''; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`); await page.locator('.surface img').waitFor(); await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); });