Compare commits

..
11 Commits
Author SHA1 Message Date
Knotty Wyvern 3c099e7f49 Link the 0.1.53 Windows installer
The Linux package stays at 0.1.51, and macOS stays at 0.1.44. The README also drops the owner's removed sentence about developer tools.
2026-10-31 19:51:20 -07:00
Knotty Wyvern 5c4d759c1b Pin browser engine 0.1.11
Engine 0.1.11 finds the link under a middle-click. It replaces engine 0.1.10 in the pin.
2026-10-31 19:42:17 -07:00
Knotty Wyvern 2ca7752c9d 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.
2026-10-31 19:41:27 -07:00
Knotty Wyvern 68c302a271 Pin browser engine 0.1.10
Engine 0.1.10 keeps the display scale when a page replaces itself during its load. It replaces engine 0.1.9 in the pin.
2026-10-31 19:08:13 -07:00
Knotty Wyvern 19ef8f2e15 Keep the display scale when a page replaces itself during its load
The engine applied device emulation at did-finish-load. Each new
document gets a renderer widget without emulation. Google replaces its
first document with ?zx=... before that document finishes. Thus the
first document kept a scale of 1, and the page grew by the display
scale when the second document finished.

The engine now also applies emulation when a main-frame document
commits. In the real app at 125%, Google keeps the same size before and
after its second document. Card 40a8db13.
2026-10-31 19:06:45 -07:00
Knotty Wyvern 28661f28bc Draw the browser scroll marker with the scroll icon
Middle-click scrolling in the built-in browser showed the text arrow
"↕" at 20 px in a 24 px circle. The look of that glyph depends on the
font, and the circle cut it. It also showed only two directions, but
the scroll moves in four.

The marker now uses the four-way scroll icon of Project Management,
which the shared Icon component also gets. The marker has the size of
the Project Management marker: a 26 px circle with a 20 px icon. The
interaction smoke test checks the icon and keeps screenshots in both
themes. Card ac49c9ec.
2026-10-31 19:06:45 -07:00
Knotty Wyvern 33495d2bf7 Set the version to 0.1.53 2026-10-31 18:31:37 -07:00
Knotty Wyvern e4be352a2b Pin browser engine 0.1.9
Engine 0.1.9 keeps the original bytes for Copy image. The pin names its ZIP on the RuneStone releases page.
2026-10-31 18:24:37 -07:00
Knotty Wyvern 6e1b24e40f Keep the frames of pasted GIF, WebP, and AVIF images
A browser puts only the first frame of an image on the clipboard, with
HTML that names the image address.

- Documents and cards download the original of a GIF, WebP, or AVIF
  address. The host commands workspace_save_image_url and
  workspace_download_image read the format from the file contents and
  refuse other data. A failed download keeps the first frame and shows
  a message.
- Copy image in the RuneStone browser keeps the bytes that the page
  loaded. The engine reads them through the DevTools Protocol, so the
  website gets no second request. The new copiedImage command gives
  them in parts below the line limit of the host. A paste uses them
  first.
- An empty dropped image file shows a message. Firefox gives such a
  file when the website refuses its download.

Copy image needs a new browser engine build. Card 0d5c18f7.
2026-10-31 17:33:08 -07:00
Knotty Wyvern 31ce7e73ce Close the workspace menu on a second click of its button
The menu is an automatic popover. A press on the button closed the open
menu, and the click that followed opened it again. The picker now
records an open menu when the press starts on the button. The click
then leaves the menu closed.

The workspace smoke test clicks the button two times. Card 53db89fc.
2026-10-31 17:33:07 -07:00
Knotty Wyvern 8e2df5544a Show the label colors in Manage labels again
The default field rule of Project Management excluded the find bar with
:not(.rs-find-bar input). That exclusion raised the specificity of the
rule above the rule of each control. Thus the color swatches, the card
title field, the switches, and the date field got the default field
background.

