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.
This commit is contained in:
@@ -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) {
|
||||
|
||||
@@ -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', '<a id="middle-link" href="${process.env.RS_TEST_URL}linked" style="position:absolute;left:600px;top:40px;width:120px;height:30px;display:block">Linked</a><a id="script-link" href="javascript:void(0)" style="position:absolute;left:600px;top:100px;width:120px;height:30px;display:block">Script</a>');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');
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 => {},
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
let scrollAnchor = $state<{ x: number; y: number } | null>(null);
|
||||
let scrollFrame = 0, moveFrame = 0, movePending = false;
|
||||
let pendingMove: Record<string, unknown> | 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<WheelQueue['push']>[0]); return; }
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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='<a href="${linked}" style="position:absolute;left:40px;top:300px;display:block;width:200px;height:40px">Linked page</a>';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='<canvas width="1000" height="700"></canvas>'; 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++); });
|
||||
|
||||
Reference in New Issue
Block a user