:where() inside :not() keeps the exclusion and adds no specificity.
A new smoke test checks the 16 swatch colors and the card title field in
both themes. Card 0efb6b6e.
2026-10-31 17:33:07 -07:00
45 changed files with 812 additions and 68 deletions
+1 -2
View File
@@ -8,7 +8,7 @@ Download the installer for your computer.
| Platform | Installer | Status | | Platform | Installer | Status |
| --- | --- | --- | | --- | --- | --- |
| Windows 10 or 11, x64 | [RuneStone_0.1.52_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.52/RuneStone_0.1.52_x64-setup.exe) | Primary platform | | Windows 10 or 11, x64 | [RuneStone_0.1.53_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.53/RuneStone_0.1.53_x64-setup.exe) | Primary platform |
| macOS, Apple silicon | [RuneStone_0.1.44_aarch64.dmg](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_aarch64.dmg) | Experimental: ad hoc signed, not notarized | | macOS, Apple silicon | [RuneStone_0.1.44_aarch64.dmg](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_aarch64.dmg) | Experimental: ad hoc signed, not notarized |
| Linux, amd64 | [RuneStone_0.1.51_amd64.deb](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.51/RuneStone_0.1.51_amd64.deb) | Experimental: built on Ubuntu 26.04.1, needs GLIBC 2.39 or newer | | Linux, amd64 | [RuneStone_0.1.51_amd64.deb](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.51/RuneStone_0.1.51_amd64.deb) | Experimental: built on Ubuntu 26.04.1, needs GLIBC 2.39 or newer |
@@ -16,7 +16,6 @@ Download the installer for your computer.
- **macOS:** Open the disk image and drag RuneStone into Applications. Then open RuneStone from Applications. - **macOS:** Open the disk image and drag RuneStone into Applications. Then open RuneStone from Applications.
- **Linux:** Run `sudo apt install ./RuneStone_0.1.51_amd64.deb` in the download folder. Then open RuneStone from your applications menu. - **Linux:** Run `sudo apt install ./RuneStone_0.1.51_amd64.deb` in the download folder. Then open RuneStone from your applications menu.
You do not need developer tools.
On Windows, the built-in browser needs a separate engine download of about 160 MB. A browser tab offers it on first use. On Windows, the built-in browser needs a separate engine download of about 160 MB. A browser tab offers it on first use.
For checksums, updates, and reinstalls, see [Installation and updates](docs/installation.md). For checksums, updates, and reinstalls, see [Installation and updates](docs/installation.md).
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "runestone-browser", "name": "runestone-browser",
"version": "0.1.8", "version": "0.1.11",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "runestone-browser", "name": "runestone-browser",
"version": "0.1.8", "version": "0.1.11",
"dependencies": { "dependencies": {
"@ghostery/adblocker": "2.18.2", "@ghostery/adblocker": "2.18.2",
"ipaddr.js": "2.3.0" "ipaddr.js": "2.3.0"
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "runestone-browser", "name": "runestone-browser",
"version": "0.1.8", "version": "0.1.11",
"private": true, "private": true,
"description": "Isolated browser runtime included with RuneStone", "description": "Isolated browser runtime included with RuneStone",
"type": "module", "type": "module",
+20
View File
@@ -5,7 +5,27 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import electron from 'electron'; import electron from 'electron';
const directory = await mkdtemp(path.join(os.tmpdir(), 'runestone-plugin-browser-')); const directory = await mkdtemp(path.join(os.tmpdir(), 'runestone-plugin-browser-'));
// A two-frame GIF that the server gives only one time, as some image hosts do.
const onceGif = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAACAkQBACH5BAAKAAAALAAAAAABAAEAAAICTAEAOw==', 'base64');
let onceGifServed = false;
// The same GIF with 7 MB of comment blocks, so that Copy image needs more than one part.
const comment = Buffer.concat([Buffer.from([255]), Buffer.alloc(255, 0x61)]);
const largeGif = Buffer.concat([onceGif.subarray(0, 32), Buffer.from([0x21, 0xfe]), ...Array(28_000).fill(comment), Buffer.from([0]), onceGif.subarray(32)]);
const server = http.createServer((req, res) => { const server = http.createServer((req, res) => {
if (req.url === '/direct.gif') {
res.writeHead(200, { 'Content-Type': 'image/gif' });
return res.end(largeGif);
}
if (req.url === '/large.gif') {
res.writeHead(200, { 'Content-Type': 'image/gif' });
return res.end(largeGif);
}
if (req.url === '/once.gif') {
if (onceGifServed) { res.writeHead(200, { 'Content-Type': 'text/html' }); return res.end('Invalid request'); }
onceGifServed = true;
res.writeHead(200, { 'Content-Type': 'image/gif' });
return res.end(onceGif);
}
if (req.url === '/picture.png') { if (req.url === '/picture.png') {
res.writeHead(200, { 'Content-Type': 'image/png' }); res.writeHead(200, { 'Content-Type': 'image/png' });
return res.end(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII=', 'base64')); return res.end(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII=', 'base64'));
+51 -2
View File
@@ -31,6 +31,31 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
pageFocusStates.set(wc, enabled); pageFocusStates.set(wc, enabled);
if (enabled) wc.focus(); if (enabled) wc.focus();
} }
// The last image that Copy image took from a page. RuneStone gets it in parts when the user pastes.
let copied = null;
const COPIED_PART = 3_000_000;
// The page holds the encoded image. Its bytes keep all frames of a GIF, and the website gets no second request.
async function loadedImage(wc, url) {
if (!wc.debugger.isAttached()) { wc.debugger.attach('1.3'); pageFocusStates.delete(wc); }
await wc.debugger.sendCommand('Page.enable');
try {
const href = value => { try { return new URL(value).href; } catch { return ''; } };
const nodes = [(await wc.debugger.sendCommand('Page.getResourceTree')).frameTree];
for (const node of nodes) {
// An image that opens as the page itself is the main resource of its frame.
const page = href(node.frame.url) === url && /^image\//.test(node.frame.mimeType) ? node.frame : undefined;
const resource = page ?? node.resources?.find(item => item.type === 'Image' && href(item.url) === url);
if (resource) {
const { content, base64Encoded } = await wc.debugger.sendCommand('Page.getResourceContent', { frameId: node.frame.id, url: resource.url });
const data = Buffer.from(content, base64Encoded ? 'base64' : 'utf8');
const valid = /^image\/(?:gif|png|jpeg|webp|avif|bmp)$/.test(resource.mimeType) && data.length > 0 && data.length <= 20_000_000;
return valid ? { mime: resource.mimeType, data } : null;
}
nodes.push(...(node.childFrames ?? []));
}
return null;
} finally { await wc.debugger.sendCommand('Page.disable').catch(() => {}); }
}
function emulateViewport(item) { function emulateViewport(item) {
if (!item.viewport) return; if (!item.viewport) return;
const { width, height } = item.viewport, scale = item.scale; const { width, height } = item.viewport, scale = item.scale;
@@ -141,7 +166,9 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
changed(); changed();
} }
}); });
wc.on('did-navigate', (_event, url) => { store.visit(profileId, url, item.title); changed(); }); // Each new document gets a renderer widget without device emulation. A page that replaces itself before it finishes
// loading, as Google does, otherwise keeps a scale of 1 and grows when the next document finishes.
wc.on('did-navigate', (_event, url) => { emulateViewport(item); store.visit(profileId, url, item.title); changed(); });
wc.on('did-navigate-in-page', (_event, _url, main) => { if (main) { item.epoch++; agent.revokeAll(); } changed(); }); wc.on('did-navigate-in-page', (_event, _url, main) => { if (main) { item.epoch++; agent.revokeAll(); } changed(); });
wc.on('page-title-updated', (_event, title) => { item.title = title.slice(0, 200); changed(); }); wc.on('page-title-updated', (_event, title) => { item.title = title.slice(0, 200); changed(); });
wc.on('page-favicon-updated', (_event, urls) => { wc.on('page-favicon-updated', (_event, urls) => {
@@ -248,7 +275,13 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
switch (args.action) { switch (args.action) {
case 'copyLink': if (context.linkURL) clipboard.writeText(context.linkURL); break; case 'copyLink': if (context.linkURL) clipboard.writeText(context.linkURL); break;
case 'copyImageAddress': if (context.srcURL) clipboard.writeText(context.srcURL); break; case 'copyImageAddress': if (context.srcURL) clipboard.writeText(context.srcURL); break;
case 'copyImage': if (context.hasImageContents) wc.copyImageAt(Math.round(context.x * current.scale), Math.round(context.y * current.scale)); break; case 'copyImage': {
if (!context.hasImageContents) break;
wc.copyImageAt(Math.round(context.x * current.scale), Math.round(context.y * current.scale));
const image = context.srcURL ? await loadedImage(wc, context.srcURL).catch(() => null) : null;
copied = image && { token: randomUUID(), tabId: current.id, url: context.srcURL, ...image };
return copied && { copied: { token: copied.token, url: copied.url, mime: copied.mime, size: copied.data.length } };
}
case 'openExternal': if (context.linkURL) await openExternal(context.linkURL); break; case 'openExternal': if (context.linkURL) await openExternal(context.linkURL); break;
case 'saveImage': case 'saveLink': { case 'saveImage': case 'saveLink': {
const url = args.action === 'saveImage' ? context.srcURL : context.linkURL; const url = args.action === 'saveImage' ? context.srcURL : context.linkURL;
@@ -259,6 +292,22 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
} }
return null; 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) {
throw new Error('The copied image is no longer available.');
}
const end = Math.min(copied.data.length, args.offset + COPIED_PART);
return { data: copied.data.subarray(args.offset, end).toString('base64'), next: end < copied.data.length ? end : null };
}
case 'input': { case 'input': {
const current = tab(args.tabId), wc = current.view.webContents; const current = tab(args.tabId), wc = current.view.webContents;
const input = args.input; const input = args.input;
+58
View File
@@ -124,6 +124,64 @@ app.whenReady().then(async () => {
await assert.rejects(engine.command('contextAction', { tabId: first, token: 'expired', action: 'saveImage' }), /no longer available/); await assert.rejects(engine.command('contextAction', { tabId: first, token: 'expired', action: 'saveImage' }), /no longer available/);
await wc.executeJavaScript('document.querySelector("#save-image").remove();true;'); await wc.executeJavaScript('document.querySelector("#save-image").remove();true;');
passed.push('Unicode text, native image context menus, saved image bytes and stale menu protection work'); passed.push('Unicode text, native image context menus, saved image bytes and stale menu protection work');
// Copy image keeps the bytes that the page loaded. The test server gives this GIF only one time.
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<img id="copy-image" src="${process.env.RS_TEST_URL}once.gif" style="position:absolute;left:400px;top:40px;width:80px;height:80px">');true;`);
await until(async () => await wc.executeJavaScript('document.querySelector("#copy-image").complete'));
const menus = events.length;
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 440, y: 80, button: 'right' } });
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 440, y: 80, button: 'right' } });
await until(() => events.slice(menus).some(event => event.event === 'context-menu' && event.hasImageContents));
const imageMenu = events.findLast(event => event.event === 'context-menu');
const { copied } = await engine.command('contextAction', { tabId: first, token: imageMenu.token, action: 'copyImage' });
assert.deepEqual([copied.url, copied.mime, copied.size], [`${process.env.RS_TEST_URL}once.gif`, 'image/gif', 85]);
const part = await engine.command('copiedImage', { tabId: first, token: copied.token, offset: 0 });
const bytes = Buffer.from(part.data, 'base64');
assert.equal(bytes.subarray(0, 6).toString(), 'GIF89a');
assert.equal(bytes.length, 85);
assert.equal(part.next, null);
await assert.rejects(engine.command('copiedImage', { tabId: first, token: copied.token, offset: 85 }), /no longer available/);
await assert.rejects(engine.command('copiedImage', { tabId: 'other', token: copied.token, offset: 0 }), /no longer available/);
// A large image comes in parts that stay below the line limit of the host.
await wc.executeJavaScript(`document.querySelector("#copy-image").src = "${process.env.RS_TEST_URL}large.gif";true;`);
await until(async () => await wc.executeJavaScript('document.querySelector("#copy-image").complete && document.querySelector("#copy-image").naturalWidth === 1'));
const largeMenus = events.length;
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 440, y: 80, button: 'right' } });
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 440, y: 80, button: 'right' } });
await until(() => events.slice(largeMenus).some(event => event.event === 'context-menu' && event.hasImageContents));
const large = (await engine.command('contextAction', { tabId: first, token: events.findLast(event => event.event === 'context-menu').token, action: 'copyImage' })).copied;
const parts = [];
for (let offset = 0; offset !== null;) {
const next = await engine.command('copiedImage', { tabId: first, token: large.token, offset });
assert.ok(next.data.length <= 4_000_000);
parts.push(Buffer.from(next.data, 'base64')); offset = next.next;
}
const whole = Buffer.concat(parts);
assert.ok(parts.length >= 3);
assert.equal(whole.length, large.size);
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;
await until(async () => await directContents.executeJavaScript('document.images[0]?.complete === true').catch(() => false));
const box = await directContents.executeJavaScript('(({ x, y, width, height }) => ({ x: Math.floor(x + width / 2), y: Math.floor(y + height / 2) }))(document.images[0].getBoundingClientRect())');
const directMenus = events.length;
await engine.command('input', { tabId: direct, input: { type: 'mouseDown', ...box, button: 'right' } });
await engine.command('input', { tabId: direct, input: { type: 'mouseUp', ...box, button: 'right' } });
await until(() => events.slice(directMenus).some(event => event.event === 'context-menu' && event.tabId === direct && event.hasImageContents));
const directCopy = (await engine.command('contextAction', { tabId: direct, token: events.findLast(event => event.event === 'context-menu').token, action: 'copyImage' })).copied;
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'); await until(async () => await wc.executeJavaScript("getComputedStyle(document.querySelector('.advertisement')).display") === 'none');
assert.equal(await wc.executeJavaScript('typeof window.adExecuted'), 'undefined'); assert.equal(await wc.executeJavaScript('typeof window.adExecuted'), 'undefined');
passed.push('network and cosmetic ad blocking remain active'); passed.push('network and cosmetic ad blocking remain active');
+2 -1
View File
@@ -6,7 +6,8 @@ app.setPath('userData', process.env.RS_INTERACTION_ROOT);
app.on('window-all-closed', () => {}); app.on('window-all-closed', () => {});
app.whenReady().then(async () => { app.whenReady().then(async () => {
let framePending = false; let framePending = false;
const engine = await createEngine({ directory: process.env.RS_INTERACTION_ROOT, canEmitFrame: () => !framePending, emit: value => { // The fixture server of the smoke test is on 127.0.0.1. The engine blocks local addresses for other hosts.
const engine = await createEngine({ directory: process.env.RS_INTERACTION_ROOT, allowedTestHosts: new Set(['127.0.0.1']), canEmitFrame: () => !framePending, emit: value => {
if (value.event === 'frame') framePending = true; if (value.event === 'frame') framePending = true;
process.send?.({ event: value }, () => { if (value.event === 'frame') framePending = false; }); process.send?.({ event: value }, () => { if (value.event === 'frame') framePending = false; });
} }); } });
+2
View File
@@ -10,6 +10,8 @@ This guide explains how to insert and edit images, read diagrams, edit Markdown
| --- | --- | | --- | --- |
| Drag an image from the navigator into a Markdown editor | RuneStone inserts a relative link to the existing file. Press Escape to cancel the drag. | | Drag an image from the navigator into a Markdown editor | RuneStone inserts a relative link to the existing file. Press Escape to cancel the drag. |
| Drop an image from your system file manager, or paste an image | RuneStone copies the image into the workspace `attachments/` folder with a unique name, then inserts a link. | | Drop an image from your system file manager, or paste an image | RuneStone copies the image into the workspace `attachments/` folder with a unique name, then inserts a link. |
| Paste an image that you copied with **Copy image** in the RuneStone browser | RuneStone saves the original file that the page loaded. A GIF keeps its animation, also from a website that refuses downloads. |
| Paste a GIF, WebP, or AVIF image that you copied in another web browser | That browser copies only the first frame. RuneStone downloads the original file from the image address, so the animation stays. If the website refuses the download, RuneStone saves the first frame and shows a message. |
Undo removes the inserted link. It keeps the image file. Undo removes the inserted link. It keeps the image file.
+6
View File
@@ -116,6 +116,12 @@ To add an image to a card, paste it or drop it into the description, or select *
Use a PNG, JPEG, GIF, or WebP image of at most 50 MiB. Use a PNG, JPEG, GIF, or WebP image of at most 50 MiB.
To show an image on the board, add **Card cover** and choose one of the images of the card. To show an image on the board, add **Card cover** and choose one of the images of the card.
A web browser copies only the first frame of an image. When you paste a GIF or WebP image from a browser, RuneStone downloads the original file.
Then the animation stays.
Some websites refuse that download. Then the card gets the first frame, and RuneStone shows a message.
To keep the animation, use **Copy image** in the RuneStone browser. That copy keeps the original file that the page loaded.
**More actions** → **Customize background** sets an image behind the open board, or behind All tasks. **More actions** → **Customize background** sets an image behind the open board, or behind All tasks.
To show the Background slideshow on the boards, see [Choose where the background shows](themes.md#choose-where-the-background-shows). To show the Background slideshow on the boards, see [Choose where the background shows](themes.md#choose-where-the-background-shows).
+2 -2
View File
@@ -6,7 +6,7 @@ This guide installs, updates, or reinstalls RuneStone from a supplied release fi
| Platform | Release file | Notes | | Platform | Release file | Notes |
| --- | --- | --- | | --- | --- | --- |
| Windows 10 or 11, x64 | [RuneStone_0.1.52_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.52/RuneStone_0.1.52_x64-setup.exe) | Installs for the current Windows account | | Windows 10 or 11, x64 | [RuneStone_0.1.53_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.53/RuneStone_0.1.53_x64-setup.exe) | Installs for the current Windows account |
| macOS, Apple silicon | [RuneStone_0.1.44_aarch64.dmg](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_aarch64.dmg) | Experimental. Intel Macs are not supported. | | macOS, Apple silicon | [RuneStone_0.1.44_aarch64.dmg](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_aarch64.dmg) | Experimental. Intel Macs are not supported. |
| Linux, amd64 | [RuneStone_0.1.51_amd64.deb](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.51/RuneStone_0.1.51_amd64.deb) | Experimental. Built on Ubuntu 26.04.1. Needs GLIBC 2.39 or newer. | | Linux, amd64 | [RuneStone_0.1.51_amd64.deb](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.51/RuneStone_0.1.51_amd64.deb) | Experimental. Built on Ubuntu 26.04.1. Needs GLIBC 2.39 or newer. |
@@ -15,7 +15,7 @@ On Windows, the built-in browser needs a separate engine download. See [Use the
## Install on Windows ## Install on Windows
1. Save `RuneStone_0.1.52_x64-setup.exe` to Downloads. 1. Save `RuneStone_0.1.53_x64-setup.exe` to Downloads.
2. Open the file. 2. Open the file.
3. Complete setup. Keep the default destination unless you need another location. 3. Complete setup. Keep the default destination unless you need another location.
4. Open RuneStone from the Start menu. 4. Open RuneStone from the Start menu.
+4
View File
@@ -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. 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**. 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. 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. **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. Each profile keeps its own cookies and bookmarks. Web bookmarks show in the Bookmarks pane.
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "runestone", "name": "runestone",
"version": "0.1.52", "version": "0.1.53",
"description": "Desktop editor for a local workspace", "description": "Desktop editor for a local workspace",
"type": "module", "type": "module",
"scripts": { "scripts": {
+1 -1
View File
@@ -3130,7 +3130,7 @@ dependencies = [
[[package]] [[package]]
name = "runestone" name = "runestone"
version = "0.1.52" version = "0.1.53"
dependencies = [ dependencies = [
"base64 0.23.1", "base64 0.23.1",
"dunce", "dunce",
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "runestone" name = "runestone"
version = "0.1.52" version = "0.1.53"
description = "Writing workspace plus script editor" description = "Writing workspace plus script editor"
authors = ["Knotty Wyvern"] authors = ["Knotty Wyvern"]
edition = "2021" edition = "2021"
@@ -46,4 +46,4 @@ opt-level = 3
strip = true strip = true
[package.metadata.runestone] [package.metadata.runestone]
version = "0.1.52" version = "0.1.53"
+4 -4
View File
@@ -1,11 +1,11 @@
{ {
"version": "0.1.8", "version": "0.1.11",
"protocol": 1, "protocol": 1,
"platforms": { "platforms": {
"windows-x86_64": { "windows-x86_64": {
"url": "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/browser-engine-v0.1.8/RuneStone-Browser_0.1.8_win32-x64.zip", "url": "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/browser-engine-v0.1.11/RuneStone-Browser_0.1.11_win32-x64.zip",
"bytes": 163632595, "bytes": 163623801,
"sha256": "d704003bf5fe047b100a3cf0ab84f3321fd272510cf287a229e50d1653d0856b" "sha256": "1e0153b134cebe882b36f74e1f3c2a4ed37acb2caca10548034a8b5d88738d26"
} }
} }
} }
+2
View File
@@ -71,6 +71,8 @@ fn main() {
"workspace_delete", "workspace_delete",
"workspace_read_data_url", "workspace_read_data_url",
"workspace_write_bytes", "workspace_write_bytes",
"workspace_save_image_url",
"workspace_download_image",
"workspace_copy", "workspace_copy",
"workspace_abs_path", "workspace_abs_path",
"workspace_reveal", "workspace_reveal",
+2
View File
@@ -69,6 +69,8 @@
"allow-workspace-delete", "allow-workspace-delete",
"allow-workspace-read-data-url", "allow-workspace-read-data-url",
"allow-workspace-write-bytes", "allow-workspace-write-bytes",
"allow-workspace-save-image-url",
"allow-workspace-download-image",
"allow-workspace-copy", "allow-workspace-copy",
"allow-workspace-abs-path", "allow-workspace-abs-path",
"allow-workspace-reveal", "allow-workspace-reveal",
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-download-image"
description = "Enables the workspace_download_image command without any pre-configured scope."
commands.allow = ["workspace_download_image"]
[[permission]]
identifier = "deny-workspace-download-image"
description = "Denies the workspace_download_image command without any pre-configured scope."
commands.deny = ["workspace_download_image"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-save-image-url"
description = "Enables the workspace_save_image_url command without any pre-configured scope."
commands.allow = ["workspace_save_image_url"]
[[permission]]
identifier = "deny-workspace-save-image-url"
description = "Denies the workspace_save_image_url command without any pre-configured scope."
commands.deny = ["workspace_save_image_url"]
+3 -1
View File
@@ -34,6 +34,8 @@ const COMMANDS: &[&str] = &[
"insertText", "insertText",
"edit", "edit",
"contextAction", "contextAction",
"copiedImage",
"linkAt",
"frameAck", "frameAck",
"createProfile", "createProfile",
"renameProfile", "renameProfile",
@@ -480,7 +482,7 @@ impl BrowserState {
let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id })); let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id }));
return Ok(worker.routing.lock()?.snapshot(result, owner)); 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", "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.")?; let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
match worker.routing.lock()?.owners.get(id) { match worker.routing.lock()?.owners.get(id) {
Some(window) if window == owner => {}, Some(window) if window == owner => {},
+2
View File
@@ -107,6 +107,8 @@ pub fn run() {
workspace::workspace_delete, workspace::workspace_delete,
workspace::workspace_read_data_url, workspace::workspace_read_data_url,
workspace::workspace_write_bytes, workspace::workspace_write_bytes,
workspace::workspace_save_image_url,
workspace::workspace_download_image,
workspace::workspace_copy, workspace::workspace_copy,
workspace::workspace_abs_path, workspace::workspace_abs_path,
workspace::workspace_reveal, workspace::workspace_reveal,
+152 -2
View File
@@ -967,10 +967,14 @@ fn read_data_url(root: &Path, rel: &str) -> Result<String> {
} }
let bytes = fsutil::read_to_limit(file, MAX_IMAGE_BYTES as u64)? let bytes = fsutil::read_to_limit(file, MAX_IMAGE_BYTES as u64)?
.ok_or_else(|| Error::new("image is too large"))?; .ok_or_else(|| Error::new("image is too large"))?;
Ok(format!( Ok(data_url(mime, &bytes))
}
fn data_url(mime: &str, bytes: &[u8]) -> String {
format!(
"data:{mime};base64,{}", "data:{mime};base64,{}",
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes) base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes)
)) )
} }
fn copy_destination(path: &Path, number: u32) -> PathBuf { fn copy_destination(path: &Path, number: u32) -> PathBuf {
@@ -1244,6 +1248,108 @@ fn write_image(root: &Path, rel: &str, base64: &str) -> Result<()> {
fsutil::write_bytes(&path, &bytes) fsutil::write_bytes(&path, &bytes)
} }
/// Save the original of an image that a web page copied. The clipboard has only a still copy,
/// so an animated GIF needs its source file. `rel` has no extension. The format of the
/// downloaded file sets it. Returns the path of the new file.
#[tauri::command]
pub async fn workspace_save_image_url(
window: tauri::Window,
state: State<'_, WorkspaceState>,
url: String,
rel: String,
) -> Result<String> {
let root = current_root(&state, window.label())?;
blocking(move || {
let bytes = download_image(&url)?;
save_image(&root, &rel, &bytes)
})
.await
}
/// Download a web image and return it as a data URL. Project Management keeps card images
/// as data URLs, so this gives a card the original of a copied image.
#[tauri::command]
pub async fn workspace_download_image(url: String) -> Result<String> {
blocking(move || image_data_url(&download_image(&url)?)).await
}
fn image_data_url(bytes: &[u8]) -> Result<String> {
let extension = image_extension(bytes).ok_or_else(|| Error::new("file is not an image"))?;
let mime = mime_from_path(Path::new(&format!("image.{extension}")))
.ok_or_else(|| Error::new("file is not an image"))?;
Ok(data_url(mime, bytes))
}
fn download_image(url: &str) -> Result<Vec<u8>> {
use std::io::Read;
let web = |url: &reqwest::Url| matches!(url.scheme(), "http" | "https");
let url = reqwest::Url::parse(url).map_err(|_| Error::new("invalid image address"))?;
if !web(&url) {
return Err(Error::new("image address is not http or https"));
}
let client = reqwest::blocking::Client::builder()
.user_agent(concat!("RuneStone/", env!("CARGO_PKG_VERSION")))
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(30))
.redirect(reqwest::redirect::Policy::custom(move |attempt| {
if attempt.previous().len() >= 5 || !web(attempt.url()) {
attempt.stop()
} else {
attempt.follow()
}
}))
.build()
.map_err(Error::from_display)?;
let response = client.get(url).send().map_err(Error::from_display)?;
if !response.status().is_success() {
return Err(Error::new(format!("image server answered {}", response.status())));
}
let mut bytes = Vec::new();
response.take(MAX_IMAGE_BYTES as u64 + 1).read_to_end(&mut bytes)?;
if bytes.len() > MAX_IMAGE_BYTES {
return Err(Error::new("image is too large"));
}
Ok(bytes)
}
fn save_image(root: &Path, rel: &str, bytes: &[u8]) -> Result<String> {
let extension = image_extension(bytes).ok_or_else(|| Error::new("file is not an image"))?;
let rel = format!("{rel}.{extension}");
let path = resolve_for_write(root, &rel)?;
check_new_components(root, &rel)?;
if path.exists() {
return Err(Error::new("a file with that name already exists"));
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fsutil::write_bytes(&path, bytes)?;
Ok(rel)
}
/// The extension of a raster image format from its first bytes. A web server can send a
/// wrong type, and an SVG file can contain scripts, so the type header and SVG do not count.
fn image_extension(bytes: &[u8]) -> Option<&'static str> {
let at = |start: usize, value: &[u8]| bytes.get(start..start + value.len()) == Some(value);
if at(0, b"GIF87a") || at(0, b"GIF89a") {
Some("gif")
} else if at(0, b"\x89PNG\r\n\x1a\n") {
Some("png")
} else if at(0, b"\xff\xd8\xff") {
Some("jpg")
} else if at(0, b"RIFF") && at(8, b"WEBP") {
Some("webp")
} else if at(4, b"ftypavif") || at(4, b"ftypavis") {
Some("avif")
} else if at(0, b"BM") {
Some("bmp")
} else if at(0, b"\0\0\x01\0") {
Some("ico")
} else {
None
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -1598,6 +1704,50 @@ mod tests {
fs::remove_dir_all(root).unwrap(); fs::remove_dir_all(root).unwrap();
} }
#[test]
fn image_formats_come_from_the_file_contents() {
assert_eq!(image_extension(b"GIF89a\x01\0"), Some("gif"));
assert_eq!(image_extension(b"GIF87a"), Some("gif"));
assert_eq!(image_extension(b"\x89PNG\r\n\x1a\n\0"), Some("png"));
assert_eq!(image_extension(b"\xff\xd8\xff\xe0"), Some("jpg"));
assert_eq!(image_extension(b"RIFF\0\0\0\0WEBPVP8 "), Some("webp"));
assert_eq!(image_extension(b"\0\0\0\x1cftypavif"), Some("avif"));
assert_eq!(image_extension(b"BM\0\0"), Some("bmp"));
assert_eq!(image_extension(b"\0\0\x01\0\x01\0"), Some("ico"));
assert_eq!(image_extension(b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>"), None);
assert_eq!(image_extension(b"<!doctype html>"), None);
assert_eq!(image_extension(b"RIFF"), None);
assert_eq!(image_extension(b""), None);
}
#[test]
fn web_images_keep_their_original_format() {
let root = workspace_fixture("image-url");
let gif = b"GIF89a\x01\0\x01\0\0\0\0;".to_vec();
let (base, server) = crate::plugin_sources::tests::server(vec![
("302 Found\r\nLocation: /cat.gif".into(), Vec::new()),
("200 OK\r\nContent-Type: image/png".into(), gif.clone()),
("200 OK\r\nContent-Type: image/gif".into(), b"<!doctype html>".to_vec()),
("404 Not Found".into(), Vec::new()),
]);
let bytes = download_image(&format!("{base}/image")).unwrap();
assert_eq!(save_image(&root, "attachments/pasted", &bytes).unwrap(), "attachments/pasted.gif");
assert_eq!(fs::read(root.join("attachments/pasted.gif")).unwrap(), gif);
assert_eq!(image_data_url(&bytes).unwrap(), "data:image/gif;base64,R0lGODlhAQABAAAAADs=");
let page = download_image(&format!("{base}/page")).unwrap();
assert_eq!(save_image(&root, "attachments/page", &page).unwrap_err().to_string(), "file is not an image");
assert_eq!(image_data_url(&page).unwrap_err().to_string(), "file is not an image");
assert_eq!(image_data_url(b"\xff\xd8\xff\xe0").unwrap(), "data:image/jpeg;base64,/9j/4A==");
assert!(download_image(&format!("{base}/missing")).unwrap_err().to_string().contains("404"));
let requests = server.join().unwrap();
assert!(requests[1].starts_with("GET /cat.gif "));
assert!(download_image("file:///C:/cat.gif").is_err());
assert!(save_image(&root, "attachments/pasted", &gif).is_err(), "an existing file stays");
assert!(save_image(&root, "../outside", &gif).is_err());
assert_eq!(names(&root.join("attachments")), ["pasted.gif"]);
fs::remove_dir_all(root).unwrap();
}
#[test] #[test]
fn permanent_delete_removes_files_and_folders_but_never_the_root() { fn permanent_delete_removes_files_and_folders_but_never_the_root() {
let root = workspace_fixture("delete"); let root = workspace_fixture("delete");
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "RuneStone", "productName": "RuneStone",
"version": "0.1.52", "version": "0.1.53",
"identifier": "com.runestone.app", "identifier": "com.runestone.app",
"build": { "build": {
"beforeDevCommand": "pnpm dev", "beforeDevCommand": "pnpm dev",
+40 -7
View File
@@ -11,6 +11,7 @@
import { TabSession, type TabStatus } from './tabSession'; import { TabSession, type TabStatus } from './tabSession';
import { engine } from './engine'; import { engine } from './engine';
import { AutoScroll } from './autoScroll'; import { AutoScroll } from './autoScroll';
import { keepCopiedImage } from '$lib/workspace/copiedImage';
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string, url?: string) => Promise<void> } = $props(); let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string, url?: string) => Promise<void> } = $props();
let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: $t('Opening browser…') }); let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: $t('Opening browser…') });
const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); }); const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); });
@@ -43,7 +44,7 @@
let scrollAnchor = $state<{ x: number; y: number } | null>(null); let scrollAnchor = $state<{ x: number; y: number } | null>(null);
let scrollFrame = 0, moveFrame = 0, movePending = false; let scrollFrame = 0, moveFrame = 0, movePending = false;
let pendingMove: Record<string, unknown> | undefined; 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 result = $derived(current?.find?.text === findText ? current.find : null);
const documentKey = $derived(`${tabId}:${current?.url}:${!!current?.loading}`); const documentKey = $derived(`${tabId}:${current?.url}:${!!current?.loading}`);
$effect(() => { $effect(() => {
@@ -116,8 +117,9 @@
{ label: $t('Copy link address'), icon: 'copy', run: action('copyLink') }, { label: $t('Copy link address'), icon: 'copy', run: action('copyLink') },
{ label: $t('Save link as…'), icon: 'save', run: action('saveLink') }, { separator: true }); { label: $t('Save link as…'), icon: 'save', run: action('saveLink') }, { separator: true });
if (context.hasImageContents) items.push( 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('Save image as…'), icon: 'save', disabled: !context.srcURL, run: action('saveImage') },
{ label: $t('Copy image'), icon: 'copy', run: action('copyImage') }, { label: $t('Copy image'), icon: 'copy', run: () => copyImage(context) },
{ label: $t('Copy image address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true }); { label: $t('Copy image address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true });
if (context.isEditable) items.push( if (context.isEditable) items.push(
{ label: $t('Undo'), icon: 'undo', shortcut: keys('Mod+Z'), disabled: !context.editFlags.canUndo, run: edit('undo') }, { label: $t('Undo'), icon: 'undo', shortcut: keys('Mod+Z'), disabled: !context.editFlags.canUndo, run: edit('undo') },
@@ -142,6 +144,23 @@
if (command === 'navigate') pageErrors.update(errors => { const next = { ...errors }; delete next[tabId]; return next; }); if (command === 'navigate') pageErrors.update(errors => { const next = { ...errors }; delete next[tabId]; return next; });
await connection.send(command, args); await connection.send(command, args);
} }
// A paste of a copied image uses the bytes that the page loaded. The engine gives them in parts.
// A paste can come before the reply, so the copy is known at once by its address.
function copyImage(context: PageMenu) {
const owner = tabId;
const data = (async () => {
const reply = await connection.send('contextAction', { token: context.token, action: 'copyImage' }) as { copied?: { token: string; mime: string } } | null | undefined;
const copied = reply?.copied;
if (!copied) return undefined;
let data = '';
for (let offset: number | null = 0; offset !== null;) {
const part: { data: string; next: number | null } = await request('copiedImage', { tabId: owner, token: copied.token, offset });
data += part.data; offset = part.next;
}
return `data:${copied.mime};base64,${data}`;
})().catch(() => undefined);
if (context.srcURL) keepCopiedImage(context.srcURL, data);
}
async function openTab(profileId = current?.profileId || $browserState?.profiles[0]?.id || 'user') { async function openTab(profileId = current?.profileId || $browserState?.profiles[0]?.id || 'user') {
if (opening) return; if (opening) return;
opening = true; opening = true;
@@ -194,23 +213,37 @@
if (mounted && pendingMove) moveFrame = requestAnimationFrame(flushMove); 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) { function pointer(event: MouseEvent | WheelEvent, type: string) {
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') textInput.focus({ preventScroll: true }); event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') textInput.focus({ preventScroll: true });
const rect = surface.getBoundingClientRect(); const rect = surface.getBoundingClientRect();
const point = { x: event.clientX - rect.left, y: event.clientY - rect.top }; 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 === 'mouseUp' && event.button === suppressedRelease) { suppressedRelease = -1; return; }
if (type === 'mouseDown' && autoScroll.anchor) { suppressedRelease = event.button; stopScroll(); return; } if (type === 'mouseDown' && autoScroll.anchor) { suppressedRelease = event.button; stopScroll(); return; }
if (type === 'mouseDown' && event.button === 1 && ready) { if (type === 'mouseDown' && event.button === 1 && ready) {
pendingMove = undefined; cancelAnimationFrame(moveFrame); moveFrame = 0; 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 (autoScroll.anchor) {
if (type === 'mouseMove') autoScroll.move(point); if (type === 'mouseMove') autoScroll.move(point);
if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); } if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); }
if (type === 'mouseWheel') stopScroll(); else return; 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, ...pagePoint(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))),
button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event), 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) } : {}) }; ...('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; } if (type === 'mouseWheel') { wheels.push(input as Parameters<WheelQueue['push']>[0]); return; }
@@ -286,7 +319,7 @@
oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }} oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }}
onblur={stopScroll}></textarea> onblur={stopScroll}></textarea>
{#if image && ready && !blank}<img src={image} class:exact={imageBox.exact} style:width={`${imageBox.width}px`} style:height={`${imageBox.height}px`} style:transform={`translate(${imageBox.x}px, ${imageBox.y}px)`} alt={$t("Web page rendered by the browser")} draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if} {#if image && ready && !blank}<img src={image} class:exact={imageBox.exact} style:width={`${imageBox.width}px`} style:height={`${imageBox.height}px`} style:transform={`translate(${imageBox.x}px, ${imageBox.y}px)`} alt={$t("Web page rendered by the browser")} draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if} {#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true"><Icon icon="scroll" /></span>{/if}
</div> </div>
</div> </div>
<style> <style>
@@ -298,7 +331,7 @@
input{flex:1}.profile-choice{max-width:160px;display:flex;align-items:center;gap:var(--rs-menu-icon-gap);cursor:pointer}input:focus-visible,.profile-choice:focus-visible{outline:2px solid var(--rs-focus)} input{flex:1}.profile-choice{max-width:160px;display:flex;align-items:center;gap:var(--rs-menu-icon-gap);cursor:pointer}input:focus-visible,.profile-choice:focus-visible{outline:2px solid var(--rs-focus)}
.surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)} .surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)}
.browser.blank,.blank .surface{background:transparent} .browser.blank,.blank .surface{background:transparent}
.surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);font-size:20px;pointer-events:none;box-shadow:0 1px 4px #0006} .surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:26px;height:26px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);pointer-events:none;box-shadow:0 1px 4px #0006}.scroll-anchor :global(svg){width:20px;height:20px;flex-basis:20px}
img{display:block;pointer-events:none;user-select:none;will-change:transform}img.exact{image-rendering:pixelated}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px} img{display:block;pointer-events:none;user-select:none;will-change:transform}img.exact{image-rendering:pixelated}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px}
.error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)} .error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)}
.reconnect{padding:6px 12px;margin:4px 0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);cursor:pointer} .reconnect{padding:6px 12px;margin:4px 0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);cursor:pointer}
+4 -2
View File
@@ -75,12 +75,14 @@ export class TabSession {
} }
} }
} }
async send(command: string, args: Record<string, unknown> = {}) { /** Returns the reply of the engine, or undefined when the request did not complete. */
async send(command: string, args: Record<string, unknown> = {}): Promise<unknown> {
if (this.closed || this.value.phase !== 'ready') return; if (this.closed || this.value.phase !== 'ready') return;
const tabId = this.value.tabId; const tabId = this.value.tabId;
try { try {
await this.transport(command, { ...args, tabId }); const reply = await this.transport(command, { ...args, tabId });
if (tabId === this.value.tabId && this.value.phase === 'ready' && !['input', 'resize', 'visible'].includes(command) && this.value.message) this.update({ message: '' }); if (tabId === this.value.tabId && this.value.phase === 'ready' && !['input', 'resize', 'visible'].includes(command) && this.value.message) this.update({ message: '' });
return reply;
} catch (error) { } catch (error) {
// Replies from the previous connection cannot replace the current error. // Replies from the previous connection cannot replace the current error.
if (this.closed || tabId !== this.value.tabId || this.value.phase !== 'ready') return; if (this.closed || tabId !== this.value.tabId || this.value.phase !== 'ready') return;
+7 -5
View File
@@ -15,7 +15,7 @@
import { linkCandidates } from "$lib/workspace/markdownLinks"; import { linkCandidates } from "$lib/workspace/markdownLinks";
import { editImageSource, imageSource } from "./imageSource"; import { editImageSource, imageSource } from "./imageSource";
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml"; import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle } from "$lib/workspace/media"; import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle, pastedImageSource } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop"; import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink"; import { workspaceFileLink } from "./workspaceFileLink";
import { savedEditor, saveEditor } from "./editorStates"; import { savedEditor, saveEditor } from "./editorStates";
@@ -48,7 +48,7 @@
onChange: (value: string, id: string) => void; onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>; onRenameTitle?: (id: string, title: string) => Promise<void>;
onOpenLink?: (kind: "md" | "wiki", target: string) => void; onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onInsertImage?: (file: File) => Promise<string | null>; onInsertImage?: (file: File, source?: string) => Promise<string | null>;
focusLine?: number | null; focusLine?: number | null;
/** The line and the column of the cursor, from 1. */ /** The line and the column of the cursor, from 1. */
onSelectionLine?: (line: number, column: number) => void; onSelectionLine?: (line: number, column: number) => void;
@@ -126,10 +126,12 @@
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
const position = event instanceof DragEvent ? view.posAtCoords({ x: event.clientX, y: event.clientY }, false) : null; const position = event instanceof DragEvent ? view.posAtCoords({ x: event.clientX, y: event.clientY }, false) : null;
await importImages(view, files, position); // Read the HTML now. The clipboard data is empty after the paste event.
const source = event instanceof ClipboardEvent && files.length === 1 ? pastedImageSource(data?.getData("text/html") ?? "") : undefined;
await importImages(view, files, position, undefined, source);
} }
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string) { async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string, source?: string) {
const range = position === null ? view.state.selection.main : { from: position, to: position }; const range = position === null ? view.state.selection.main : { from: position, to: position };
const id = Symbol(), path = buffer.relPath; const id = Symbol(), path = buffer.relPath;
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) }); view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
@@ -137,7 +139,7 @@
const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : []; const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : [];
for (const file of files) { for (const file of files) {
if (editor !== view) return; if (editor !== view) return;
const snippet = await onInsertImage?.(file); const snippet = await onInsertImage?.(file, source);
if (snippet) snippets.push(snippet); if (snippet) snippets.push(snippet);
} }
if (editor !== view || !snippets.length) return; if (editor !== view || !snippets.length) return;
+42 -12
View File
@@ -11,6 +11,30 @@ import {
parseImage, parseImage,
saveImages, saveImages,
} from "../storage/images.ts"; } from "../storage/images.ts";
import { workspaceDownloadImage } from "../../../workspace/api.ts";
import { copiedImage } from "../../../workspace/copiedImage.ts";
import { mayAnimate, pastedImageSource } from "../../../workspace/media.ts";
async function fileDataUrl(file: File) {
const bytes = new Uint8Array(await file.arrayBuffer());
let binary = "";
for (let offset = 0; offset < bytes.length; offset += 8192)
binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
return `data:${file.type};base64,${btoa(binary)}`;
}
/**
* The original of a copied web image. The RuneStone browser keeps the bytes of the image that it copied.
* For a copy from another browser, download the original of a format with frames.
* Undefined keeps the still copy. "refused" means that the website did not give the original.
*/
async function webImage(source: string): Promise<{ data: string; type: string } | "refused" | undefined> {
const data = await copiedImage(source) ?? (mayAnimate(source) ? await workspaceDownloadImage(source).catch(() => "") : undefined);
if (data === undefined) return undefined;
if (!data) return "refused";
const type = /^data:([^;]+);/.exec(data)?.[1] ?? "";
return imageTypes.includes(type) ? { data, type } : undefined;
}
/** The image data stays outside the card Markdown and loads only in the open editor. */ /** The image data stays outside the card Markdown and loads only in the open editor. */
export function createCardImages( export function createCardImages(
@@ -226,7 +250,8 @@ export function createCardImages(
} }
} }
} }
async function addFiles(files: File[], attachOnly = false) { /** `source` is the web address of the original of a copied image. `files` holds its still copy. */
async function addFiles(files: File[], attachOnly = false, source?: string) {
if (disposed || loading || description.disabled || !files.length) return; if (disposed || loading || description.disabled || !files.length) return;
loading = true; loading = true;
updateControls(); updateControls();
@@ -237,18 +262,20 @@ export function createCardImages(
end = description.selectionEnd; end = description.selectionEnd;
try { try {
const staged: { id: string; name: string; data: string }[] = []; const staged: { id: string; name: string; data: string }[] = [];
let refused = false;
for (const file of files) { for (const file of files) {
if (!imageTypes.includes(file.type)) // A browser copies only the first frame of a web image. The original keeps all of its frames.
const web = source ? await webImage(source) : undefined;
refused ||= web === "refused";
const original = typeof web === "object" ? web : undefined;
if (!original && !imageTypes.includes(file.type))
throw new Error(message("Use a PNG, JPEG, GIF, or WebP image.")); throw new Error(message("Use a PNG, JPEG, GIF, or WebP image."));
if (!file.size || file.size > maxImageBytes) if (!original && !file.size)
throw new Error(message("The image file is empty. A browser can give an empty file when the website refuses a download. To add the image, copy it in the RuneStone browser. You can also save the image and add the saved file."));
if (!original && file.size > maxImageBytes)
throw new Error(message("Use an image between 1 byte and 50 MiB.")); throw new Error(message("Use an image between 1 byte and 50 MiB."));
const bytes = new Uint8Array(await file.arrayBuffer()); const data = original?.data ?? await fileDataUrl(file);
let binary = ""; const name = original ? `${(file.name || "image").replace(/\.\w+$/, "")}.${original.type.slice(6)}` : file.name;
for (let offset = 0; offset < bytes.length; offset += 8192)
binary += String.fromCharCode(
...bytes.subarray(offset, offset + 8192),
);
const data = `data:${file.type};base64,${btoa(binary)}`;
// Decode the image before the reference goes in, so that an invalid clipboard file keeps the draft. // Decode the image before the reference goes in, so that an invalid clipboard file keeps the draft.
const image = new Image(); const image = new Image();
image.src = data; image.src = data;
@@ -257,7 +284,7 @@ export function createCardImages(
}); });
staged.push({ staged.push({
id: crypto.randomUUID(), id: crypto.randomUUID(),
name: (file.name || tr("Pasted image")).slice(0, 255), name: (name || tr("Pasted image")).slice(0, 255),
data, data,
}); });
} }
@@ -269,6 +296,7 @@ export function createCardImages(
description.setRangeText(`\n${markdown}\n`, start, end, "end"); description.setRangeText(`\n${markdown}\n`, start, end, "end");
} }
description.dispatchEvent(new Event("input", { bubbles: true })); description.dispatchEvent(new Event("input", { bubbles: true }));
if (refused) error.textContent = tr("The website refused the original image, so RuneStone added only its first frame. To keep the animation, copy the image in the RuneStone browser. You can also save the image and add the saved file.");
} catch (reason) { } catch (reason) {
if (!disposed) if (!disposed)
(attachOnly ? attachmentError : error).textContent = errorText(reason); (attachOnly ? attachmentError : error).textContent = errorText(reason);
@@ -288,7 +316,9 @@ export function createCardImages(
if (!files.length) return; if (!files.length) return;
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
void addFiles(files); // Read the HTML now. The clipboard data is empty after the paste event.
const source = files.length === 1 ? pastedImageSource(event.clipboardData?.getData("text/html") ?? "") : undefined;
void addFiles(files, false, source);
}; };
const dragOver = (event: DragEvent) => { const dragOver = (event: DragEvent) => {
if (event.dataTransfer?.types.includes("Files")) { if (event.dataTransfer?.types.includes("Files")) {
+4 -3
View File
@@ -67,7 +67,7 @@
cursor: default; cursor: default;
} }
.rs-pm button:not(.rs-picker-row):not([role^="menuitem"]):focus-visible, .rs-pm button:not(.rs-picker-row):not([role^="menuitem"]):focus-visible,
.rs-pm input:not(.rs-find-bar input):focus-visible, .rs-pm input:not(:where(.rs-find-bar input)):focus-visible,
.rs-pm select:focus-visible, .rs-pm select:focus-visible,
.rs-pm textarea:focus-visible { .rs-pm textarea:focus-visible {
outline: 1px solid var(--pm-accent); outline: 1px solid var(--pm-accent);
@@ -196,7 +196,8 @@
.pm-search-row input { .pm-search-row input {
width: min(340px, 100%); width: min(340px, 100%);
} }
.rs-pm input:not(.rs-find-bar input), /* The find bar exclusion adds no specificity, so the rules of each control can replace these defaults. */
.rs-pm input:not(:where(.rs-find-bar input)),
.rs-pm select, .rs-pm select,
.rs-pm textarea { .rs-pm textarea {
background: var(--pm-field-surface); background: var(--pm-field-surface);
@@ -205,7 +206,7 @@
padding: 6px 8px; padding: 6px 8px;
min-height: 30px; min-height: 30px;
} }
.rs-pm input[type="checkbox"]:not(.rs-find-bar input) { .rs-pm input[type="checkbox"]:not(:where(.rs-find-bar input)) {
min-height: 0; min-height: 0;
width: 16px; width: 16px;
height: 16px; height: 16px;
+8
View File
@@ -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", "Open link in default browser",
"Ouvrir le lien dans le navigateur par défaut", "Ouvrir le lien dans le navigateur par défaut",
@@ -4065,6 +4071,8 @@ export const messageRows: [string, string, string, string][] = [
["Unlink {name}", "Délier {name}", "{name} のリンクを解除", "取消关联 {name}"], ["Unlink {name}", "Délier {name}", "{name} のリンクを解除", "取消关联 {name}"],
["Unsaved changes", "Modifications non enregistrées", "未保存の変更", "未保存的更改"], ["Unsaved changes", "Modifications non enregistrées", "未保存の変更", "未保存的更改"],
["Use a PNG, JPEG, GIF, or WebP image.", "Utilisez une image PNG, JPEG, GIF ou WebP.", "PNG、JPEG、GIF、WebP のいずれかの画像を使用してください。", "请使用 PNG、JPEG、GIF 或 WebP 图片。"], ["Use a PNG, JPEG, GIF, or WebP image.", "Utilisez une image PNG, JPEG, GIF ou WebP.", "PNG、JPEG、GIF、WebP のいずれかの画像を使用してください。", "请使用 PNG、JPEG、GIF 或 WebP 图片。"],
["The website refused the original image, so RuneStone added only its first frame. To keep the animation, copy the image in the RuneStone browser. You can also save the image and add the saved file.", "Le site web a refusé l’image d’origine. RuneStone n’en a donc ajouté que la première trame. Pour conserver l’animation, copiez l’image dans le navigateur de RuneStone. Vous pouvez aussi enregistrer l’image, puis ajouter le fichier enregistré.", "Web サイトが元の画像を拒否したため、RuneStone は最初のフレームだけを追加しました。アニメーションを保つには、RuneStone のブラウザーで画像をコピーしてください。画像を保存して、保存したファイルを追加することもできます。", "网站拒绝提供原始图片,因此 RuneStone 只添加了第一帧。要保留动画,请在 RuneStone 浏览器中复制图片。也可以保存图片,然后添加保存的文件。"],
["The image file is empty. A browser can give an empty file when the website refuses a download. To add the image, copy it in the RuneStone browser. You can also save the image and add the saved file.", "Le fichier image est vide. Un navigateur peut fournir un fichier vide quand le site web refuse un téléchargement. Pour ajouter l’image, copiez-la dans le navigateur de RuneStone. Vous pouvez aussi enregistrer l’image, puis ajouter le fichier enregistré.", "画像ファイルが空です。Web サイトがダウンロードを拒否すると、ブラウザーが空のファイルを渡すことがあります。画像を追加するには、RuneStone のブラウザーでコピーしてください。画像を保存して、保存したファイルを追加することもできます。", "图片文件为空。网站拒绝下载时,浏览器可能会提供空文件。要添加图片,请在 RuneStone 浏览器中复制它。也可以保存图片,然后添加保存的文件。"],
["Use an image between 1 byte and 50 MiB.", "Utilisez une image entre 1 octet et 50 Mio.", "1 バイトから 50 MiB までの画像を使用してください。", "请使用 1 字节到 50 MiB 之间的图片。"], ["Use an image between 1 byte and 50 MiB.", "Utilisez une image entre 1 octet et 50 Mio.", "1 バイトから 50 MiB までの画像を使用してください。", "请使用 1 字节到 50 MiB 之间的图片。"],
["View image {name}", "Afficher l’image {name}", "画像 {name} を表示", "查看图片 {name}"], ["View image {name}", "Afficher l’image {name}", "画像 {name} を表示", "查看图片 {name}"],
["When you save, RuneStone removes each deleted label from all cards.", "Lors de l’enregistrement, RuneStone retire chaque étiquette supprimée de toutes les cartes.", "保存すると、RuneStone は削除したラベルをすべてのカードから外します。", "保存时,RuneStone 会从所有卡片中移除每个已删除的标签。"], ["When you save, RuneStone removes each deleted label from all cards.", "Lors de l’enregistrement, RuneStone retire chaque étiquette supprimée de toutes les cartes.", "保存すると、RuneStone は削除したラベルをすべてのカードから外します。", "保存时,RuneStone 会从所有卡片中移除每个已删除的标签。"],
+2 -2
View File
@@ -37,7 +37,7 @@
onQuickOpen: () => void; onQuickOpen: () => void;
onOpenBrowser?: () => void; onOpenBrowser?: () => void;
onChange: EditorProps["onChange"]; onChange: EditorProps["onChange"];
onInsertImage: (file: File, buffer: OpenBuffer | null) => Promise<string | null>; onInsertImage: (file: File, buffer: OpenBuffer | null, source?: string) => Promise<string | null>;
onRenameTitle: EditorProps["onRenameTitle"]; onRenameTitle: EditorProps["onRenameTitle"];
tableActions: (pane: DocumentView) => EditorProps["tableActions"]; tableActions: (pane: DocumentView) => EditorProps["tableActions"];
linkActions: (pane: DocumentView) => EditorProps["linkActions"]; linkActions: (pane: DocumentView) => EditorProps["linkActions"];
@@ -108,7 +108,7 @@
split={pane.split} split={pane.split}
focusLine={activePane === pane.id ? focusLine : null} focusLine={activePane === pane.id ? focusLine : null}
{onChange} {onChange}
onInsertImage={file => onInsertImage(file, pane.buffer)} onInsertImage={(file, source) => onInsertImage(file, pane.buffer, source)}
{onRenameTitle} {onRenameTitle}
tableActions={tableActions(pane)} tableActions={tableActions(pane)}
linkActions={linkActions(pane)} linkActions={linkActions(pane)}
+1 -1
View File
@@ -29,7 +29,7 @@
focusLine: number | null; focusLine: number | null;
onChange: (value: string, id: string) => void; onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>; onRenameTitle?: (id: string, title: string) => Promise<void>;
onInsertImage?: (file: File) => Promise<string | null>; onInsertImage?: (file: File, source?: string) => Promise<string | null>;
onView?: (view: ViewMode) => void; onView?: (view: ViewMode) => void;
onSplit?: (split: boolean) => void; onSplit?: (split: boolean) => void;
onCursor?: (line: number, column: number) => void; onCursor?: (line: number, column: number) => void;
+21 -5
View File
@@ -65,10 +65,12 @@
workspaceReveal, workspaceReveal,
workspaceWrite, workspaceWrite,
workspaceWriteBytes, workspaceWriteBytes,
workspaceSaveImageUrl,
} from "$lib/workspace/api"; } from "$lib/workspace/api";
import { detectChrome } from "$lib/workspace/chrome"; import { detectChrome } from "$lib/workspace/chrome";
import { planRename, planMarkdownTitleRename, planDocumentTitleRename, renameSelection } from "$lib/workspace/renamePath"; import { planRename, planMarkdownTitleRename, planDocumentTitleRename, renameSelection } from "$lib/workspace/renamePath";
import { attachmentRel, isImagePath, isMarkdownPath } from "$lib/workspace/media"; import { attachmentRel, dataUrlExtension, isImagePath, isMarkdownPath, mayAnimate } from "$lib/workspace/media";
import { copiedImage } from "$lib/workspace/copiedImage";
import { headingLinkLine, linkFragment } from "$lib/workspace/headingLinks"; import { headingLinkLine, linkFragment } from "$lib/workspace/headingLinks";
import type { Chrome, OpenBuffer, TreeEntry, WorkspaceInfo } from "$lib/workspace/types"; import type { Chrome, OpenBuffer, TreeEntry, WorkspaceInfo } from "$lib/workspace/types";
@@ -775,21 +777,35 @@
}); });
} }
async function insertImage(file: File, note = buffer): Promise<string | null> { /** `source` is the web address of the original of a copied image. `file` is its still copy. */
async function insertImage(file: File, note = buffer, source?: string): Promise<string | null> {
if (!note || note.kind !== "text" || !isMarkdownPath(note.relPath)) { if (!note || note.kind !== "text" || !isMarkdownPath(note.relPath)) {
return null; return null;
} }
const noteRel = note.relPath; const noteRel = note.relPath;
const current = documents; const current = documents;
try { try {
const rel = attachmentRel(file.name); let rel = attachmentRel(file.name);
const dataUrl = await readFileDataUrl(file); const stem = rel.replace(/\.[^./]+$/, "");
// The RuneStone browser keeps the bytes of the image that it copied. For a copy from another browser, download the original of a format with frames.
const copied = source ? await copiedImage(source) : undefined;
const copiedExtension = copied ? dataUrlExtension(copied) : undefined;
const download = !copiedExtension && !!source && mayAnimate(source);
// The host sets the extension from the downloaded file. A failed download keeps the still copy.
const downloaded = download && source ? await workspaceSaveImageUrl(source, stem).catch(() => null) : null;
if (downloaded) rel = downloaded;
else {
if (copiedExtension) rel = `${stem}.${copiedExtension}`;
const dataUrl = copied && copiedExtension ? copied : await readFileDataUrl(file);
const base64 = dataUrl.split(",")[1]; const base64 = dataUrl.split(",")[1];
if (!base64) { if (!base64) {
error = $t("The image file is empty. A browser can give an empty file when the website refuses a download. To add the image, copy it in the RuneStone browser. You can also save the image and add the saved file.");
return null; return null;
} }
if (documents !== current || switching) return null; if (documents !== current || switching) return null;
await workspaceWriteBytes(rel, base64); await workspaceWriteBytes(rel, base64);
if (download) error = $t("The website refused the original image, so RuneStone added only its first frame. To keep the animation, copy the image in the RuneStone browser. You can also save the image and add the saved file.");
}
if (documents !== current) return null; if (documents !== current) return null;
session.changed([rel]); session.changed([rel]);
return `![](${"../".repeat(noteRel.split("/").length - 1)}${rel})`; return `![](${"../".repeat(noteRel.split("/").length - 1)}${rel})`;
@@ -1379,7 +1395,7 @@
onQuickOpen={() => quickOpen = true} onQuickOpen={() => quickOpen = true}
onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined} onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined}
{onChange} {onChange}
onInsertImage={(file, tab) => insertImage(file, tab)} onInsertImage={(file, tab, source) => insertImage(file, tab, source)}
onRenameTitle={renameNoteTitle} onRenameTitle={renameNoteTitle}
tableActions={(pane) => ({ onSearch: searchSelection, onExtract: (markdown, label, valid) => extractSelection(markdown, label, valid, pane.buffer) })} tableActions={(pane) => ({ onSearch: searchSelection, onExtract: (markdown, label, valid) => extractSelection(markdown, label, valid, pane.buffer) })}
linkActions={(pane) => ({ linkActions={(pane) => ({
+15
View File
@@ -23,9 +23,24 @@
const folderName = (path: string) => path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path; const folderName = (path: string) => path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path;
const removeTooltip = (node: HTMLElement) => ({ destroy: attachTooltip(node, () => tr("Remove from recent workspaces")) }); const removeTooltip = (node: HTMLElement) => ({ destroy: attachTooltip(node, () => tr("Remove from recent workspaces")) });
const destination = $derived(parent ? `${parent.replace(/[\\/]+$/, "")}${parent.includes("\\") ? "\\" : "/"}${name.trim()}` : $t("Choose where to create your workspace.")); const destination = $derived(parent ? `${parent.replace(/[\\/]+$/, "")}${parent.includes("\\") ? "\\" : "/"}${name.trim()}` : $t("Choose where to create your workspace."));
// A press on the anchor closes the open menu before the click. Then the click must not open it again.
let pressedOpen = false;
$effect(() => {
const target = anchor;
if (!target) return;
const press = () => {
pressedOpen = menu.matches(":popover-open");
// The click comes in the same task as the release. A drag away from the anchor gives no click.
if (pressedOpen) window.addEventListener("pointerup", () => setTimeout(() => { pressedOpen = false; }), { once: true });
};
target.addEventListener("pointerdown", press);
return () => target.removeEventListener("pointerdown", press);
});
export async function show() { export async function show() {
if (busy || creating) return; if (busy || creating) return;
if (pressedOpen) { pressedOpen = false; return; }
if (menu.matches(":popover-open")) { menu.hidePopover(); return; } if (menu.matches(":popover-open")) { menu.hidePopover(); return; }
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null; returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
error = ""; loading = true; error = ""; loading = true;
+2
View File
@@ -34,6 +34,8 @@
<path d="m6 9 6 6 6-6" /> <path d="m6 9 6 6 6-6" />
{:else if icon === "chevrons-up-down"} {:else if icon === "chevrons-up-down"}
<path d="m7 15 5 5 5-5M7 9l5-5 5 5" /> <path d="m7 15 5 5 5-5M7 9l5-5 5 5" />
{:else if icon === "scroll"}
<path d="M12 3v5m-3-2 3-3 3 3M12 21v-5m-3 2 3 3 3-3M3 12h5m-2-3-3 3 3 3M21 12h-5m2-3 3 3-3 3" /><circle cx="12" cy="12" r="1" />
{:else if icon === "maximize"} {:else if icon === "maximize"}
<path d="M8 3H3v5M16 3h5v5M21 16v5h-5M8 21H3v-5" /> <path d="M8 3H3v5M16 3h5v5M21 16v5h-5M8 21H3v-5" />
{:else if icon === "minimize"} {:else if icon === "minimize"}
+1
View File
@@ -23,6 +23,7 @@
| "more" | "more"
| "chevron-down" | "chevron-down"
| "chevrons-up-down" | "chevrons-up-down"
| "scroll"
| "up" | "up"
| "down" | "down"
| "maximize" | "maximize"
+10
View File
@@ -83,6 +83,16 @@ export function workspaceWriteBytes(rel: string, base64: string): Promise<void>
return invoke("workspace_write_bytes", { rel, base64 }); return invoke("workspace_write_bytes", { rel, base64 });
} }
/** Download a web image to `rel` plus the extension of its format. Returns the path of the new file. */
export function workspaceSaveImageUrl(url: string, rel: string): Promise<string> {
return invoke("workspace_save_image_url", { url, rel });
}
/** Download a web image. Returns it as a data URL. */
export function workspaceDownloadImage(url: string): Promise<string> {
return invoke("workspace_download_image", { url });
}
export type CopyResult = { export type CopyResult = {
name: string; name: string;
rel_path: string; rel_path: string;
+16
View File
@@ -0,0 +1,16 @@
/**
* The original of the last image that Copy image took in the RuneStone browser.
* The browser takes the bytes that the page loaded, so a pasted GIF keeps its frames.
* This also works when the website refuses a second download of the image.
*/
let last: { url: string; data: Promise<string | undefined> } | undefined;
/** Keep the original of a copied image. `data` gives its data URL. */
export function keepCopiedImage(url: string, data: Promise<string | undefined>) {
last = { url, data: data.catch(() => undefined) };
}
/** The data URL of the original of `url`, when the RuneStone browser copied that image last. */
export async function copiedImage(url: string): Promise<string | undefined> {
return last?.url === url ? last.data : undefined;
}
+33
View File
@@ -96,6 +96,39 @@ export function attachmentRel(fileName: string): string {
return `attachments/${stamp}-${crypto.randomUUID()}-${safe}`; return `attachments/${stamp}-${crypto.randomUUID()}-${safe}`;
} }
const ENTITIES: Record<string, string> = { amp: "&", quot: '"', apos: "'", "#39": "'", lt: "<", gt: ">" };
/**
* The web address of a copied image. A browser puts only the first frame on the clipboard,
* with HTML that names the original file.
*/
export function pastedImageSource(html: string): string | undefined {
const images = [...html.matchAll(/<img\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi)];
if (images.length !== 1) return undefined;
const [, double, single, bare] = images[0];
const source = (double ?? single ?? bare).trim().replace(/&(amp|quot|apos|#39|lt|gt);/g, (_, name: string) => ENTITIES[name]);
try {
const url = new URL(source);
return /^https?:$/.test(url.protocol) ? url.href : undefined;
} catch {
return undefined;
}
}
/** A GIF, WebP, or AVIF address. These formats can have more frames, so the original is worth a download. */
export function mayAnimate(source: string): boolean {
return /\.(?:gif|webp|avif)$/i.test(new URL(source).pathname);
}
const EXTENSIONS: Record<string, string> = {
"image/gif": "gif", "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/avif": "avif", "image/bmp": "bmp",
};
/** The file extension of an image data URL, or undefined for another type. */
export function dataUrlExtension(data: string): string | undefined {
return EXTENSIONS[/^data:([^;,]+)[;,]/.exec(data)?.[1] ?? ""];
}
export function imageFiles(data: DataTransfer | null): File[] { export function imageFiles(data: DataTransfer | null): File[] {
return [...(data?.files ?? [])].filter(file => isImagePath(file.name)); return [...(data?.files ?? [])].filter(file => isImagePath(file.name));
} }
+5
View File
@@ -88,6 +88,11 @@ function pmCommands(test) {
else workspace.folders.add(rel); else workspace.folders.add(rel);
return null; return null;
}), }),
// The download of a copied web image: a 1 by 1 GIF. An address with "offline" fails.
workspace_download_image: ({ url }) => {
if (url.includes("offline")) throw new Error("Cannot reach the image server");
return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
},
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }), plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null, spelling_menu_install: () => null,
"plugin:window|is_maximized": () => false, "plugin:window|is_maximized": () => false,
+46 -1
View File
@@ -52,9 +52,19 @@ async function startEngine() {
return engine; return engine;
} }
// A two-frame GIF that the fixture gives only one time, as some image hosts do.
const onceGif = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAACAkQBACH5BAAKAAAALAAAAAABAAEAAAICTAEAOw==', 'base64');
/** Serve an empty page. A tab on about:blank shows the host background instead of frames (docs/ui-design.md:218). */ /** Serve an empty page. A tab on about:blank shows the host background instead of frames (docs/ui-design.md:218). */
async function startFixture() { async function startFixture() {
const server = createServer((_request, response) => { response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>'); }); let gifServed = false;
const server = createServer((request, response) => {
if (request.url === '/once.gif') {
response.writeHead(200, { 'content-type': gifServed ? 'text/html' : 'image/gif' });
response.end(gifServed ? 'Invalid request' : onceGif); gifServed = true; return;
}
response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>');
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return { url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) }; return { url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) };
} }
@@ -120,6 +130,33 @@ await runSmoke('browser/interaction', async ({ browser }) => {
await page.mouse.click(initialBox.x + 100, initialBox.y + 60); await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+v'); await page.keyboard.press('Control+a'); await page.keyboard.press('Control+v');
await expectRemote('document.querySelector("#typing").value', 'https://example.com/'); await expectRemote('document.querySelector("#typing").value', 'https://example.com/');
// Copy image keeps the GIF bytes that the page loaded, also when the website refuses a second request.
const gifUrl = `${fixture.url}once.gif`;
await evaluate(`document.body.innerHTML='<img id="gif" src="${gifUrl}" style="position:absolute;left:40px;top:300px;width:80px;height:80px">';true;`);
await expectRemote('document.querySelector("#gif").complete && document.querySelector("#gif").naturalWidth', 1);
await page.mouse.click(initialBox.x + 80, initialBox.y + 340, { button: 'right' });
await page.getByRole('menuitem', { name: 'Copy image', exact: true }).click();
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 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.locator('.surface img').waitFor();
await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); }); await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); });
@@ -143,6 +180,14 @@ await runSmoke('browser/interaction', async ({ browser }) => {
const box = await surface.boundingBox(); const box = await surface.boundingBox();
const x = box.x + 220, y = box.y + 180; const x = box.x + 220, y = box.y + 180;
await page.mouse.click(x, y, { button: 'middle' }); await page.mouse.click(x, y, { button: 'middle' });
// The marker draws the four-way scroll icon, not a text glyph that depends on the font.
const marker = page.locator('.scroll-anchor');
assert.equal(await marker.locator('svg path').count(), 1);
assert.equal(await marker.evaluate(node => node.textContent.trim()), '');
for (const theme of ['light', 'dark']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).applyAppearance({ theme: 'default', mode }), theme);
await page.screenshot({ path: path.join(output, `scroll-marker-${theme}.png`), clip: { x: x - 30, y: y - 30, width: 60, height: 60 } });
}
await page.mouse.move(x + 90, y + 120); await page.mouse.move(x + 90, y + 120);
await page.waitForTimeout(1500); await page.waitForTimeout(1500);
const scrolled = await evaluate('({x:scrollX,y:scrollY})'); const scrolled = await evaluate('({x:scrollX,y:scrollY})');
+52 -1
View File
@@ -28,6 +28,13 @@ await runSmoke("editor/images", async ({ page }) => {
if (test.failWrite) throw new Error("Image write failed"); if (test.failWrite) throw new Error("Image write failed");
workspace.files.set(args.rel, args.base64); workspace.files.set(args.rel, args.base64);
}, },
// The download of a copied web image. The host adds the extension of the downloaded format.
workspace_save_image_url: args => {
if (args.url.includes("offline")) throw new Error("Cannot reach the image server");
const rel = args.rel + ".gif";
workspace.files.set(rel, btoa('<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>'));
return rel;
},
workspace_read_data_url: ({ rel }) => { workspace_read_data_url: ({ rel }) => {
if (!workspace.files.has(rel)) throw new Error("missing image"); if (!workspace.files.has(rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + workspace.files.get(rel); return "data:image/svg+xml;base64," + workspace.files.get(rel);
@@ -196,5 +203,49 @@ await runSmoke("editor/images", async ({ page }) => {
await page.waitForFunction(() => document.querySelector(".md-image-frame img")); await page.waitForFunction(() => document.querySelector(".md-image-frame img"));
await page.keyboard.press("Control+s"); await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/second.md").includes("pasted.svg")); await page.waitForFunction(() => window.__TEST__.files.get("notes/second.md").includes("pasted.svg"));
console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode and undo passed."); // A browser copies the still first frame of a GIF. RuneStone saves the original file from the address in the HTML.
async function pasteWebImage(src) {
await page.locator(".cm-content").evaluate((element, src) => {
const data = new DataTransfer();
data.items.add(new File(["png"], "image.png", { type: "image/png" }));
data.setData("text/html", `<html><body>\r\n<!--StartFragment--><img src="${src}"/><!--EndFragment-->\r\n</body>\r\n</html>`);
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
}, src);
}
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
const writes = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_write_bytes").length);
const writesBefore = await writes();
await pasteWebImage("https://media.example.com/cat.gif?size=large&amp;v=2");
await page.waitForFunction(() => /attachments\/[\w-]+-image\.gif\)/.test(window.__CM__.state.doc.toString()));
const download = await page.evaluate(() => window.__TEST__.calls.find(call => call.command === "workspace_save_image_url").args);
assert.equal(download.url, "https://media.example.com/cat.gif?size=large&v=2");
assert.match(download.rel, /^attachments\/[\w-]+-image$/);
assert.equal(await writes(), writesBefore);
// When the download fails, the still copy stays.
await pasteWebImage("https://offline.example.com/cat.gif");
await page.waitForFunction(() => /attachments\/[\w-]+-image\.png\)/.test(window.__CM__.state.doc.toString()));
assert.equal(await writes(), writesBefore + 1);
await page.getByText("The website refused the original image, so RuneStone added only its first frame.", { exact: false }).waitFor();
// The RuneStone browser keeps the bytes of the image that it copied. The website gets no second request.
await page.evaluate(async () => (await import("/src/lib/workspace/copiedImage.ts")).keepCopiedImage("https://offline.example.com/copied.gif",
Promise.resolve("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")));
const downloads = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_save_image_url").length);
const downloadsBefore = await downloads();
await pasteWebImage("https://offline.example.com/copied.gif");
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/-image\.gif\)/g) || []).length === 2);
assert.equal(await downloads(), downloadsBefore);
assert.match(await page.evaluate(() => window.__TEST__.calls.findLast(call => call.command === "workspace_write_bytes").args.rel), /-image\.gif$/);
// An empty file from a browser drag gives a message, not a broken image.
await page.locator(".cm-content").evaluate(element => {
const data = new DataTransfer();
data.items.add(new File([], "viprsr188.gif", { type: "image/gif" }));
const rect = element.getBoundingClientRect();
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 }));
});
await page.getByText("The image file is empty.", { exact: false }).waitFor();
assert.ok(!(await page.evaluate(() => window.__CM__.state.doc.toString())).includes("viprsr188"));
console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode, undo, web GIF pastes, copied originals, and empty files passed.");
}); });
+66
View File
@@ -0,0 +1,66 @@
// Project Management card images: a GIF copied in a web browser keeps its original file. A failed download keeps the still copy.
import assert from "node:assert/strict";
import { runSmoke } from "../_harness/index.mjs";
import { cardPath, fileText, loadWorkspace, openBoard, pane, waitForFile } from "../_harness/pmFixture.mjs";
const imageFile = id => `.runestone/pm/images/${id}.json`;
await runSmoke("features/pmImages", async ({ page }) => {
await loadWorkspace(page);
await openBoard(page, "Roadmap");
await pane(page).locator(".pm-card-title", { hasText: /^Card A$/ }).click();
const editor = page.locator("dialog.pm-card-editor[open]");
await editor.waitFor();
await editor.getByRole("button", { name: "Edit", exact: true }).click();
const description = editor.locator('textarea[aria-label="Details (Markdown)"]');
await description.fill("");
// A browser puts a still PNG on the clipboard, with HTML that names the original GIF.
async function pasteWebImage(src) {
await description.evaluate((element, src) => {
const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="), c => c.charCodeAt(0));
const data = new DataTransfer();
data.items.add(new File([png], "image.png", { type: "image/png" }));
data.setData("text/html", `<html><body><!--StartFragment--><img src="${src}"/><!--EndFragment--></body></html>`);
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
}, src);
}
const reference = name => new RegExp(`!\\[${name.replace(".", "\\.")}\\]\\(pm-image:([0-9a-f-]{36})\\)`);
await pasteWebImage("https://media.example.com/cat.gif");
await page.waitForFunction(() => /!\[image\.gif\]\(pm-image:/.test(document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value));
const download = await page.evaluate(() => window.__TEST__.calls.find(call => call.command === "workspace_download_image").args);
assert.equal(download.url, "https://media.example.com/cat.gif");
// When the download fails, the card gets the still PNG.
await pasteWebImage("https://offline.example.com/cat.gif");
await page.waitForFunction(() => /!\[image\.png\]\(pm-image:/.test(document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value));
await editor.getByText("The website refused the original image, so RuneStone added only its first frame.", { exact: false }).waitFor();
// The RuneStone browser keeps the bytes of the image that it copied. The website gets no second request.
await page.evaluate(async () => (await import("/src/lib/workspace/copiedImage.ts")).keepCopiedImage("https://offline.example.com/copied.gif",
Promise.resolve("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")));
const downloads = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_download_image").length);
const downloadsBefore = await downloads();
await pasteWebImage("https://offline.example.com/copied.gif");
await page.waitForFunction(() => (document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value.match(/!\[image\.gif\]/g) || []).length === 2);
assert.equal(await downloads(), downloadsBefore);
assert.equal(await editor.getByText("The website refused the original image", { exact: false }).count(), 0, "A kept original clears the message");
// An empty file from a browser drag gives a message, not the size limit.
await description.evaluate(element => {
const data = new DataTransfer();
data.items.add(new File([], "viprsr188.gif", { type: "image/gif" }));
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data }));
});
await editor.getByText("The image file is empty.", { exact: false }).waitFor();
assert.equal(await editor.getByText("Use an image between 1 byte and 50 MiB.").count(), 0);
await editor.locator(".pm-description-actions").getByRole("button", { name: "Save", exact: true }).click();
await waitForFile(page, cardPath("card-a"), /pm-image:.*\n?[\s\S]*pm-image:/);
const body = await fileText(page, cardPath("card-a"));
const gif = reference("image.gif").exec(body)[1], png = reference("image.png").exec(body)[1];
assert.match(await fileText(page, imageFile(gif)), /"data":"data:image\/gif;base64,R0lGOD/);
assert.match(await fileText(page, imageFile(png)), /"data":"data:image\/png;base64,iVBOR/);
console.log("PASS: a pasted web GIF keeps its original file, a copied original needs no download, and failures explain the cause");
});
@@ -0,0 +1,38 @@
// Project Management label colors: each color choice of Manage labels shows its color, and the card title keeps its own field style, in both themes.
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke } from "../_harness/index.mjs";
import { loadWorkspace, openBoard, pane, setTheme } from "../_harness/pmFixture.mjs";
const rgb = hex => `rgb(${hex.slice(1).match(/../g).map(value => parseInt(value, 16)).join(", ")})`;
await runSmoke("features/pmLabelColors", async ({ page }) => {
const output = await outputDir("features/pmLabelColors");
await loadWorkspace(page);
await openBoard(page, "Roadmap");
await pane(page).locator(".pm-card-title", { hasText: /^Card A$/ }).click();
const editor = page.locator("dialog.pm-card-editor[open]");
await editor.waitFor();
// The card title is a transparent field. The default field rule of Project Management does not replace its background.
const title = editor.getByRole("textbox", { name: "Title", exact: true });
assert.equal(await title.evaluate(input => getComputedStyle(input).backgroundColor), "rgba(0, 0, 0, 0)");
await editor.getByRole("group", { name: "Card details", exact: true }).getByRole("button", { name: "Labels", exact: true }).click();
await page.getByRole("dialog", { name: "Choose labels", exact: true }).getByRole("button", { name: "Manage labels", exact: true }).click();
const manager = page.getByRole("dialog", { name: "Manage labels", exact: true });
await manager.waitFor();
const bug = manager.getByRole("group", { name: "Label Bug", exact: true });
const swatches = await bug.locator("input.pm-color-swatch").evaluateAll(inputs =>
inputs.map(input => ({ name: input.getAttribute("aria-label"), color: input.style.getPropertyValue("--pm-swatch-color"), shown: getComputedStyle(input).backgroundColor })));
assert.equal(swatches.length, 16);
for (const swatch of swatches) assert.equal(swatch.shown, rgb(swatch.color), `${swatch.name} shows its color`);
await bug.getByRole("radio", { name: "Blue", exact: true }).check();
await manager.locator(".pm-label-badge", { hasText: /^Bug$/ }).waitFor();
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await bug.screenshot({ path: path.join(output, `label-colors-${theme}.png`) });
}
console.log("PASS: label color choices and the card title field");
});
@@ -66,7 +66,12 @@ await runSmoke("workspace/openAndCreate", async ({ page }) => {
assert.equal(await menu.locator('[aria-current="true"]').count(), 1); assert.equal(await menu.locator('[aria-current="true"]').count(), 1);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "plugin:dialog|open").length), 0); assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "plugin:dialog|open").length), 0);
await page.screenshot({ path: path.join(output, "workspaces-menu.png") }); await page.screenshot({ path: path.join(output, "workspaces-menu.png") });
const opened = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length); // A second click on the switcher closes the menu. It does not open the menu again.
await trigger.click();
await menu.waitFor({ state: "hidden", timeout: 2000 });
await trigger.click();
await menu.getByText("D:\\Writing\\Notes", { exact: true }).waitFor();
const opened =await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length);
await menu.getByRole("button").filter({ hasText: "Current" }).click(); await menu.getByRole("button").filter({ hasText: "Current" }).click();
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length), opened); assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length), opened);
await page.keyboard.press("Control+o"); await page.keyboard.press("Control+o");
+47 -1
View File
@@ -1,7 +1,8 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import test from "node:test"; import test from "node:test";
import { EditorState } from "@codemirror/state"; import { EditorState } from "@codemirror/state";
import { attachmentRel, hasFileDrag, imageFiles, imageInsertion, workspaceImageLink } from "../../../src/lib/workspace/media.ts"; import { attachmentRel, dataUrlExtension, hasFileDrag, imageFiles, imageInsertion, mayAnimate, pastedImageSource, workspaceImageLink } from "../../../src/lib/workspace/media.ts";
import { copiedImage, keepCopiedImage } from "../../../src/lib/workspace/copiedImage.ts";
import { imageSource, editImageSource, imageSourceRanges } from "../../../src/lib/editor/imageSource.ts"; import { imageSource, editImageSource, imageSourceRanges } from "../../../src/lib/editor/imageSource.ts";
import { imageDrops, trackImageDrop } from "../../../src/lib/editor/imageDrop.ts"; import { imageDrops, trackImageDrop } from "../../../src/lib/editor/imageDrop.ts";
@@ -18,6 +19,51 @@ test("protected file drags and files without MIME metadata are recognized", () =
assert.deepEqual(imageFiles({ files } as unknown as DataTransfer), [files[0]]); assert.deepEqual(imageFiles({ files } as unknown as DataTransfer), [files[0]]);
}); });
test("a copied web image names its original file in the clipboard HTML", () => {
const copy = (src: string) => `<html><body>\r\n<!--StartFragment--><img src="${src}"/><!--EndFragment-->\r\n</body>\r\n</html>`;
assert.equal(pastedImageSource(copy("https://media.example.com/cat.gif")), "https://media.example.com/cat.gif");
assert.equal(pastedImageSource(copy("https://cdn.example.com/a/b.WEBP?width=200&amp;ex=1")), "https://cdn.example.com/a/b.WEBP?width=200&ex=1");
assert.equal(pastedImageSource("<img alt='x' data-src='a.png' src='http://example.com/x.avif'>"), "http://example.com/x.avif");
assert.equal(pastedImageSource("<img src=https://example.com/x.gif>"), "https://example.com/x.gif");
assert.equal(pastedImageSource(copy("https://example.com/photo.jpg")), "https://example.com/photo.jpg");
// Firefox copies the element of the page with all of its attributes.
assert.equal(pastedImageSource('<img id="img" src="https://h.example.net/om/1/x.gif" style="width:640px" onload="update()">'), "https://h.example.net/om/1/x.gif");
// A missing address and other schemes keep the clipboard copy.
assert.equal(pastedImageSource(copy("data:image/gif;base64,R0lGODlh")), undefined);
assert.equal(pastedImageSource(copy("file:///C:/cat.gif")), undefined);
assert.equal(pastedImageSource(copy("cat.gif")), undefined);
assert.equal(pastedImageSource('<img srcset="https://example.com/x.gif 1x">'), undefined);
assert.equal(pastedImageSource(""), undefined);
// A copy of a page part with two images is not a copied image.
assert.equal(pastedImageSource(copy("https://example.com/a.gif") + copy("https://example.com/b.gif")), undefined);
});
test("only formats with frames get a download, and data URLs name their extension", () => {
assert.equal(mayAnimate("https://media.example.com/cat.gif"), true);
assert.equal(mayAnimate("https://cdn.example.com/a/b.WEBP?width=200"), true);
assert.equal(mayAnimate("http://example.com/x.avif"), true);
assert.equal(mayAnimate("https://example.com/photo.jpg"), false);
assert.equal(mayAnimate("https://example.com/image?format=gif"), false);
assert.equal(dataUrlExtension("data:image/gif;base64,R0lGODlh"), "gif");
assert.equal(dataUrlExtension("data:image/jpeg;base64,/9j/"), "jpg");
assert.equal(dataUrlExtension("data:image/webp;base64,UklG"), "webp");
assert.equal(dataUrlExtension("data:image/svg+xml;base64,PHN2Zz4="), undefined);
assert.equal(dataUrlExtension("data:text/html;base64,PGh0bWw+"), undefined);
});
test("a paste uses only the original of the image that the RuneStone browser copied last", async () => {
assert.equal(await copiedImage("https://example.com/a.gif"), undefined);
let finish: (value: string) => void = () => {};
keepCopiedImage("https://example.com/a.gif", new Promise(resolve => { finish = resolve; }));
const waiting = copiedImage("https://example.com/a.gif");
finish("data:image/gif;base64,R0lGODlh");
assert.equal(await waiting, "data:image/gif;base64,R0lGODlh");
assert.equal(await copiedImage("https://example.com/b.gif"), undefined);
keepCopiedImage("https://example.com/b.gif", Promise.reject(new Error("engine stopped")));
assert.equal(await copiedImage("https://example.com/b.gif"), undefined);
assert.equal(await copiedImage("https://example.com/a.gif"), undefined, "a newer copy replaces the older one");
});
test("image batches form independent Markdown blocks without extra blank lines", () => { test("image batches form independent Markdown blocks without extra blank lines", () => {
assert.equal(imageInsertion("beforeafter", 6, 6, ["![](a.png)", "![](b.png)"]), "\n\n![](a.png)\n\n![](b.png)\n\n"); assert.equal(imageInsertion("beforeafter", 6, 6, ["![](a.png)", "![](b.png)"]), "\n\n![](a.png)\n\n![](b.png)\n\n");
assert.equal(imageInsertion("before\n\nafter", 8, 8, ["![](a.png)"]), "![](a.png)\n\n"); assert.equal(imageInsertion("before\n\nafter", 8, 8, ["![](a.png)"]), "![](a.png)\n\n");