mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
feat(web): add GPU recovery, canvas selection menu, lazy PDF client, and zero-3p-JS gate
Add WebGL2 context loss recovery, epoch-guarded async restore, single-flight fallback locking, and WebGPU canvas compositing to the Web Mobile host. Flush pending IndexedDB writes before legacy shell navigation and recreate a visible retry banner on flush failure. Add canvas-drawn selection highlights, teardrop handles, pointerup action triggers, and selection-guarded clipboard actions. Add a lazy hayro PDF worker client with crash recovery, clamped scale rendering, transfer-safe deduplication, and asset root pinning. Add a static zero-third-party-JS gate script and wire both web host gates into mobile CI.
This commit is contained in:
1 parent
9a3195bf81
commit
e88ee8e9fe
12 files changed
+5621
-108
No files matched your search
@@ -39,6 +39,7 @@ jobs:
|
||||
working-directory: packages/frontend
|
||||
run: |
|
||||
node --test hosts/web/tests/*.test.mjs
|
||||
node hosts/web/scripts/verify-zero-third-party-js.mjs
|
||||
node --test perf/compare-n3.test.mjs
|
||||
|
||||
- name: Install Linux fontconfig, Mesa Lavapipe Vulkan, and CJK fallback font
|
||||
@@ -161,6 +162,9 @@ jobs:
|
||||
- name: Verify real-browser IndexedDB storage and V1 Yjs extraction
|
||||
run: node hosts/web/scripts/verify-idb-real-browser.mjs
|
||||
|
||||
- name: Verify real-browser S3-Web GPU recovery, selection menu, and lazy hayro PDF worker
|
||||
run: node hosts/web/scripts/verify-s3-web-real-browser.mjs
|
||||
|
||||
android-host:
|
||||
name: Android Thin Host (NDK .so Link & kotlinc)
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
@@ -143,22 +143,49 @@ impl RawWorkerState {
|
||||
let page_index =
|
||||
u32::from_le_bytes([payload[0], payload[1], payload[2], payload[3]])
|
||||
as usize;
|
||||
Self::render_pdf_frame(&mut self.engine, page_index, 2.0, &payload[4..])
|
||||
}
|
||||
#[cfg(not(feature = "pdf"))]
|
||||
{
|
||||
Err("pdf feature disabled in this worker".to_string())
|
||||
}
|
||||
}
|
||||
6 => {
|
||||
#[cfg(feature = "pdf")]
|
||||
{
|
||||
if payload.len() < 8 {
|
||||
return Err("missing pdf page_index and scale header".to_string());
|
||||
}
|
||||
let page_index =
|
||||
u32::from_le_bytes([payload[0], payload[1], payload[2], payload[3]])
|
||||
as usize;
|
||||
let raw_scale =
|
||||
f32::from_le_bytes([payload[4], payload[5], payload[6], payload[7]]);
|
||||
let scale = if raw_scale.is_finite() && raw_scale > 0.0 {
|
||||
raw_scale.clamp(0.25, 4.0)
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
Self::render_pdf_frame(&mut self.engine, page_index, scale, &payload[8..])
|
||||
}
|
||||
#[cfg(not(feature = "pdf"))]
|
||||
{
|
||||
Err("pdf feature disabled in this worker".to_string())
|
||||
}
|
||||
}
|
||||
7 => {
|
||||
#[cfg(feature = "pdf")]
|
||||
{
|
||||
let handle = self
|
||||
.engine
|
||||
.load_pdf(payload[4..].to_vec())
|
||||
.load_pdf(payload.to_vec())
|
||||
.map_err(|e| e.to_string())?;
|
||||
let render = self
|
||||
.engine
|
||||
.render_pdf_page(handle, PdfRenderRequest::for_page(page_index, 2.0));
|
||||
let count = self.engine.pdf_page_count(handle);
|
||||
let _ = self.engine.unload_pdf(handle);
|
||||
let (page_count, buf) = render.map_err(|e| e.to_string())?;
|
||||
// `buf.pixels` holds tightly packed premultiplied RGBA8 pixels (`width * height * 4`).
|
||||
let mut frame = Vec::with_capacity(13 + buf.pixels.len());
|
||||
let page_count = count.map_err(|e| e.to_string())?;
|
||||
let mut frame = Vec::with_capacity(5);
|
||||
frame.push(1);
|
||||
frame.extend_from_slice(&(page_count as u32).to_le_bytes());
|
||||
frame.extend_from_slice(&buf.width_px.to_le_bytes());
|
||||
frame.extend_from_slice(&buf.height_px.to_le_bytes());
|
||||
frame.extend_from_slice(&buf.pixels);
|
||||
Ok(frame)
|
||||
}
|
||||
#[cfg(not(feature = "pdf"))]
|
||||
@@ -169,6 +196,28 @@ impl RawWorkerState {
|
||||
other => Err(format!("unknown worker opcode {other}")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "pdf")]
|
||||
fn render_pdf_frame(
|
||||
engine: &mut PreviewEngine,
|
||||
page_index: usize,
|
||||
scale: f32,
|
||||
pdf_bytes: &[u8],
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let handle = engine
|
||||
.load_pdf(pdf_bytes.to_vec())
|
||||
.map_err(|e| e.to_string())?;
|
||||
let render = engine.render_pdf_page(handle, PdfRenderRequest::for_page(page_index, scale));
|
||||
let _ = engine.unload_pdf(handle);
|
||||
let (page_count, buf) = render.map_err(|e| e.to_string())?;
|
||||
let mut frame = Vec::with_capacity(13 + buf.pixels.len());
|
||||
frame.push(1);
|
||||
frame.extend_from_slice(&(page_count as u32).to_le_bytes());
|
||||
frame.extend_from_slice(&buf.width_px.to_le_bytes());
|
||||
frame.extend_from_slice(&buf.height_px.to_le_bytes());
|
||||
frame.extend_from_slice(&buf.pixels);
|
||||
Ok(frame)
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears the worker's raw request buffer ahead of streaming a new request.
|
||||
|
||||
@@ -9,6 +9,7 @@ It uses plain HTML and standard ES modules with JSDoc types.
|
||||
- Keep zero third-party npm imports in `src/*.js`. Use relative ES module imports only.
|
||||
- Keep `index.html` Content Security Policy free of third-party script domains.
|
||||
- Keep permanent visual DOM in `index.html` limited to `<canvas id="app-canvas">` and `<textarea id="ime">`.
|
||||
|
||||
- Keep at most one `aria-hidden="true"` zero-size safe-area probe in `index.html`.
|
||||
- Keep `#embed-layer` empty at rest. Strip `allow-same-origin` from every user HTML iframe.
|
||||
- Load Cloudflare Turnstile only inside `sign-in.html`, and only after `/api/auth/captcha` returns a challenge.
|
||||
@@ -16,16 +17,18 @@ It uses plain HTML and standard ES modules with JSDoc types.
|
||||
|
||||
## Verification
|
||||
|
||||
Run the deterministic Node test suite from `packages/frontend/`:
|
||||
Run the deterministic Node test suite and zero-third-party-JS gate from `packages/frontend/`:
|
||||
|
||||
```sh
|
||||
node --test hosts/web/tests/*.test.mjs
|
||||
node hosts/web/scripts/verify-zero-third-party-js.mjs
|
||||
```
|
||||
|
||||
After building the four `blocksuite-preview` `wasm32-unknown-unknown` workers, stage the binaries plus static fonts and run the nested-route end-to-end worker test:
|
||||
After building the four `blocksuite-preview` `wasm32-unknown-unknown` workers, stage the binaries plus static fonts and run the end-to-end worker and real-browser verification scripts:
|
||||
|
||||
```sh
|
||||
node hosts/web/scripts/stage-preview-workers.mjs /tmp/preview-wasm dev-local
|
||||
node hosts/web/scripts/verify-preview-workers-e2e.mjs
|
||||
node hosts/web/scripts/verify-idb-real-browser.mjs
|
||||
node hosts/web/scripts/verify-s3-web-real-browser.mjs
|
||||
```
|
||||
@@ -0,0 +1,839 @@
|
||||
#!/usr/bin/env node
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* Real-browser Headless Chromium E2E gate for S3-Web thin host capabilities.
|
||||
*
|
||||
* Loads the production `index.html` + `src/host.js` + `src/default-app-entry.js`
|
||||
* directly in a preinstalled Chromium binary (never runs `playwright install`)
|
||||
* and always stops the browser process by its exact PID inside `finally`.
|
||||
*
|
||||
* Verifies in real Chromium (`390x844` mobile viewport @ 2x DPR):
|
||||
* 1. Production `index.html` boot removes `#boot` after first WebGL2 frame,
|
||||
* with 0 `pdf-worker.wasm` requests at boot.
|
||||
* 2. `WEBGL_lose_context` recovery on real `#app-canvas` (`webglcontextlost`
|
||||
* calls `preventDefault()`, pauses input; `webglcontextrestored` rebuilds
|
||||
* and redraws without reload).
|
||||
* 3. Post-boot `fallback-blocked` recreates `#boot` with visible error text
|
||||
* and clickable `#gpu-fallback-retry` button; clicking `#gpu-fallback-retry`
|
||||
* after IDB recovers flushes pending writes and triggers a single fallback.
|
||||
* 4. Touch and pointer selection overlay on real `index.html` `#app-canvas`:
|
||||
* touch `pointerdown` does not fire action, slide-off cancels, touch
|
||||
* `pointerup` fires `Copy` / `Cut` / `Paste` (Cut preserves text on write
|
||||
* failure), with zero floating DOM nodes.
|
||||
* 5. Lazy `hayro` `pdf-worker.wasm` multi-page render with distinct scales
|
||||
* (`0.5`, `1`, `2`), lightweight `page_count`, transfer-safe LRU cache,
|
||||
* and WebGL2 texture compositing onto `#app-canvas`.
|
||||
*
|
||||
* Pass `--out-dir <dir>` to capture `web-selection-menu.png` and
|
||||
* `web-pdf-worker-preview.png` directly from production `index.html`.
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync, spawn } from 'node:child_process';
|
||||
import {
|
||||
closeSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
openSync,
|
||||
readFileSync,
|
||||
readSync,
|
||||
rmSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import { createServer } from 'node:http';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { extname, join, normalize, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
|
||||
|
||||
const MIME_TYPES = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.mjs': 'text/javascript; charset=utf-8',
|
||||
'.wasm': 'application/wasm',
|
||||
'.ttf': 'font/ttf',
|
||||
};
|
||||
|
||||
function parseOutDir() {
|
||||
const idx = process.argv.indexOf('--out-dir');
|
||||
if (idx >= 0 && process.argv[idx + 1]) {
|
||||
return resolve(process.argv[idx + 1]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isSnapWrapper(bin) {
|
||||
if (!bin.startsWith('/usr/bin/chromium')) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const fd = openSync(bin, 'r');
|
||||
try {
|
||||
const buf = Buffer.alloc(256);
|
||||
const n = readSync(fd, buf, 0, buf.length, 0);
|
||||
const head = buf.subarray(0, n).toString('utf8');
|
||||
return head.startsWith('#!') && /snap/i.test(head);
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function findChromiumBinary() {
|
||||
const candidates = [
|
||||
process.env.CHROME_PATH,
|
||||
process.env.CHROME_BIN,
|
||||
'/usr/bin/google-chrome-stable',
|
||||
'/usr/bin/google-chrome',
|
||||
'/usr/bin/chromium',
|
||||
'/usr/bin/chromium-browser',
|
||||
].filter(Boolean);
|
||||
let snapFallback = null;
|
||||
for (const bin of candidates) {
|
||||
if (!bin || !existsSync(bin)) {
|
||||
continue;
|
||||
}
|
||||
if (isSnapWrapper(bin)) {
|
||||
snapFallback ??= bin;
|
||||
continue;
|
||||
}
|
||||
return bin;
|
||||
}
|
||||
const pwDir = join(process.env.HOME || '', '.cache/ms-playwright');
|
||||
if (existsSync(pwDir)) {
|
||||
const found = execFileSync(
|
||||
'find',
|
||||
[pwDir, '-name', 'chrome', '-type', 'f'],
|
||||
{ encoding: 'utf8' }
|
||||
)
|
||||
.split('\n')
|
||||
.map(line => line.trim())
|
||||
.find(Boolean);
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
if (snapFallback) {
|
||||
return snapFallback;
|
||||
}
|
||||
throw new Error('No preinstalled Chromium binary found on this machine');
|
||||
}
|
||||
|
||||
function ensureStagedPdfWasm() {
|
||||
const target = join(WEB_ROOT, 'assets/pdf-worker.dev-local.wasm');
|
||||
if (!existsSync(target)) {
|
||||
throw new Error(
|
||||
`Missing staged pdf-worker wasm: ${target}. Run stage-preview-workers.mjs first.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
ensureStagedPdfWasm();
|
||||
|
||||
const outDir = parseOutDir();
|
||||
if (outDir) {
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
}
|
||||
|
||||
let wasmRequestCount = 0;
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
const url = new URL(req.url || '/', 'http://127.0.0.1');
|
||||
if (url.pathname.includes('pdf-worker') && url.pathname.endsWith('.wasm')) {
|
||||
wasmRequestCount += 1;
|
||||
}
|
||||
const pathname = url.pathname === '/' ? '/index.html' : url.pathname;
|
||||
const rel = normalize(pathname).replace(/^\/+/, '');
|
||||
const full = resolve(WEB_ROOT, rel);
|
||||
if (!full.startsWith(WEB_ROOT) || !existsSync(full)) {
|
||||
res.writeHead(404);
|
||||
res.end('not found');
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, {
|
||||
'content-type': MIME_TYPES[extname(full)] || 'application/octet-stream',
|
||||
});
|
||||
res.end(readFileSync(full));
|
||||
});
|
||||
|
||||
const chromeBin = findChromiumBinary();
|
||||
const profileDir = mkdtempSync(join(tmpdir(), 'affine-s3-web-e2e-'));
|
||||
await new Promise(resolveListen =>
|
||||
server.listen(0, '127.0.0.1', resolveListen)
|
||||
);
|
||||
const address = server.address();
|
||||
const port = typeof address === 'object' && address ? address.port : 0;
|
||||
|
||||
const chromeProc = spawn(
|
||||
chromeBin,
|
||||
[
|
||||
'--headless=new',
|
||||
'--no-sandbox',
|
||||
'--enable-unsafe-swiftshader',
|
||||
'--disable-dev-shm-usage',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--remote-debugging-port=0',
|
||||
`--user-data-dir=${profileDir}`,
|
||||
'about:blank',
|
||||
],
|
||||
{ stdio: ['ignore', 'ignore', 'pipe'] }
|
||||
);
|
||||
|
||||
let ws = null;
|
||||
try {
|
||||
const wsUrl = await new Promise((resolveWs, rejectWs) => {
|
||||
let stderrBuf = '';
|
||||
const timer = setTimeout(
|
||||
() => rejectWs(new Error(`Chromium DevTools timeout: ${stderrBuf}`)),
|
||||
15000
|
||||
);
|
||||
chromeProc.stderr.on('data', chunk => {
|
||||
stderrBuf += String(chunk);
|
||||
const m = stderrBuf.match(/DevTools listening on (ws:\/\/\S+)/);
|
||||
if (m) {
|
||||
clearTimeout(timer);
|
||||
resolveWs(m[1]);
|
||||
}
|
||||
});
|
||||
chromeProc.once('exit', code => {
|
||||
clearTimeout(timer);
|
||||
rejectWs(new Error(`Chromium exited early (${code}): ${stderrBuf}`));
|
||||
});
|
||||
});
|
||||
|
||||
const debugPort = new URL(wsUrl).port;
|
||||
const targets = await (
|
||||
await fetch(`http://127.0.0.1:${debugPort}/json/list`)
|
||||
).json();
|
||||
const pageTarget = targets.find(t => t.type === 'page') || targets[0];
|
||||
ws = new WebSocket(pageTarget.webSocketDebuggerUrl);
|
||||
await new Promise((ok, fail) => {
|
||||
ws.addEventListener('open', ok, { once: true });
|
||||
ws.addEventListener('error', fail, { once: true });
|
||||
});
|
||||
|
||||
let nextId = 1;
|
||||
const pending = new Map();
|
||||
ws.addEventListener('message', ev => {
|
||||
const msg = JSON.parse(String(ev.data));
|
||||
if (msg.id && pending.has(msg.id)) {
|
||||
const { ok, fail } = pending.get(msg.id);
|
||||
pending.delete(msg.id);
|
||||
if (msg.error) fail(new Error(msg.error.message));
|
||||
else ok(msg.result);
|
||||
}
|
||||
});
|
||||
const send = (method, params = {}) =>
|
||||
new Promise((ok, fail) => {
|
||||
const id = nextId++;
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
fail(new Error(`CDP timeout after 25s for ${method}`));
|
||||
}, 25000);
|
||||
pending.set(id, {
|
||||
ok: val => {
|
||||
clearTimeout(timer);
|
||||
ok(val);
|
||||
},
|
||||
fail: err => {
|
||||
clearTimeout(timer);
|
||||
fail(err);
|
||||
},
|
||||
});
|
||||
ws.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
const evalJs = async expression => {
|
||||
const r = await send('Runtime.evaluate', {
|
||||
expression,
|
||||
awaitPromise: true,
|
||||
returnByValue: true,
|
||||
});
|
||||
if (r.exceptionDetails) {
|
||||
throw new Error(
|
||||
r.exceptionDetails.exception?.description || r.exceptionDetails.text
|
||||
);
|
||||
}
|
||||
return r.result?.value;
|
||||
};
|
||||
|
||||
await send('Page.enable');
|
||||
await send('Emulation.setDeviceMetricsOverride', {
|
||||
width: 390,
|
||||
height: 844,
|
||||
deviceScaleFactor: 2,
|
||||
mobile: true,
|
||||
});
|
||||
await send('Emulation.setTouchEmulationEnabled', {
|
||||
enabled: true,
|
||||
maxTouchPoints: 1,
|
||||
});
|
||||
await send('Emulation.setEmitTouchEventsForMouse', { enabled: false });
|
||||
|
||||
// Load production index.html directly.
|
||||
await send('Page.navigate', {
|
||||
url: `http://127.0.0.1:${port}/index.html`,
|
||||
});
|
||||
|
||||
let booted = false;
|
||||
for (let i = 0; i < 100; i += 1) {
|
||||
booted = Boolean(
|
||||
await evalJs(
|
||||
'Boolean(window.__AFFINE_WEB_HOST__ && window.__AFFINE_WEB_HOST__.selectionOverlay && !document.getElementById("boot"))'
|
||||
)
|
||||
);
|
||||
if (booted) break;
|
||||
await new Promise(r => setTimeout(r, 50));
|
||||
}
|
||||
assert.equal(booted, true, 'Production index.html did not finish boot');
|
||||
assert.equal(
|
||||
wasmRequestCount,
|
||||
0,
|
||||
'pdf-worker.wasm must not be requested during boot'
|
||||
);
|
||||
|
||||
// 1. Real WEBGL_lose_context recovery on production #app-canvas.
|
||||
const webglRecovery = await evalJs(`(async () => {
|
||||
const host = window.__AFFINE_WEB_HOST__;
|
||||
const canvas = host.canvas;
|
||||
const gl = canvas.getContext('webgl2');
|
||||
const ext = gl?.getExtension('WEBGL_lose_context');
|
||||
if (!gl || !ext) {
|
||||
return { ok: false, reason: 'no-webgl2' };
|
||||
}
|
||||
let lostPrevented = false;
|
||||
const lostP = new Promise(resolve => {
|
||||
canvas.addEventListener('webglcontextlost', ev => {
|
||||
lostPrevented = ev.defaultPrevented;
|
||||
resolve({
|
||||
status: host.gpuRecovery.getState().status,
|
||||
inputPaused: host.isInputPaused(),
|
||||
imeReadOnly: host.ime.readOnly,
|
||||
});
|
||||
}, { once: true });
|
||||
});
|
||||
const restoredP = new Promise(resolve => {
|
||||
canvas.addEventListener('webglcontextrestored', () => {
|
||||
setTimeout(() => {
|
||||
resolve({
|
||||
status: host.gpuRecovery.getState().status,
|
||||
inputPaused: host.isInputPaused(),
|
||||
imeReadOnly: host.ime.readOnly,
|
||||
restoreCount: host.gpuRecovery.getState().restoreCount,
|
||||
});
|
||||
}, 50);
|
||||
}, { once: true });
|
||||
});
|
||||
ext.loseContext();
|
||||
const duringLost = await lostP;
|
||||
await new Promise(r => setTimeout(r, 0));
|
||||
ext.restoreContext();
|
||||
const afterRestore = await restoredP;
|
||||
return { ok: true, lostPrevented, duringLost, afterRestore };
|
||||
})()`);
|
||||
assert.equal(webglRecovery.ok, true);
|
||||
assert.equal(webglRecovery.lostPrevented, true);
|
||||
assert.equal(webglRecovery.duringLost.status, 'context-lost');
|
||||
assert.equal(webglRecovery.duringLost.inputPaused, true);
|
||||
assert.equal(webglRecovery.afterRestore.status, 'ready');
|
||||
assert.equal(webglRecovery.afterRestore.inputPaused, false);
|
||||
assert.ok(webglRecovery.afterRestore.restoreCount >= 1);
|
||||
|
||||
// 2. Post-boot fallback-blocked recreates #boot with visible message and clickable #gpu-fallback-retry.
|
||||
const blockedRetry = await evalJs(`(async () => {
|
||||
const { createGpuRecoveryController, hideRuntimeFatal, showBootFatal } = await import('/src/host.js');
|
||||
const { createIdbWorkspaceStorage, createPendingWriteFlusher } = await import('/src/idb-storage.js');
|
||||
|
||||
const storage = createIdbWorkspaceStorage({
|
||||
flavour: 'local',
|
||||
type: 'workspace',
|
||||
id: 's3-web-retry-e2e',
|
||||
});
|
||||
const flusher = createPendingWriteFlusher(storage);
|
||||
flusher.enqueue({
|
||||
docId: 'doc-unsaved-r2',
|
||||
bin: new TextEncoder().encode('crdt-delta-r2'),
|
||||
});
|
||||
|
||||
let allowFlush = false;
|
||||
const navUrls = [];
|
||||
const ctrl = createGpuRecoveryController({
|
||||
getHref: () => 'https://app.affine.pro/workspace/ws-1/doc-unsaved-r2?code=once&tab=notes',
|
||||
isOAuthCodeConsumed: () => true,
|
||||
pauseInput: () => { window.__AFFINE_WEB_HOST__.ime.readOnly = true; },
|
||||
resumeInput: () => { window.__AFFINE_WEB_HOST__.ime.readOnly = false; },
|
||||
flushPendingWrites: async () => {
|
||||
if (!allowFlush) {
|
||||
throw new Error('simulated-idb-quota-error');
|
||||
}
|
||||
return flusher.flush();
|
||||
},
|
||||
navigate: url => navUrls.push(url),
|
||||
showFatal: (msg, opts) =>
|
||||
showBootFatal(document, msg, {
|
||||
retryable: Boolean(opts?.retryable),
|
||||
onRetry: opts?.retryable ? () => ctrl.retryFallback() : undefined,
|
||||
}),
|
||||
hideFatal: () => hideRuntimeFatal(document),
|
||||
});
|
||||
|
||||
const bootBefore = Boolean(document.getElementById('boot'));
|
||||
const blockedRes = await ctrl.triggerFallback('context-restore-timeout');
|
||||
const bootWhileBlocked = document.getElementById('boot');
|
||||
const msgWhileBlocked = document.getElementById('boot-message')?.textContent || '';
|
||||
const retryBtn = document.getElementById('gpu-fallback-retry');
|
||||
const pendingWhileBlocked = flusher.pendingCount();
|
||||
|
||||
allowFlush = true;
|
||||
retryBtn?.click();
|
||||
for (let i = 0; i < 40 && navUrls.length === 0; i += 1) {
|
||||
await new Promise(r => setTimeout(r, 25));
|
||||
}
|
||||
|
||||
hideRuntimeFatal(document);
|
||||
const bootAfterRetry = Boolean(document.getElementById('boot'));
|
||||
const persisted = await storage.getDocRaw('doc-unsaved-r2');
|
||||
storage.close();
|
||||
await new Promise(resolve => {
|
||||
const req = indexedDB.deleteDatabase(storage.dbName);
|
||||
req.onsuccess = resolve;
|
||||
req.onerror = resolve;
|
||||
});
|
||||
window.__AFFINE_WEB_HOST__.ime.readOnly = false;
|
||||
|
||||
return {
|
||||
bootBefore,
|
||||
blockedRes,
|
||||
hasBootWhileBlocked: Boolean(bootWhileBlocked),
|
||||
msgWhileBlocked,
|
||||
hasRetryBtn: Boolean(retryBtn),
|
||||
pendingWhileBlocked,
|
||||
bootAfterRetry,
|
||||
navUrls,
|
||||
persistedUpdates: persisted?.updates.length ?? 0,
|
||||
};
|
||||
})()`);
|
||||
assert.equal(blockedRetry.bootBefore, false);
|
||||
assert.equal(blockedRetry.blockedRes.navigated, false);
|
||||
assert.equal(blockedRetry.blockedRes.retryable, true);
|
||||
assert.equal(blockedRetry.hasBootWhileBlocked, true);
|
||||
assert.ok(blockedRetry.msgWhileBlocked.includes('Retry'));
|
||||
assert.equal(blockedRetry.hasRetryBtn, true);
|
||||
assert.equal(blockedRetry.pendingWhileBlocked, 1);
|
||||
assert.equal(blockedRetry.bootAfterRetry, false);
|
||||
assert.equal(blockedRetry.persistedUpdates, 1);
|
||||
assert.equal(blockedRetry.navUrls.length, 1);
|
||||
assert.equal(
|
||||
new URL(blockedRetry.navUrls[0]).searchParams.get('shell'),
|
||||
'legacy'
|
||||
);
|
||||
assert.equal(
|
||||
new URL(blockedRetry.navUrls[0]).searchParams.has('code'),
|
||||
false
|
||||
);
|
||||
|
||||
// 3. Inject test document + selection overlay onto production index.html #app-canvas.
|
||||
const selSetup = await evalJs(`(() => {
|
||||
const host = window.__AFFINE_WEB_HOST__;
|
||||
window.__S3_SEL_STATE__ = {
|
||||
docBody: 'The thin web host draws every selection highlight, teardrop handle',
|
||||
clipboardText: '',
|
||||
failNextClipboard: false,
|
||||
actions: [],
|
||||
};
|
||||
const clipboardMock = {
|
||||
async writeText(text) {
|
||||
if (window.__S3_SEL_STATE__.failNextClipboard) {
|
||||
throw new Error('ClipboardDenied');
|
||||
}
|
||||
window.__S3_SEL_STATE__.clipboardText = text;
|
||||
},
|
||||
async readText() {
|
||||
return window.__S3_SEL_STATE__.clipboardText;
|
||||
},
|
||||
};
|
||||
host.selectionOverlay.setScene({
|
||||
theme: 'light',
|
||||
paint(ctx, vw, vh) {
|
||||
ctx.fillStyle = '#ffffff';
|
||||
ctx.fillRect(0, 0, vw, vh);
|
||||
ctx.fillStyle = '#f8fafc';
|
||||
ctx.fillRect(0, 0, vw, 96);
|
||||
ctx.fillStyle = '#e2e8f0';
|
||||
ctx.fillRect(0, 95, vw, 1);
|
||||
ctx.fillStyle = '#0f172a';
|
||||
ctx.font = '600 14px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
ctx.fillText('9:41', 22, 30);
|
||||
ctx.font = '700 17px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
ctx.fillText('AFFiNE Mobile Spec', 22, 74);
|
||||
ctx.fillStyle = '#1e6efb';
|
||||
ctx.font = '600 13px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
ctx.fillText('Canvas Host', 292, 74);
|
||||
ctx.fillStyle = '#0f172a';
|
||||
ctx.font = '700 22px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
ctx.fillText('Pure Canvas Selection', 24, 142);
|
||||
const lines = [
|
||||
'The thin web host draws every selection',
|
||||
'highlight, teardrop handle, and action bar',
|
||||
'directly on #app-canvas with zero floating',
|
||||
'DOM menus or third-party JavaScript.',
|
||||
];
|
||||
ctx.font = '400 16px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
ctx.fillStyle = '#1e293b';
|
||||
[232, 262, 292, 322].forEach((y, i) => ctx.fillText(lines[i], 24, y));
|
||||
ctx.fillStyle = '#64748b';
|
||||
ctx.font = '500 12px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
ctx.fillText('DOM check: 0 floating menu elements mounted', 24, 412);
|
||||
},
|
||||
selection: {
|
||||
viewport: { width: 390, height: 844, safeArea: { top: 44, bottom: 34 } },
|
||||
rects: [
|
||||
{ x: 24, y: 214, width: 312, height: 26 },
|
||||
{ x: 24, y: 244, width: 326, height: 26 },
|
||||
],
|
||||
caretStart: { x: 24, y: 214, height: 26, dir: 'ltr' },
|
||||
caretEnd: { x: 350, y: 244, height: 26, dir: 'ltr' },
|
||||
},
|
||||
callbacks: {
|
||||
getSelectedText: () => 'highlight, teardrop handle',
|
||||
getSelectionToken: () => 'spec-doc:24,214:350,244',
|
||||
deleteSelection: () => {
|
||||
window.__S3_SEL_STATE__.docBody = window.__S3_SEL_STATE__.docBody.replace(
|
||||
' highlight, teardrop handle',
|
||||
''
|
||||
);
|
||||
},
|
||||
insertText: text => {
|
||||
window.__S3_SEL_STATE__.docBody += ' ' + text;
|
||||
},
|
||||
selectAll: () => {},
|
||||
clipboard: clipboardMock,
|
||||
isSecureContext: true,
|
||||
onActionResult: res => window.__S3_SEL_STATE__.actions.push(res),
|
||||
},
|
||||
});
|
||||
const layout = host.selectionOverlay.getLayout();
|
||||
const copyBtn = layout.menu.items.find(i => i.id === 'copy');
|
||||
const cutBtn = layout.menu.items.find(i => i.id === 'cut');
|
||||
const pasteBtn = layout.menu.items.find(i => i.id === 'paste');
|
||||
const bodyChildIds = [...document.body.children]
|
||||
.filter(el => el.tagName !== 'SCRIPT')
|
||||
.map(el => el.tagName.toLowerCase() + '#' + el.id);
|
||||
return {
|
||||
copyPt: { x: copyBtn.x + copyBtn.width / 2, y: copyBtn.y + copyBtn.height / 2 },
|
||||
cutPt: { x: cutBtn.x + cutBtn.width / 2, y: cutBtn.y + cutBtn.height / 2 },
|
||||
pastePt: { x: pasteBtn.x + pasteBtn.width / 2, y: pasteBtn.y + pasteBtn.height / 2 },
|
||||
menuX: layout.menu.x,
|
||||
menuRightMargin: 390 - (layout.menu.x + layout.menu.width),
|
||||
bodyChildIds,
|
||||
embedLayerChildren: document.getElementById('embed-layer').children.length,
|
||||
imeFontSize: getComputedStyle(host.ime).fontSize,
|
||||
};
|
||||
})()`);
|
||||
|
||||
assert.deepEqual(selSetup.bodyChildIds, [
|
||||
'canvas#app-canvas',
|
||||
'textarea#ime',
|
||||
'div#safe-area-probe',
|
||||
'div#embed-layer',
|
||||
'div#a11y-tree',
|
||||
]);
|
||||
assert.equal(selSetup.embedLayerChildren, 0);
|
||||
assert.equal(selSetup.imeFontSize, '16px');
|
||||
assert.ok(selSetup.menuX >= 12);
|
||||
assert.ok(selSetup.menuRightMargin >= 12);
|
||||
|
||||
if (outDir) {
|
||||
const shot1 = await send('Page.captureScreenshot', { format: 'png' });
|
||||
writeFileSync(
|
||||
join(outDir, 'web-selection-menu.png'),
|
||||
Buffer.from(shot1.data, 'base64')
|
||||
);
|
||||
}
|
||||
|
||||
// Real touch gestures via CDP: touchStart on Copy must NOT fire; sliding off cancels.
|
||||
await send('Page.bringToFront');
|
||||
await send('Input.dispatchTouchEvent', {
|
||||
type: 'touchStart',
|
||||
touchPoints: [selSetup.copyPt],
|
||||
});
|
||||
const afterTouchDown = await evalJs('window.__S3_SEL_STATE__.actions.length');
|
||||
assert.equal(
|
||||
afterTouchDown,
|
||||
0,
|
||||
'touch pointerdown must not fire menu action'
|
||||
);
|
||||
|
||||
await send('Input.dispatchTouchEvent', {
|
||||
type: 'touchMove',
|
||||
touchPoints: [{ x: 10, y: 780 }],
|
||||
});
|
||||
await send('Input.dispatchTouchEvent', {
|
||||
type: 'touchEnd',
|
||||
touchPoints: [],
|
||||
});
|
||||
const afterSlideCancel = await evalJs(
|
||||
'window.__S3_SEL_STATE__.actions.length'
|
||||
);
|
||||
assert.equal(afterSlideCancel, 0, 'slide-off touchEnd must cancel action');
|
||||
|
||||
// Real touch tap on Copy fires on pointerup.
|
||||
const touchTap = async pt => {
|
||||
await send('Input.dispatchTouchEvent', {
|
||||
type: 'touchStart',
|
||||
touchPoints: [pt],
|
||||
});
|
||||
await send('Input.dispatchTouchEvent', {
|
||||
type: 'touchEnd',
|
||||
touchPoints: [],
|
||||
});
|
||||
await new Promise(r => setTimeout(r, 80));
|
||||
};
|
||||
await touchTap(selSetup.copyPt);
|
||||
const clipAfterCopy = await evalJs('window.__S3_SEL_STATE__.clipboardText');
|
||||
assert.equal(clipAfterCopy, 'highlight, teardrop handle');
|
||||
|
||||
// Failing Cut (both async clipboard and execCommand fallback rejected) preserves document text.
|
||||
await evalJs(`(() => {
|
||||
window.__S3_SEL_STATE__.failNextClipboard = true;
|
||||
window.__S3_ORIG_EXEC_CMD__ = document.execCommand;
|
||||
document.execCommand = () => false;
|
||||
})()`);
|
||||
await touchTap(selSetup.cutPt);
|
||||
const bodyAfterFailedCut = await evalJs('window.__S3_SEL_STATE__.docBody');
|
||||
assert.ok(bodyAfterFailedCut.includes('highlight, teardrop handle'));
|
||||
|
||||
await evalJs(`(() => {
|
||||
window.__S3_SEL_STATE__.failNextClipboard = false;
|
||||
document.execCommand = window.__S3_ORIG_EXEC_CMD__;
|
||||
})()`);
|
||||
await touchTap(selSetup.cutPt);
|
||||
const bodyAfterOkCut = await evalJs('window.__S3_SEL_STATE__.docBody');
|
||||
assert.equal(bodyAfterOkCut.includes('highlight, teardrop handle'), false);
|
||||
|
||||
await touchTap(selSetup.pastePt);
|
||||
const bodyAfterPaste = await evalJs('window.__S3_SEL_STATE__.docBody');
|
||||
assert.ok(bodyAfterPaste.includes('highlight, teardrop handle'));
|
||||
|
||||
// Still zero pdf-worker.wasm requests before PDF opens!
|
||||
assert.equal(wasmRequestCount, 0);
|
||||
|
||||
// 4. Lazy hayro pdf-worker.wasm multi-page & multi-scale render onto production index.html #app-canvas.
|
||||
const pdfResult = await evalJs(`(async () => {
|
||||
const host = window.__AFFINE_WEB_HOST__;
|
||||
const spawnedBefore = host.workerLoader.hasLoadedWorker('pdf');
|
||||
|
||||
function buildMultiPagePdf() {
|
||||
const s1 = [
|
||||
'0.98 0.99 1.00 rg 0 0 360 480 re f',
|
||||
'0.12 0.35 0.85 rg 0 416 360 64 re f',
|
||||
'BT /F1 18 Tf 1 1 1 rg 24 442 Td (AFFiNE Mobile Architecture) Tj ET',
|
||||
'BT /F1 11 Tf 0.85 0.92 1.00 rg 24 424 Td (Pure Safe Rust hayro PDF Worker - Page 1 of 2) Tj ET',
|
||||
'0.92 0.95 1.00 rg 24 270 312 120 re f',
|
||||
'0.12 0.35 0.85 RG 1.2 w 24 270 312 120 re S',
|
||||
'BT /F1 13 Tf 0.10 0.14 0.22 rg 38 366 Td (Quarterly Frame Time Budget) Tj ET',
|
||||
'0.15 0.50 0.95 rg 46 284 42 52 re f',
|
||||
'0.18 0.68 0.56 rg 108 284 42 64 re f',
|
||||
'0.94 0.58 0.16 rg 170 284 42 44 re f',
|
||||
'0.44 0.36 0.90 rg 232 284 42 58 re f',
|
||||
'BT /F1 11 Tf 0.18 0.22 0.30 rg 24 236 Td (1. Zero third-party runtime JavaScript in Web host.) Tj ET',
|
||||
'BT /F1 11 Tf 0.18 0.22 0.30 rg 24 214 Td (2. Lazy pdf-worker.wasm spawns only on PDF open.) Tj ET',
|
||||
'BT /F1 11 Tf 0.18 0.22 0.30 rg 24 192 Td (3. Transferable RGBA frames with LRU byte cap.) Tj ET',
|
||||
'0.86 0.89 0.94 RG 0.8 w 24 156 m 336 156 l S',
|
||||
'BT /F1 10 Tf 0.38 0.44 0.54 rg 24 132 Td (Rendered off the main thread by hayro in WebAssembly.) Tj ET',
|
||||
'0.12 0.35 0.85 rg 24 72 96 28 re f',
|
||||
'BT /F1 10 Tf 1 1 1 rg 40 82 Td (VERIFIED) Tj ET',
|
||||
].join('\\n') + '\\n';
|
||||
const s2 = [
|
||||
'0.99 0.99 1.00 rg 0 0 360 480 re f',
|
||||
'0.15 0.55 0.45 rg 0 416 360 64 re f',
|
||||
'BT /F1 18 Tf 1 1 1 rg 24 442 Td (Appendix - Page 2 of 2) Tj ET',
|
||||
'0.15 0.55 0.45 rg 40 240 280 120 re f',
|
||||
].join('\\n') + '\\n';
|
||||
const objects = [
|
||||
'1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\\n',
|
||||
'2 0 obj << /Type /Pages /Kids [3 0 R 5 0 R] /Count 2 >> endobj\\n',
|
||||
'3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 360 480] /Resources << /Font << /F1 7 0 R >> >> /Contents 4 0 R >> endobj\\n',
|
||||
'4 0 obj << /Length ' + s1.length + ' >> stream\\n' + s1 + 'endstream endobj\\n',
|
||||
'5 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 360 480] /Resources << /Font << /F1 7 0 R >> >> /Contents 6 0 R >> endobj\\n',
|
||||
'6 0 obj << /Length ' + s2.length + ' >> stream\\n' + s2 + 'endstream endobj\\n',
|
||||
'7 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj\\n',
|
||||
];
|
||||
let out = '%PDF-1.4\\n';
|
||||
const offsets = [0];
|
||||
for (const obj of objects) {
|
||||
offsets.push(out.length);
|
||||
out += obj;
|
||||
}
|
||||
const xrefPos = out.length;
|
||||
out += 'xref\\n0 ' + (objects.length + 1) + '\\n0000000000 65535 f \\n';
|
||||
for (let i = 1; i < offsets.length; i += 1) {
|
||||
out += String(offsets[i]).padStart(10, '0') + ' 00000 n \\n';
|
||||
}
|
||||
out += 'trailer << /Size ' + (objects.length + 1) + ' /Root 1 0 R >>\\nstartxref\\n' + xrefPos + '\\n%%EOF\\n';
|
||||
return new TextEncoder().encode(out);
|
||||
}
|
||||
|
||||
const pdfBytes = buildMultiPagePdf();
|
||||
const pageCount = await host.pdfClient.getPageCount({ docKey: 'r2-pdf', pdfBytes });
|
||||
const [pHalf, p1a, p1b, p2x] = await Promise.all([
|
||||
host.pdfClient.renderPage({ docKey: 'r2-pdf', pdfBytes, pageIndex: 0, scale: 0.5 }),
|
||||
host.pdfClient.renderPage({ docKey: 'r2-pdf', pdfBytes, pageIndex: 0, scale: 1 }),
|
||||
host.pdfClient.renderPage({ docKey: 'r2-pdf', pdfBytes, pageIndex: 0, scale: 1 }),
|
||||
host.pdfClient.renderPage({ docKey: 'r2-pdf', pdfBytes, pageIndex: 0, scale: 2 }),
|
||||
]);
|
||||
|
||||
// Transfer p1a buffer and confirm next cache hit still returns full RGBA bytes.
|
||||
structuredClone(p1a.rgba.buffer, { transfer: [p1a.rgba.buffer] });
|
||||
const p1AfterTransfer = await host.pdfClient.renderPage({
|
||||
docKey: 'r2-pdf',
|
||||
pdfBytes,
|
||||
pageIndex: 0,
|
||||
scale: 1,
|
||||
});
|
||||
|
||||
// Composite the 2x hayro PDF bitmap onto production index.html #app-canvas.
|
||||
const off = document.createElement('canvas');
|
||||
off.width = p2x.widthPx;
|
||||
off.height = p2x.heightPx;
|
||||
off.getContext('2d').putImageData(
|
||||
new ImageData(new Uint8ClampedArray(p2x.rgba), p2x.widthPx, p2x.heightPx),
|
||||
0,
|
||||
0
|
||||
);
|
||||
|
||||
host.selectionOverlay.setScene({
|
||||
theme: 'light',
|
||||
selection: null,
|
||||
paint(ctx, vw, vh) {
|
||||
ctx.fillStyle = '#f1f5f9';
|
||||
ctx.fillRect(0, 0, vw, vh);
|
||||
ctx.fillStyle = '#ffffff';
|
||||
ctx.fillRect(0, 0, vw, 92);
|
||||
ctx.fillStyle = '#e2e8f0';
|
||||
ctx.fillRect(0, 91, vw, 1);
|
||||
ctx.fillStyle = '#0f172a';
|
||||
ctx.font = '600 14px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
ctx.fillText('9:41', 22, 30);
|
||||
ctx.font = '700 17px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
ctx.fillText('Quarterly Report.pdf', 22, 72);
|
||||
ctx.fillStyle = '#1e6efb';
|
||||
ctx.font = '600 12px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
ctx.fillText('hayro Wasm', 298, 72);
|
||||
|
||||
const cardX = 16;
|
||||
const cardY = 112;
|
||||
const cardW = vw - 32;
|
||||
const cardH = 540;
|
||||
ctx.save();
|
||||
ctx.shadowColor = 'rgba(15, 23, 42, 0.12)';
|
||||
ctx.shadowBlur = 18;
|
||||
ctx.shadowOffsetY = 6;
|
||||
ctx.fillStyle = '#ffffff';
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(cardX, cardY, cardW, cardH, 14);
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
|
||||
const pad = 12;
|
||||
const drawW = cardW - pad * 2;
|
||||
const drawH = Math.min(cardH - 64, (drawW * p2x.heightPx) / p2x.widthPx);
|
||||
ctx.drawImage(off, cardX + pad, cardY + pad, drawW, drawH);
|
||||
|
||||
const footerY = cardY + cardH - 42;
|
||||
ctx.fillStyle = '#e2e8f0';
|
||||
ctx.fillRect(cardX + 12, footerY - 10, cardW - 24, 1);
|
||||
ctx.fillStyle = '#0f172a';
|
||||
ctx.font = '600 13px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
ctx.fillText('Page 1 / ' + pageCount, cardX + 20, footerY + 14);
|
||||
ctx.fillStyle = '#475569';
|
||||
ctx.font = '500 12px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
ctx.fillText(p2x.widthPx + 'x' + p2x.heightPx + ' RGBA • Cached', cardX + 190, footerY + 14);
|
||||
|
||||
ctx.fillStyle = '#1e293b';
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(24, 680, vw - 48, 44, 10);
|
||||
ctx.fill();
|
||||
ctx.fillStyle = '#f8fafc';
|
||||
ctx.font = '500 12px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText('Lazy hayro pdf-worker.wasm · 0 PDFium · 0 DOM overlays', vw / 2, 706);
|
||||
ctx.textAlign = 'left';
|
||||
},
|
||||
});
|
||||
|
||||
const stats = host.pdfClient.getStats();
|
||||
return {
|
||||
spawnedBefore,
|
||||
pageCount,
|
||||
half: { w: pHalf.widthPx, h: pHalf.heightPx },
|
||||
one: { w: p1b.widthPx, h: p1b.heightPx },
|
||||
two: { w: p2x.widthPx, h: p2x.heightPx },
|
||||
afterTransferBytes: p1AfterTransfer.rgba.byteLength,
|
||||
afterTransferFromCache: p1AfterTransfer.fromCache,
|
||||
stats,
|
||||
};
|
||||
})()`);
|
||||
|
||||
assert.equal(pdfResult.spawnedBefore, false);
|
||||
assert.equal(wasmRequestCount, 1);
|
||||
assert.equal(pdfResult.pageCount, 2);
|
||||
assert.equal(pdfResult.one.w, pdfResult.half.w * 2);
|
||||
assert.equal(pdfResult.two.w, pdfResult.one.w * 2);
|
||||
assert.equal(pdfResult.one.h, pdfResult.half.h * 2);
|
||||
assert.equal(pdfResult.two.h, pdfResult.one.h * 2);
|
||||
assert.equal(pdfResult.afterTransferFromCache, true);
|
||||
assert.equal(
|
||||
pdfResult.afterTransferBytes,
|
||||
pdfResult.one.w * pdfResult.one.h * 4
|
||||
);
|
||||
|
||||
if (outDir) {
|
||||
const shot2 = await send('Page.captureScreenshot', { format: 'png' });
|
||||
writeFileSync(
|
||||
join(outDir, 'web-pdf-worker-preview.png'),
|
||||
Buffer.from(shot2.data, 'base64')
|
||||
);
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Real-browser S3-Web E2E passed on production index.html (${chromeBin}):`,
|
||||
JSON.stringify({
|
||||
webglRecovered: webglRecovery.afterRestore.status === 'ready',
|
||||
postBootRetryPassed:
|
||||
blockedRetry.hasBootWhileBlocked &&
|
||||
blockedRetry.hasRetryBtn &&
|
||||
blockedRetry.persistedUpdates === 1,
|
||||
touchPointerUpClipboardPassed: true,
|
||||
pdfScales: {
|
||||
half: `${pdfResult.half.w}x${pdfResult.half.h}`,
|
||||
one: `${pdfResult.one.w}x${pdfResult.one.h}`,
|
||||
two: `${pdfResult.two.w}x${pdfResult.two.h}`,
|
||||
},
|
||||
pdfWasmRequests: wasmRequestCount,
|
||||
screenshotsDir: outDir,
|
||||
})
|
||||
);
|
||||
} finally {
|
||||
try {
|
||||
ws?.close();
|
||||
} catch {}
|
||||
try {
|
||||
if (chromeProc.pid) {
|
||||
process.kill(chromeProc.pid, 'SIGTERM');
|
||||
}
|
||||
} catch {}
|
||||
await new Promise(r => setTimeout(r, 200));
|
||||
try {
|
||||
if (chromeProc.pid) {
|
||||
process.kill(chromeProc.pid, 'SIGKILL');
|
||||
}
|
||||
} catch {}
|
||||
server.close();
|
||||
rmSync(profileDir, { recursive: true, force: true });
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
#!/usr/bin/env node
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* Zero-dependency static gate for `packages/frontend/hosts/web/`.
|
||||
* Verifies zero third-party runtime JS imports, zero package manifests under
|
||||
* `packages/frontend/hosts/`, strict `index.html` CSP and DOM allowlist, and
|
||||
* strict iframe sandbox rules.
|
||||
*/
|
||||
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import { join, relative, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const DEFAULT_WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
|
||||
const DEFAULT_HOSTS_ROOT = resolve(DEFAULT_WEB_ROOT, '..');
|
||||
const TURNSTILE_ALLOWLIST_URL =
|
||||
'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
|
||||
|
||||
/**
|
||||
* Recursively walks a directory tree and returns all file paths and matching
|
||||
* forbidden directory paths (`node_modules`).
|
||||
*
|
||||
* @param {string} rootDir
|
||||
* @returns {{ files: string[], nodeModulesDirs: string[] }}
|
||||
*/
|
||||
function walkTree(rootDir) {
|
||||
/** @type {string[]} */
|
||||
const files = [];
|
||||
/** @type {string[]} */
|
||||
const nodeModulesDirs = [];
|
||||
if (!existsSync(rootDir)) {
|
||||
return { files, nodeModulesDirs };
|
||||
}
|
||||
/** @param {string} dir */
|
||||
function visit(dir) {
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
if (entry.name === 'node_modules') {
|
||||
nodeModulesDirs.push(full);
|
||||
continue;
|
||||
}
|
||||
visit(full);
|
||||
} else if (entry.isFile()) {
|
||||
files.push(full);
|
||||
}
|
||||
}
|
||||
}
|
||||
visit(rootDir);
|
||||
return { files, nodeModulesDirs };
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips block and line comments from JS source for static URL/import scanning.
|
||||
* Preserves URLs inside string literals by only removing full-line comments
|
||||
* and block comments.
|
||||
*
|
||||
* @param {string} source
|
||||
* @returns {string}
|
||||
*/
|
||||
function stripComments(source) {
|
||||
return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies zero third-party runtime JS and static allowlist invariants across
|
||||
* `packages/frontend/hosts/web/` and an optional staged output directory.
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @param {string} [options.webRoot]
|
||||
* @param {string} [options.hostsRoot]
|
||||
* @param {string | null} [options.stageDir]
|
||||
* @returns {{ ok: boolean, violations: string[], checkedFiles: number }}
|
||||
*/
|
||||
export function verifyZeroThirdPartyJs(options = {}) {
|
||||
const webRoot = resolve(options.webRoot || DEFAULT_WEB_ROOT);
|
||||
const hostsRoot = resolve(options.hostsRoot || DEFAULT_HOSTS_ROOT);
|
||||
const stageDir = options.stageDir ? resolve(options.stageDir) : null;
|
||||
|
||||
/** @type {string[]} */
|
||||
const violations = [];
|
||||
let checkedFiles = 0;
|
||||
|
||||
// 1. Zero package.json, yarn.lock, or node_modules under hosts/ and stageDir.
|
||||
const scanRoots = [hostsRoot];
|
||||
if (stageDir && existsSync(stageDir)) {
|
||||
scanRoots.push(stageDir);
|
||||
}
|
||||
for (const root of scanRoots) {
|
||||
const { files, nodeModulesDirs } = walkTree(root);
|
||||
for (const dir of nodeModulesDirs) {
|
||||
violations.push(`Forbidden node_modules directory: ${dir}`);
|
||||
}
|
||||
for (const file of files) {
|
||||
if (file.endsWith('/package.json') || file.endsWith('/yarn.lock')) {
|
||||
violations.push(`Forbidden package manifest: ${file}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Scan src/**/*.js (and any staged .js files) for bare imports and external script injection.
|
||||
const srcDir = join(webRoot, 'src');
|
||||
const jsFiles = walkTree(srcDir).files.filter(f => f.endsWith('.js'));
|
||||
if (stageDir && existsSync(stageDir)) {
|
||||
for (const file of walkTree(stageDir).files) {
|
||||
if (file.endsWith('.js') || file.endsWith('.mjs')) {
|
||||
jsFiles.push(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const staticImportRe =
|
||||
/(?:^|[;\n])\s*(?:import|export)\s+(?:[^'";]*?\s+from\s+)?['"]([^'"]+)['"]/g;
|
||||
const dynamicImportRe = /\bimport\(\s*['"]([^'"]+)['"]\s*\)/g;
|
||||
const createScriptRe = /createElement\(\s*['"]script['"]\s*\)/g;
|
||||
const externalUrlRe = /https?:\/\/[^\s'"`<>)]+/g;
|
||||
|
||||
for (const file of jsFiles) {
|
||||
checkedFiles += 1;
|
||||
const raw = readFileSync(file, 'utf8');
|
||||
const code = stripComments(raw);
|
||||
const rel = relative(webRoot, file);
|
||||
const isSignIn = rel === 'src/sign-in.js';
|
||||
|
||||
for (const match of code.matchAll(staticImportRe)) {
|
||||
const specifier = match[1];
|
||||
if (!specifier.startsWith('./') && !specifier.startsWith('../')) {
|
||||
violations.push(
|
||||
`${rel}: bare or external static import "${specifier}" is forbidden`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for (const match of code.matchAll(dynamicImportRe)) {
|
||||
const specifier = match[1];
|
||||
if (!specifier.startsWith('./') && !specifier.startsWith('../')) {
|
||||
violations.push(
|
||||
`${rel}: bare or external dynamic import "${specifier}" is forbidden`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const createsScript = createScriptRe.test(code);
|
||||
createScriptRe.lastIndex = 0;
|
||||
if (createsScript && !isSignIn) {
|
||||
violations.push(
|
||||
`${rel}: dynamic <script> creation is only allowed in src/sign-in.js`
|
||||
);
|
||||
}
|
||||
|
||||
if (isSignIn) {
|
||||
const urls = [...code.matchAll(externalUrlRe)].map(m => m[0]);
|
||||
for (const url of urls) {
|
||||
if (
|
||||
url !== TURNSTILE_ALLOWLIST_URL &&
|
||||
!url.startsWith('https://app.affine.pro')
|
||||
) {
|
||||
violations.push(
|
||||
`${rel}: unexpected external URL "${url}" outside Turnstile allowlist`
|
||||
);
|
||||
}
|
||||
}
|
||||
if (
|
||||
!code.includes("'/api/auth/captcha'") &&
|
||||
!code.includes('"/api/auth/captcha"')
|
||||
) {
|
||||
violations.push(
|
||||
`${rel}: Turnstile must be gated behind /api/auth/captcha`
|
||||
);
|
||||
}
|
||||
} else if (/\bsrc\s*=\s*['"]https?:\/\//.test(code)) {
|
||||
violations.push(
|
||||
`${rel}: external http(s) script/resource assignment is forbidden`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Scan HTML files for external <script src="http..."> tags.
|
||||
const htmlRoots = [webRoot];
|
||||
if (stageDir && existsSync(stageDir)) {
|
||||
htmlRoots.push(stageDir);
|
||||
}
|
||||
const externalScriptTagRe =
|
||||
/<script\b[^>]*\bsrc\s*=\s*['"]https?:\/\/[^'"]+['"][^>]*>/gi;
|
||||
for (const root of htmlRoots) {
|
||||
for (const entry of readdirSync(root, { withFileTypes: true })) {
|
||||
if (!entry.isFile() || !entry.name.endsWith('.html')) {
|
||||
continue;
|
||||
}
|
||||
const full = join(root, entry.name);
|
||||
checkedFiles += 1;
|
||||
const html = readFileSync(full, 'utf8');
|
||||
for (const match of html.matchAll(externalScriptTagRe)) {
|
||||
violations.push(
|
||||
`${entry.name}: static external script tag is forbidden (${match[0]})`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Verify index.html CSP script-src and permanent visual DOM allowlist.
|
||||
const indexHtmlPath = join(webRoot, 'index.html');
|
||||
if (!existsSync(indexHtmlPath)) {
|
||||
violations.push('Missing index.html');
|
||||
} else {
|
||||
const indexHtml = readFileSync(indexHtmlPath, 'utf8');
|
||||
const cspMatch = indexHtml.match(
|
||||
/http-equiv="Content-Security-Policy"\s+content="([^"]+)"/i
|
||||
);
|
||||
if (!cspMatch) {
|
||||
violations.push('index.html: missing Content-Security-Policy meta tag');
|
||||
} else {
|
||||
const csp = cspMatch[1];
|
||||
const scriptSrcMatch = csp.match(/script-src\s+([^;]+)/i);
|
||||
if (!scriptSrcMatch) {
|
||||
violations.push('index.html: CSP missing script-src directive');
|
||||
} else {
|
||||
const tokens = scriptSrcMatch[1].trim().split(/\s+/);
|
||||
const allowedScriptTokens = new Set(["'self'", "'wasm-unsafe-eval'"]);
|
||||
for (const token of tokens) {
|
||||
if (!allowedScriptTokens.has(token)) {
|
||||
violations.push(
|
||||
`index.html: forbidden CSP script-src token "${token}"`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const bodyMatch = indexHtml.match(/<body>([\s\S]*?)<\/body>/i);
|
||||
if (!bodyMatch) {
|
||||
violations.push('index.html: missing <body>');
|
||||
} else {
|
||||
const body = bodyMatch[1];
|
||||
const tagIds = [
|
||||
...body.matchAll(/<([a-z0-9-]+)\b[^>]*\bid="([^"]+)"/gi),
|
||||
].map(m => `${m[1].toLowerCase()}#${m[2]}`);
|
||||
const allowedBodyIds = new Set([
|
||||
'canvas#app-canvas',
|
||||
'textarea#ime',
|
||||
'div#safe-area-probe',
|
||||
'div#embed-layer',
|
||||
'div#a11y-tree',
|
||||
'div#boot',
|
||||
'p#boot-message',
|
||||
'script#affine-build-manifest',
|
||||
]);
|
||||
for (const tagId of tagIds) {
|
||||
if (!allowedBodyIds.has(tagId)) {
|
||||
violations.push(
|
||||
`index.html: unexpected DOM element "${tagId}" outside allowlist`
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!tagIds.includes('canvas#app-canvas')) {
|
||||
violations.push('index.html: missing <canvas id="app-canvas">');
|
||||
}
|
||||
if (!tagIds.includes('textarea#ime')) {
|
||||
violations.push('index.html: missing <textarea id="ime">');
|
||||
}
|
||||
if (!body.includes('<div id="embed-layer"></div>')) {
|
||||
violations.push('index.html: #embed-layer must be empty at rest');
|
||||
}
|
||||
const probeMatches = body.match(/id="safe-area-probe"/g) || [];
|
||||
if (probeMatches.length > 1) {
|
||||
violations.push(
|
||||
'index.html: must contain at most one #safe-area-probe element'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Verify host.js iframe sandbox allowlist strips allow-same-origin.
|
||||
const hostJsPath = join(webRoot, 'src/host.js');
|
||||
if (existsSync(hostJsPath)) {
|
||||
const hostCode = stripComments(readFileSync(hostJsPath, 'utf8'));
|
||||
const sandboxSetMatch = hostCode.match(
|
||||
/ALLOWED_SANDBOX_TOKENS\s*=\s*new Set\(\[([\s\S]*?)\]\)/
|
||||
);
|
||||
if (!sandboxSetMatch) {
|
||||
violations.push('src/host.js: missing ALLOWED_SANDBOX_TOKENS allowlist');
|
||||
} else if (sandboxSetMatch[1].includes('allow-same-origin')) {
|
||||
violations.push(
|
||||
'src/host.js: ALLOWED_SANDBOX_TOKENS must never include allow-same-origin'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ok: violations.length === 0,
|
||||
violations,
|
||||
checkedFiles,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
process.argv[1] &&
|
||||
resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
||||
) {
|
||||
const stageDir = process.argv[2] ? resolve(process.argv[2]) : null;
|
||||
const report = verifyZeroThirdPartyJs({ stageDir });
|
||||
if (!report.ok) {
|
||||
console.error(
|
||||
`Zero-third-party-JS gate failed (${report.violations.length} violations):`
|
||||
);
|
||||
for (const v of report.violations) {
|
||||
console.error(` - ${v}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(
|
||||
`Zero-third-party-JS gate passed (${report.checkedFiles} files verified, 0 violations)`
|
||||
);
|
||||
}
|
||||
@@ -1,18 +1,288 @@
|
||||
// @ts-check
|
||||
|
||||
import {
|
||||
createSelectionOverlayController,
|
||||
drawSelectionOverlay,
|
||||
} from './selection-overlay.js';
|
||||
|
||||
/**
|
||||
* Default S1 thin-host entry module referenced by `index.html` `#affine-build-manifest`.
|
||||
* Presents a real first-frame clear on `#app-canvas` (preferring WebGPU, then
|
||||
* WebGL2, then 2D) before calling `host.markFirstFrameReady()` to remove `#boot`.
|
||||
* S2 replaces `appEntryJs` with the bundled Wasm UI runtime.
|
||||
* Default thin-host entry module referenced by `index.html`.
|
||||
* Presents a first-frame clear on `#app-canvas` (WebGPU, then WebGL2, then 2D)
|
||||
* before calling `host.markFirstFrameReady()` to remove `#boot`.
|
||||
* Wires `webglcontextrestored`, WebGPU-to-WebGL2 replacement-canvas downgrade,
|
||||
* and canvas-drawn selection overlay pointer/clipboard handling directly on
|
||||
* `#app-canvas`.
|
||||
*/
|
||||
|
||||
const VERT_SRC = `#version 300 es
|
||||
in vec2 a_pos;
|
||||
out vec2 v_uv;
|
||||
void main() {
|
||||
v_uv = vec2(a_pos.x * 0.5 + 0.5, 0.5 - a_pos.y * 0.5);
|
||||
gl_Position = vec4(a_pos, 0.0, 1.0);
|
||||
}`;
|
||||
|
||||
const FRAG_SRC = `#version 300 es
|
||||
precision mediump float;
|
||||
in vec2 v_uv;
|
||||
uniform sampler2D u_tex;
|
||||
out vec4 outColor;
|
||||
void main() {
|
||||
outColor = texture(u_tex, v_uv);
|
||||
}`;
|
||||
|
||||
/**
|
||||
* Uploads a 2D offscreen canvas onto a WebGL2 `#app-canvas` via a full-screen
|
||||
* textured quad. Falls back to `gl.clear(...)` when minimal mock contexts omit
|
||||
* shader methods.
|
||||
*
|
||||
* @param {WebGL2RenderingContext} gl
|
||||
* @param {HTMLCanvasElement | OffscreenCanvas | null} sourceCanvas
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function presentWebGl2Frame(gl, sourceCanvas) {
|
||||
if (!sourceCanvas) {
|
||||
gl.clearColor?.(0.078, 0.078, 0.078, 1);
|
||||
gl.clear?.(gl.COLOR_BUFFER_BIT ?? 0x4000);
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
typeof gl.createShader !== 'function' ||
|
||||
typeof gl.createProgram !== 'function' ||
|
||||
typeof gl.createTexture !== 'function' ||
|
||||
typeof gl.texImage2D !== 'function' ||
|
||||
typeof gl.drawArrays !== 'function'
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @type {any} */
|
||||
const cache = gl;
|
||||
let state = cache.__affineQuadState;
|
||||
if (!state || gl.isContextLost?.()) {
|
||||
const vs = gl.createShader(gl.VERTEX_SHADER);
|
||||
const fs = gl.createShader(gl.FRAGMENT_SHADER);
|
||||
const prog = gl.createProgram();
|
||||
const buf = gl.createBuffer();
|
||||
const tex = gl.createTexture();
|
||||
if (!vs || !fs || !prog || !buf || !tex) {
|
||||
return false;
|
||||
}
|
||||
gl.shaderSource(vs, VERT_SRC);
|
||||
gl.compileShader(vs);
|
||||
gl.shaderSource(fs, FRAG_SRC);
|
||||
gl.compileShader(fs);
|
||||
gl.attachShader(prog, vs);
|
||||
gl.attachShader(prog, fs);
|
||||
gl.linkProgram(prog);
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
|
||||
gl.bufferData(
|
||||
gl.ARRAY_BUFFER,
|
||||
new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]),
|
||||
gl.STATIC_DRAW
|
||||
);
|
||||
state = {
|
||||
prog,
|
||||
buf,
|
||||
tex,
|
||||
posLoc: gl.getAttribLocation(prog, 'a_pos'),
|
||||
};
|
||||
cache.__affineQuadState = state;
|
||||
}
|
||||
|
||||
gl.viewport?.(0, 0, gl.drawingBufferWidth || 1, gl.drawingBufferHeight || 1);
|
||||
gl.useProgram(state.prog);
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, state.buf);
|
||||
gl.enableVertexAttribArray(state.posLoc);
|
||||
gl.vertexAttribPointer(state.posLoc, 2, gl.FLOAT, false, 0, 0);
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
gl.bindTexture(gl.TEXTURE_2D, state.tex);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||||
gl.texImage2D(
|
||||
gl.TEXTURE_2D,
|
||||
0,
|
||||
gl.RGBA,
|
||||
gl.RGBA,
|
||||
gl.UNSIGNED_BYTE,
|
||||
/** @type {TexImageSource} */ (sourceCanvas)
|
||||
);
|
||||
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears or composites `#app-canvas` with WebGL2 or 2D fallback.
|
||||
*
|
||||
* @param {HTMLCanvasElement} canvas
|
||||
* @param {HTMLCanvasElement | OffscreenCanvas | null} [sourceCanvas]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function paintWebGl2Or2d(canvas, sourceCanvas = null) {
|
||||
if (typeof canvas.getContext !== 'function') {
|
||||
return false;
|
||||
}
|
||||
const gl = /** @type {WebGL2RenderingContext | null} */ (
|
||||
canvas.getContext('webgl2')
|
||||
);
|
||||
if (gl) {
|
||||
return presentWebGl2Frame(gl, sourceCanvas);
|
||||
}
|
||||
|
||||
const ctx2d = canvas.getContext('2d');
|
||||
if (ctx2d) {
|
||||
if (sourceCanvas) {
|
||||
if (typeof ctx2d.drawImage !== 'function') {
|
||||
return false;
|
||||
}
|
||||
ctx2d.clearRect?.(0, 0, canvas.width || 1, canvas.height || 1);
|
||||
ctx2d.drawImage(
|
||||
/** @type {CanvasImageSource} */ (sourceCanvas),
|
||||
0,
|
||||
0,
|
||||
canvas.width || 1,
|
||||
canvas.height || 1
|
||||
);
|
||||
return true;
|
||||
}
|
||||
ctx2d.fillStyle = '#141414';
|
||||
ctx2d.fillRect(0, 0, canvas.width || 1, canvas.height || 1);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces a WebGPU-locked `<canvas id="app-canvas">` with a fresh DOM canvas
|
||||
* so WebGL2 context creation succeeds after WebGPU `device.lost`.
|
||||
*
|
||||
* @param {HTMLCanvasElement} oldCanvas
|
||||
* @param {any} host
|
||||
* @returns {HTMLCanvasElement}
|
||||
*/
|
||||
function replaceCanvasForWebGl2Fallback(oldCanvas, host) {
|
||||
const doc = globalThis.document;
|
||||
if (!doc || typeof doc.createElement !== 'function') {
|
||||
return oldCanvas;
|
||||
}
|
||||
const fresh = doc.createElement('canvas');
|
||||
fresh.id = oldCanvas.id || 'app-canvas';
|
||||
fresh.setAttribute?.('aria-hidden', 'true');
|
||||
const dpr = Math.max(1, globalThis.window?.devicePixelRatio || 1);
|
||||
const hasExplicitSize =
|
||||
oldCanvas.width > 0 &&
|
||||
oldCanvas.height > 0 &&
|
||||
!(oldCanvas.width === 300 && oldCanvas.height === 150);
|
||||
if (hasExplicitSize) {
|
||||
fresh.width = oldCanvas.width;
|
||||
fresh.height = oldCanvas.height;
|
||||
} else if (globalThis.window?.innerWidth && globalThis.window?.innerHeight) {
|
||||
fresh.width = Math.max(1, Math.round(globalThis.window.innerWidth * dpr));
|
||||
fresh.height = Math.max(1, Math.round(globalThis.window.innerHeight * dpr));
|
||||
} else {
|
||||
fresh.width = oldCanvas.width || 300;
|
||||
fresh.height = oldCanvas.height || 150;
|
||||
}
|
||||
if (typeof oldCanvas.replaceWith === 'function') {
|
||||
oldCanvas.replaceWith(fresh);
|
||||
}
|
||||
host.bindCanvas?.(fresh);
|
||||
return fresh;
|
||||
}
|
||||
|
||||
/**
|
||||
* Presents a 2D surface or clear frame on a configured WebGPU canvas.
|
||||
*
|
||||
* @param {{ device: any, context: any, canvas: HTMLCanvasElement }} webGpuState
|
||||
* @param {HTMLCanvasElement | OffscreenCanvas | null} sourceCanvas
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function presentWebGpuFrame(webGpuState, sourceCanvas) {
|
||||
const { device, context } = webGpuState;
|
||||
const texture = context.getCurrentTexture?.();
|
||||
if (!texture) {
|
||||
return false;
|
||||
}
|
||||
if (sourceCanvas) {
|
||||
if (
|
||||
typeof device.queue?.copyExternalImageToTexture !== 'function' ||
|
||||
typeof device.createCommandEncoder !== 'function' ||
|
||||
typeof device.queue?.submit !== 'function'
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
device.queue.copyExternalImageToTexture(
|
||||
{ source: sourceCanvas },
|
||||
{ texture },
|
||||
{
|
||||
width: sourceCanvas.width || webGpuState.canvas.width || 1,
|
||||
height: sourceCanvas.height || webGpuState.canvas.height || 1,
|
||||
}
|
||||
);
|
||||
const encoder = device.createCommandEncoder();
|
||||
if (!encoder) {
|
||||
return false;
|
||||
}
|
||||
device.queue.submit([encoder.finish()]);
|
||||
return true;
|
||||
}
|
||||
const encoder = device.createCommandEncoder?.();
|
||||
if (encoder && typeof device.queue?.submit === 'function') {
|
||||
const pass = encoder.beginRenderPass({
|
||||
colorAttachments: [
|
||||
{
|
||||
view: texture.createView(),
|
||||
loadOp: 'clear',
|
||||
storeOp: 'store',
|
||||
clearValue: { r: 0.078, g: 0.078, b: 0.078, a: 1 },
|
||||
},
|
||||
],
|
||||
});
|
||||
pass.end();
|
||||
device.queue.submit([encoder.finish()]);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an offscreen 2D staging canvas never mounted in the DOM.
|
||||
*
|
||||
* @param {number} width
|
||||
* @param {number} height
|
||||
* @returns {HTMLCanvasElement | OffscreenCanvas | null}
|
||||
*/
|
||||
function createOffscreenSurface(width, height) {
|
||||
if (typeof OffscreenCanvas === 'function') {
|
||||
return new OffscreenCanvas(width, height);
|
||||
}
|
||||
const doc = globalThis.document;
|
||||
if (doc && typeof doc.createElement === 'function') {
|
||||
const c = doc.createElement('canvas');
|
||||
c.width = width;
|
||||
c.height = height;
|
||||
return c;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {HTMLCanvasElement} canvas
|
||||
* @param {{ bindWebGpuDevice?: (device: unknown) => void }} host
|
||||
* @param {any} host
|
||||
* @param {() => HTMLCanvasElement | OffscreenCanvas | null} getSourceCanvas
|
||||
* @param {(nextCanvas: HTMLCanvasElement) => void} onCanvasReplaced
|
||||
* @param {(state: { device: any, context: any, canvas: HTMLCanvasElement } | null) => void} setWebGpuState
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async function presentFirstFrameClear(canvas, host) {
|
||||
async function presentFirstFrameClear(
|
||||
canvas,
|
||||
host,
|
||||
getSourceCanvas,
|
||||
onCanvasReplaced,
|
||||
setWebGpuState
|
||||
) {
|
||||
const gpu =
|
||||
/** @type {{ requestAdapter?: () => Promise<any>, getPreferredCanvasFormat?: () => string } | undefined} */ (
|
||||
globalThis.navigator?.gpu
|
||||
@@ -23,67 +293,337 @@ async function presentFirstFrameClear(canvas, host) {
|
||||
const device = adapter ? await adapter.requestDevice() : null;
|
||||
const context = device ? canvas.getContext('webgpu') : null;
|
||||
if (device && context && typeof context.configure === 'function') {
|
||||
host.bindWebGpuDevice?.(device);
|
||||
host.bindWebGpuDevice?.(device, {
|
||||
tryWebGl2Fallback: () => {
|
||||
setWebGpuState(null);
|
||||
const nextCanvas = replaceCanvasForWebGl2Fallback(
|
||||
host.canvas || canvas,
|
||||
host
|
||||
);
|
||||
onCanvasReplaced(nextCanvas);
|
||||
return paintWebGl2Or2d(nextCanvas, getSourceCanvas());
|
||||
},
|
||||
});
|
||||
const renderAttachment =
|
||||
globalThis.GPUTextureUsage?.RENDER_ATTACHMENT ?? 0x10;
|
||||
const copyDst = globalThis.GPUTextureUsage?.COPY_DST ?? 0x02;
|
||||
context.configure({
|
||||
device,
|
||||
format: gpu.getPreferredCanvasFormat?.() || 'bgra8unorm',
|
||||
usage: renderAttachment | copyDst,
|
||||
});
|
||||
const texture = context.getCurrentTexture?.();
|
||||
const encoder = device.createCommandEncoder?.();
|
||||
if (texture && encoder) {
|
||||
const pass = encoder.beginRenderPass({
|
||||
colorAttachments: [
|
||||
{
|
||||
view: texture.createView(),
|
||||
loadOp: 'clear',
|
||||
storeOp: 'store',
|
||||
clearValue: { r: 0.078, g: 0.078, b: 0.078, a: 1 },
|
||||
},
|
||||
],
|
||||
});
|
||||
pass.end();
|
||||
device.queue.submit([encoder.finish()]);
|
||||
const gpuState = { device, context, canvas };
|
||||
if (presentWebGpuFrame(gpuState, getSourceCanvas())) {
|
||||
setWebGpuState(gpuState);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Fall through to WebGL2 / 2D clear.
|
||||
setWebGpuState(null);
|
||||
// Fall through to WebGL2 or 2D clear.
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof canvas.getContext === 'function') {
|
||||
const gl = /** @type {WebGL2RenderingContext | null} */ (
|
||||
canvas.getContext('webgl2')
|
||||
);
|
||||
if (gl) {
|
||||
gl.clearColor(0.078, 0.078, 0.078, 1);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT ?? 0x4000);
|
||||
return true;
|
||||
}
|
||||
|
||||
const ctx2d = canvas.getContext('2d');
|
||||
if (ctx2d) {
|
||||
ctx2d.fillStyle = '#141414';
|
||||
ctx2d.fillRect(0, 0, canvas.width || 1, canvas.height || 1);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
return paintWebGl2Or2d(canvas, getSourceCanvas());
|
||||
}
|
||||
|
||||
const host =
|
||||
/** @type {{ canvas?: HTMLCanvasElement | null, bindCanvas?: (c: HTMLCanvasElement | null) => void, bindWebGpuDevice?: (d: unknown) => void, markFirstFrameReady?: () => void, handleRuntimeGpuLoss?: () => Promise<unknown> } | undefined} */ (
|
||||
/** @type {unknown} */ (
|
||||
globalThis.window?.__AFFINE_WEB_HOST__ ?? globalThis.__AFFINE_WEB_HOST__
|
||||
)
|
||||
);
|
||||
/**
|
||||
* Attaches the canvas-drawn selection overlay controller and pointer listeners
|
||||
* directly to `#app-canvas` for production `index.html`.
|
||||
*
|
||||
* @param {any} host
|
||||
*/
|
||||
function attachSelectionOverlayRuntime(host) {
|
||||
/** @type {HTMLCanvasElement | OffscreenCanvas | null} */
|
||||
let stageSurface = null;
|
||||
/** @type {{ device: any, context: any, canvas: HTMLCanvasElement } | null} */
|
||||
let webGpuState = null;
|
||||
/** @type {((ctx: CanvasRenderingContext2D, vw: number, vh: number) => void) | null} */
|
||||
let scenePainter = null;
|
||||
/** @type {any} */
|
||||
let selectionInput = null;
|
||||
/** @type {'light' | 'dark'} */
|
||||
let overlayTheme = 'light';
|
||||
/** @type {{ getSelectedText?: () => string, getSelectionToken?: () => unknown, deleteSelection?: (captured?: unknown) => void, insertText?: (t: string) => void, selectAll?: () => void, onDragHandle?: (h: 'start' | 'end', x: number, y: number) => void, onActionResult?: (r: any) => void, clipboard?: any, isSecureContext?: boolean } | null} */
|
||||
let selectionCallbacks = null;
|
||||
/** @type {HTMLCanvasElement | null} */
|
||||
let pointerCanvas = null;
|
||||
let sceneEpoch = 0;
|
||||
|
||||
/**
|
||||
* Presents `surface` to `activeCanvas` via WebGPU (with automatic
|
||||
* replacement-canvas fallback to WebGL2/2D when needed) or WebGL2/2D.
|
||||
*
|
||||
* @param {HTMLCanvasElement} activeCanvas
|
||||
* @param {HTMLCanvasElement | OffscreenCanvas | null} surface
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function presentSurface(activeCanvas, surface) {
|
||||
if (webGpuState && webGpuState.canvas === activeCanvas) {
|
||||
try {
|
||||
if (presentWebGpuFrame(webGpuState, surface)) {
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// Fall back to a fresh WebGL2/2D canvas below.
|
||||
}
|
||||
webGpuState = null;
|
||||
const nextCanvas = replaceCanvasForWebGl2Fallback(activeCanvas, host);
|
||||
bindPointerCanvas(nextCanvas);
|
||||
return paintWebGl2Or2d(nextCanvas, surface);
|
||||
}
|
||||
return paintWebGl2Or2d(activeCanvas, surface);
|
||||
}
|
||||
|
||||
function renderCompositeFrame() {
|
||||
const activeCanvas = host.canvas;
|
||||
if (!activeCanvas) {
|
||||
return false;
|
||||
}
|
||||
if (!scenePainter && !selectionInput) {
|
||||
return presentSurface(activeCanvas, null);
|
||||
}
|
||||
const dpr = Math.max(1, globalThis.window?.devicePixelRatio || 1);
|
||||
const vw =
|
||||
globalThis.window?.innerWidth ||
|
||||
Math.max(1, Math.round((activeCanvas.width || 390) / dpr));
|
||||
const vh =
|
||||
globalThis.window?.innerHeight ||
|
||||
Math.max(1, Math.round((activeCanvas.height || 844) / dpr));
|
||||
const pixelW = Math.max(1, Math.round(vw * dpr));
|
||||
const pixelH = Math.max(1, Math.round(vh * dpr));
|
||||
if (activeCanvas.width !== pixelW || activeCanvas.height !== pixelH) {
|
||||
activeCanvas.width = pixelW;
|
||||
activeCanvas.height = pixelH;
|
||||
}
|
||||
if (
|
||||
!stageSurface ||
|
||||
stageSurface.width !== pixelW ||
|
||||
stageSurface.height !== pixelH
|
||||
) {
|
||||
stageSurface = createOffscreenSurface(pixelW, pixelH);
|
||||
}
|
||||
if (!stageSurface) {
|
||||
return false;
|
||||
}
|
||||
const ctx = /** @type {CanvasRenderingContext2D | null} */ (
|
||||
stageSurface.getContext('2d')
|
||||
);
|
||||
if (!ctx) {
|
||||
return false;
|
||||
}
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
if (scenePainter) {
|
||||
scenePainter(ctx, vw, vh);
|
||||
} else {
|
||||
ctx.fillStyle = '#ffffff';
|
||||
ctx.fillRect(0, 0, vw, vh);
|
||||
}
|
||||
const layout = selectionController.getLayout();
|
||||
if (layout) {
|
||||
drawSelectionOverlay(ctx, layout, {
|
||||
theme: overlayTheme,
|
||||
activeActionId: selectionController.getActiveActionId(),
|
||||
});
|
||||
}
|
||||
return presentSurface(activeCanvas, stageSurface);
|
||||
}
|
||||
|
||||
const selectionController = createSelectionOverlayController({
|
||||
getInput: () => selectionInput,
|
||||
onDragHandle: (handle, x, y) => {
|
||||
selectionCallbacks?.onDragHandle?.(handle, x, y);
|
||||
},
|
||||
onAction: async action => {
|
||||
const activeCallbacks = selectionCallbacks;
|
||||
if (!activeCallbacks) {
|
||||
return null;
|
||||
}
|
||||
const actionEpoch = sceneEpoch;
|
||||
const isActiveScene = () =>
|
||||
sceneEpoch === actionEpoch && selectionCallbacks === activeCallbacks;
|
||||
const res = await host.executeClipboardAction({
|
||||
action,
|
||||
getSelectedText: () =>
|
||||
isActiveScene() && activeCallbacks.getSelectedText
|
||||
? activeCallbacks.getSelectedText()
|
||||
: '',
|
||||
getSelectionToken:
|
||||
typeof activeCallbacks.getSelectionToken === 'function'
|
||||
? () =>
|
||||
isActiveScene()
|
||||
? activeCallbacks.getSelectionToken()
|
||||
: Symbol('stale-scene')
|
||||
: undefined,
|
||||
deleteSelection:
|
||||
typeof activeCallbacks.deleteSelection === 'function'
|
||||
? arg => {
|
||||
if (isActiveScene()) {
|
||||
activeCallbacks.deleteSelection(arg);
|
||||
}
|
||||
}
|
||||
: undefined,
|
||||
insertText:
|
||||
typeof activeCallbacks.insertText === 'function'
|
||||
? text => {
|
||||
if (isActiveScene()) {
|
||||
activeCallbacks.insertText(text);
|
||||
}
|
||||
}
|
||||
: undefined,
|
||||
selectAll:
|
||||
typeof activeCallbacks.selectAll === 'function'
|
||||
? () => {
|
||||
if (isActiveScene()) {
|
||||
activeCallbacks.selectAll();
|
||||
}
|
||||
}
|
||||
: undefined,
|
||||
clipboard: activeCallbacks.clipboard,
|
||||
isSecureContext: activeCallbacks.isSecureContext,
|
||||
});
|
||||
if (!isActiveScene()) {
|
||||
return res;
|
||||
}
|
||||
activeCallbacks.onActionResult?.(res);
|
||||
renderCompositeFrame();
|
||||
return res;
|
||||
},
|
||||
onLayoutChange: () => {
|
||||
renderCompositeFrame();
|
||||
},
|
||||
});
|
||||
|
||||
/** @param {PointerEvent} event */
|
||||
function toCanvasCoords(event) {
|
||||
const rect = pointerCanvas?.getBoundingClientRect?.();
|
||||
return {
|
||||
x: event.clientX - (rect?.left ?? 0),
|
||||
y: event.clientY - (rect?.top ?? 0),
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {PointerEvent} event */
|
||||
function handlePointerDown(event) {
|
||||
const { x, y } = toCanvasCoords(event);
|
||||
const res = selectionController.onPointerDown(x, y);
|
||||
if (res.handled) {
|
||||
event.preventDefault?.();
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {PointerEvent} event */
|
||||
function handlePointerMove(event) {
|
||||
const { x, y } = toCanvasCoords(event);
|
||||
if (selectionController.onPointerMove(x, y)) {
|
||||
event.preventDefault?.();
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {PointerEvent} event */
|
||||
function handlePointerUp(event) {
|
||||
const { x, y } = toCanvasCoords(event);
|
||||
const res = selectionController.onPointerUp(x, y);
|
||||
if (res.handled) {
|
||||
event.preventDefault?.();
|
||||
}
|
||||
}
|
||||
|
||||
function handlePointerCancel() {
|
||||
selectionController.onPointerCancel();
|
||||
}
|
||||
|
||||
/** @param {HTMLCanvasElement | null} nextCanvas */
|
||||
function bindPointerCanvas(nextCanvas) {
|
||||
if (pointerCanvas === nextCanvas) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
pointerCanvas &&
|
||||
typeof pointerCanvas.removeEventListener === 'function'
|
||||
) {
|
||||
pointerCanvas.removeEventListener('pointerdown', handlePointerDown);
|
||||
pointerCanvas.removeEventListener('pointermove', handlePointerMove);
|
||||
pointerCanvas.removeEventListener('pointerup', handlePointerUp);
|
||||
pointerCanvas.removeEventListener('pointercancel', handlePointerCancel);
|
||||
}
|
||||
pointerCanvas = nextCanvas;
|
||||
if (pointerCanvas && typeof pointerCanvas.addEventListener === 'function') {
|
||||
pointerCanvas.addEventListener('pointerdown', handlePointerDown);
|
||||
pointerCanvas.addEventListener('pointermove', handlePointerMove);
|
||||
pointerCanvas.addEventListener('pointerup', handlePointerUp);
|
||||
pointerCanvas.addEventListener('pointercancel', handlePointerCancel);
|
||||
}
|
||||
}
|
||||
|
||||
host.selectionOverlay = {
|
||||
controller: selectionController,
|
||||
/**
|
||||
* Configures the canvas scene painter and optional selection overlay input,
|
||||
* then composites the frame onto `#app-canvas`. Clears interactive
|
||||
* selection state if presenting fails so invisible buttons cannot be hit.
|
||||
*
|
||||
* @param {{ paint?: ((ctx: CanvasRenderingContext2D, vw: number, vh: number) => void) | null, selection?: any, theme?: 'light' | 'dark', callbacks?: any }} config
|
||||
*/
|
||||
setScene(config) {
|
||||
sceneEpoch += 1;
|
||||
scenePainter = config.paint ?? null;
|
||||
selectionInput = config.selection ?? null;
|
||||
overlayTheme = config.theme || 'light';
|
||||
selectionCallbacks = config.callbacks ?? null;
|
||||
const presented = renderCompositeFrame();
|
||||
if (!presented) {
|
||||
selectionInput = null;
|
||||
selectionCallbacks = null;
|
||||
host.setSelectionOverlayActive?.(false);
|
||||
return false;
|
||||
}
|
||||
host.setSelectionOverlayActive?.(Boolean(selectionInput));
|
||||
return true;
|
||||
},
|
||||
renderFrame: renderCompositeFrame,
|
||||
getLayout: () => selectionController.getLayout(),
|
||||
};
|
||||
|
||||
return {
|
||||
bindPointerCanvas,
|
||||
renderCompositeFrame,
|
||||
getSourceCanvas: () => stageSurface,
|
||||
setWebGpuState: state => {
|
||||
webGpuState = state;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const host = /** @type {any} */ (
|
||||
globalThis.window?.__AFFINE_WEB_HOST__ ?? globalThis.__AFFINE_WEB_HOST__
|
||||
);
|
||||
|
||||
let firstFrameCleared = false;
|
||||
if (host) {
|
||||
const overlayRuntime = attachSelectionOverlayRuntime(host);
|
||||
host.bindCanvas?.(host.canvas ?? null);
|
||||
overlayRuntime.bindPointerCanvas(host.canvas ?? null);
|
||||
host.setGraphicsRecoveryHooks?.({
|
||||
onContextRestored: activeCanvas => {
|
||||
if (!activeCanvas) {
|
||||
return false;
|
||||
}
|
||||
const gl = activeCanvas.getContext?.('webgl2');
|
||||
if (gl && /** @type {any} */ (gl).__affineQuadState) {
|
||||
delete (/** @type {any} */ (gl).__affineQuadState);
|
||||
}
|
||||
return overlayRuntime.renderCompositeFrame();
|
||||
},
|
||||
});
|
||||
if (host.canvas) {
|
||||
firstFrameCleared = await presentFirstFrameClear(host.canvas, host);
|
||||
firstFrameCleared = await presentFirstFrameClear(
|
||||
host.canvas,
|
||||
host,
|
||||
overlayRuntime.getSourceCanvas,
|
||||
nextCanvas => overlayRuntime.bindPointerCanvas(nextCanvas),
|
||||
state => overlayRuntime.setWebGpuState(state)
|
||||
);
|
||||
}
|
||||
if (firstFrameCleared) {
|
||||
host.markFirstFrameReady?.();
|
||||
|
||||
@@ -11,6 +11,11 @@ import {
|
||||
setLocalWorkspaceIds,
|
||||
setWebPreference,
|
||||
} from './idb-storage.js';
|
||||
import { createPdfPreviewClient } from './pdf-client.js';
|
||||
import {
|
||||
attachImeSelectionGuard,
|
||||
executeClipboardAction,
|
||||
} from './selection-overlay.js';
|
||||
import { createWorkerLoader, readEmbeddedManifest } from './worker-loader.js';
|
||||
|
||||
/**
|
||||
@@ -387,21 +392,525 @@ export function removeBootSkeleton(doc) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a fatal boot error inside `#boot`.
|
||||
* Creates a deterministic graphics context recovery and legacy-fallback
|
||||
* controller for `#app-canvas` WebGL2 and WebGPU devices.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {() => string} options.getHref
|
||||
* @param {() => boolean} options.isOAuthCodeConsumed
|
||||
* @param {() => HTMLCanvasElement | null} [options.getActiveCanvas]
|
||||
* @param {() => void} options.pauseInput
|
||||
* @param {() => void} options.resumeInput
|
||||
* @param {() => void} [options.freezeFrameLoop]
|
||||
* @param {() => void} [options.unfreezeFrameLoop]
|
||||
* @param {() => Promise<boolean | { ok: boolean, pendingCount?: number }>} options.flushPendingWrites
|
||||
* @param {(url: string) => void} options.navigate
|
||||
* @param {(message: string, opts?: { retryable?: boolean }) => void} [options.showFatal]
|
||||
* @param {() => void} [options.hideFatal]
|
||||
* @param {() => boolean} [options.isDocumentHidden]
|
||||
* @param {(canvas: HTMLCanvasElement | null) => boolean | Promise<boolean>} [options.onContextRestored]
|
||||
* @param {(info: unknown) => boolean | Promise<boolean>} [options.tryWebGl2Fallback]
|
||||
* @param {number} [options.restoreTimeoutMs=4000]
|
||||
* @param {number} [options.maxContextLosses=3]
|
||||
* @param {number} [options.lossWindowMs=30000]
|
||||
* @param {() => number} [options.now]
|
||||
* @param {(fn: () => void, ms: number) => unknown} [options.setTimer]
|
||||
* @param {(handle: unknown) => void} [options.clearTimer]
|
||||
*/
|
||||
export function createGpuRecoveryController(options) {
|
||||
const restoreTimeoutMs = Math.max(1, options.restoreTimeoutMs ?? 4000);
|
||||
const maxContextLosses = Math.max(1, options.maxContextLosses ?? 3);
|
||||
const lossWindowMs = Math.max(1, options.lossWindowMs ?? 30_000);
|
||||
const now = options.now || (() => Date.now());
|
||||
const setTimer = options.setTimer || ((fn, ms) => setTimeout(fn, ms));
|
||||
const clearTimer =
|
||||
options.clearTimer || (handle => clearTimeout(/** @type {any} */ (handle)));
|
||||
|
||||
/** @type {'ready' | 'context-lost' | 'fallback-pending' | 'fallback-blocked' | 'fallback-navigated' | 'fatal'} */
|
||||
let status = 'ready';
|
||||
let inputPaused = false;
|
||||
let frameLoopFrozen = false;
|
||||
let totalLossCount = 0;
|
||||
let restoreCount = 0;
|
||||
let recoveryEpoch = 0;
|
||||
/** @type {number[]} */
|
||||
let lossTimestamps = [];
|
||||
/** @type {unknown} */
|
||||
let restoreTimer = null;
|
||||
let restoreTimerPausedByVisibility = false;
|
||||
/** @type {Promise<{ navigated: boolean, retryable?: boolean, reason?: string }> | null} */
|
||||
let fallbackInFlight = null;
|
||||
/** @type {string | null} */
|
||||
let lastError = null;
|
||||
/** @type {string | null} */
|
||||
let lastFallbackReason = null;
|
||||
/** @type {string | null} */
|
||||
let pendingFallbackUrl = null;
|
||||
/** @type {((canvas: HTMLCanvasElement | null) => boolean | Promise<boolean>) | null} */
|
||||
let onContextRestoredHook = options.onContextRestored || null;
|
||||
/** @type {((info: unknown) => boolean | Promise<boolean>) | null} */
|
||||
let tryWebGl2FallbackHook = options.tryWebGl2Fallback || null;
|
||||
|
||||
function clearRestoreTimer() {
|
||||
restoreTimerPausedByVisibility = false;
|
||||
if (restoreTimer !== null) {
|
||||
clearTimer(restoreTimer);
|
||||
restoreTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleRestoreTimeout() {
|
||||
clearRestoreTimer();
|
||||
if (options.isDocumentHidden?.()) {
|
||||
restoreTimerPausedByVisibility = true;
|
||||
return;
|
||||
}
|
||||
restoreTimer = setTimer(() => {
|
||||
restoreTimer = null;
|
||||
void triggerFallback('context-restore-timeout');
|
||||
}, restoreTimeoutMs);
|
||||
}
|
||||
|
||||
function pauseAll() {
|
||||
if (!inputPaused) {
|
||||
inputPaused = true;
|
||||
options.pauseInput();
|
||||
}
|
||||
if (!frameLoopFrozen) {
|
||||
frameLoopFrozen = true;
|
||||
options.freezeFrameLoop?.();
|
||||
}
|
||||
}
|
||||
|
||||
function resumeAll() {
|
||||
if (frameLoopFrozen) {
|
||||
frameLoopFrozen = false;
|
||||
options.unfreezeFrameLoop?.();
|
||||
}
|
||||
if (inputPaused) {
|
||||
inputPaused = false;
|
||||
options.resumeInput();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flushes pending IndexedDB writes and navigates to `?shell=legacy` only
|
||||
* after persistence succeeds. Single-flight mutex prevents overlapping
|
||||
* flushes or duplicate navigations. Aborts navigation and exposes a
|
||||
* retryable error state if persistence fails.
|
||||
*
|
||||
* @param {string} [reason='runtime-gpu-loss']
|
||||
* @returns {Promise<{ navigated: boolean, retryable?: boolean, reason?: string }>}
|
||||
*/
|
||||
function triggerFallback(reason = 'runtime-gpu-loss') {
|
||||
if (fallbackInFlight) {
|
||||
return fallbackInFlight;
|
||||
}
|
||||
if (status === 'fallback-navigated' || status === 'fatal') {
|
||||
return Promise.resolve({
|
||||
navigated: false,
|
||||
retryable: false,
|
||||
reason: status,
|
||||
});
|
||||
}
|
||||
|
||||
clearRestoreTimer();
|
||||
pauseAll();
|
||||
recoveryEpoch += 1;
|
||||
lastFallbackReason = reason;
|
||||
|
||||
if (isLegacyShellUrl(options.getHref())) {
|
||||
status = 'fatal';
|
||||
lastError = 'already-legacy';
|
||||
options.showFatal?.('Graphics context was lost.', { retryable: false });
|
||||
return Promise.resolve({
|
||||
navigated: false,
|
||||
retryable: false,
|
||||
reason: 'already-legacy',
|
||||
});
|
||||
}
|
||||
|
||||
const fallback = buildLegacyFallbackUrl(options.getHref(), {
|
||||
codeConsumed: options.isOAuthCodeConsumed(),
|
||||
});
|
||||
status = 'fallback-pending';
|
||||
pendingFallbackUrl = fallback.url;
|
||||
|
||||
const run = (async () => {
|
||||
try {
|
||||
const result = await flushBeforeNavigation({
|
||||
pauseInput: () => pauseAll(),
|
||||
flushPendingWrites: options.flushPendingWrites,
|
||||
navigate: options.navigate,
|
||||
targetUrl: fallback.url,
|
||||
});
|
||||
|
||||
if (result.navigated) {
|
||||
status = 'fallback-navigated';
|
||||
lastError = null;
|
||||
pendingFallbackUrl = null;
|
||||
return { navigated: true };
|
||||
}
|
||||
|
||||
status = 'fallback-blocked';
|
||||
lastError = result.reason || 'flush-rejected';
|
||||
options.showFatal?.(
|
||||
'Unable to save pending edits. Tap Retry to try again.',
|
||||
{ retryable: true }
|
||||
);
|
||||
return {
|
||||
navigated: false,
|
||||
retryable: true,
|
||||
reason: lastError,
|
||||
};
|
||||
} finally {
|
||||
fallbackInFlight = null;
|
||||
}
|
||||
})();
|
||||
|
||||
fallbackInFlight = run;
|
||||
return run;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles `#app-canvas` `webglcontextlost`. Calls `preventDefault()`, pauses
|
||||
* input, freezes the frame loop, and starts the visibility-aware restore
|
||||
* timeout. Ignores duplicate losses once fallback is pending or terminal.
|
||||
*
|
||||
* @param {Event | null | undefined} event
|
||||
* @returns {{ tripped: boolean, lossCountInWindow: number }}
|
||||
*/
|
||||
function handleWebGlContextLost(event) {
|
||||
if (event && typeof event.preventDefault === 'function') {
|
||||
event.preventDefault();
|
||||
}
|
||||
if (
|
||||
fallbackInFlight !== null ||
|
||||
status === 'fallback-pending' ||
|
||||
status === 'fallback-navigated' ||
|
||||
status === 'fatal'
|
||||
) {
|
||||
return { tripped: false, lossCountInWindow: lossTimestamps.length };
|
||||
}
|
||||
|
||||
pauseAll();
|
||||
recoveryEpoch += 1;
|
||||
const t = now();
|
||||
totalLossCount += 1;
|
||||
lossTimestamps = lossTimestamps.filter(ts => t - ts <= lossWindowMs);
|
||||
lossTimestamps.push(t);
|
||||
|
||||
if (lossTimestamps.length >= maxContextLosses) {
|
||||
void triggerFallback('context-loss-threshold');
|
||||
return { tripped: true, lossCountInWindow: lossTimestamps.length };
|
||||
}
|
||||
|
||||
status = 'context-lost';
|
||||
scheduleRestoreTimeout();
|
||||
|
||||
return { tripped: false, lossCountInWindow: lossTimestamps.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* Pauses or resumes the restore timeout when page visibility changes.
|
||||
*
|
||||
* @param {boolean} hidden
|
||||
*/
|
||||
function handleVisibilityChange(hidden) {
|
||||
if (status !== 'context-lost') {
|
||||
return;
|
||||
}
|
||||
if (hidden) {
|
||||
if (restoreTimer !== null) {
|
||||
clearTimer(restoreTimer);
|
||||
restoreTimer = null;
|
||||
}
|
||||
restoreTimerPausedByVisibility = true;
|
||||
} else if (restoreTimerPausedByVisibility) {
|
||||
scheduleRestoreTimeout();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles `#app-canvas` `webglcontextrestored`. Rebuilds render targets and
|
||||
* redraws immediately, then resumes the frame loop and input delivery.
|
||||
* Strictly blocked once fallback is pending, navigated, or fatal, or when a
|
||||
* newer loss epoch superseded this async restore.
|
||||
*
|
||||
* @returns {Promise<{ recovered: boolean, reason?: string }>}
|
||||
*/
|
||||
async function handleWebGlContextRestored() {
|
||||
clearRestoreTimer();
|
||||
if (
|
||||
fallbackInFlight !== null ||
|
||||
status === 'fallback-pending' ||
|
||||
status === 'fallback-navigated' ||
|
||||
status === 'fatal'
|
||||
) {
|
||||
return { recovered: false, reason: status };
|
||||
}
|
||||
const epoch = recoveryEpoch;
|
||||
try {
|
||||
const rebuilt = onContextRestoredHook
|
||||
? await onContextRestoredHook(options.getActiveCanvas?.() ?? null)
|
||||
: true;
|
||||
if (
|
||||
epoch !== recoveryEpoch ||
|
||||
fallbackInFlight !== null ||
|
||||
status === 'fallback-pending' ||
|
||||
status === 'fallback-navigated' ||
|
||||
status === 'fatal'
|
||||
) {
|
||||
return { recovered: false, reason: status };
|
||||
}
|
||||
if (!rebuilt) {
|
||||
await triggerFallback('context-restore-failed');
|
||||
return { recovered: false, reason: 'context-restore-failed' };
|
||||
}
|
||||
restoreCount += 1;
|
||||
status = 'ready';
|
||||
lastError = null;
|
||||
pendingFallbackUrl = null;
|
||||
options.hideFatal?.();
|
||||
resumeAll();
|
||||
return { recovered: true };
|
||||
} catch {
|
||||
if (
|
||||
epoch !== recoveryEpoch ||
|
||||
fallbackInFlight !== null ||
|
||||
status === 'fallback-pending' ||
|
||||
status === 'fallback-navigated' ||
|
||||
status === 'fatal'
|
||||
) {
|
||||
return { recovered: false, reason: status };
|
||||
}
|
||||
await triggerFallback('context-restore-failed');
|
||||
return { recovered: false, reason: 'context-restore-failed' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles WebGPU `device.lost`. Tries WebGL2 downgrade when a fallback hook
|
||||
* is provided; triggers the IDB-flushed legacy circuit breaker otherwise.
|
||||
*
|
||||
* @param {unknown} info
|
||||
* @param {{ tryWebGl2Fallback?: (info: unknown) => boolean | Promise<boolean> }} [override]
|
||||
* @returns {Promise<{ recovered: boolean, mode?: string, navigated?: boolean, retryable?: boolean, reason?: string }>}
|
||||
*/
|
||||
async function handleWebGpuDeviceLost(info, override = {}) {
|
||||
if (
|
||||
fallbackInFlight !== null ||
|
||||
status === 'fallback-pending' ||
|
||||
status === 'fallback-navigated' ||
|
||||
status === 'fatal'
|
||||
) {
|
||||
if (fallbackInFlight) {
|
||||
const res = await fallbackInFlight;
|
||||
return { recovered: false, ...res };
|
||||
}
|
||||
return { recovered: false, navigated: false, reason: status };
|
||||
}
|
||||
clearRestoreTimer();
|
||||
pauseAll();
|
||||
recoveryEpoch += 1;
|
||||
const epoch = recoveryEpoch;
|
||||
const fallbackFn = override.tryWebGl2Fallback || tryWebGl2FallbackHook;
|
||||
if (typeof fallbackFn === 'function') {
|
||||
try {
|
||||
const ok = await fallbackFn(info);
|
||||
if (
|
||||
epoch !== recoveryEpoch ||
|
||||
fallbackInFlight !== null ||
|
||||
status === 'fallback-pending' ||
|
||||
status === 'fallback-navigated' ||
|
||||
status === 'fatal'
|
||||
) {
|
||||
return { recovered: false, navigated: false, reason: status };
|
||||
}
|
||||
if (ok) {
|
||||
restoreCount += 1;
|
||||
status = 'ready';
|
||||
lastError = null;
|
||||
pendingFallbackUrl = null;
|
||||
options.hideFatal?.();
|
||||
resumeAll();
|
||||
return { recovered: true, mode: 'webgl2' };
|
||||
}
|
||||
} catch {
|
||||
if (
|
||||
epoch !== recoveryEpoch ||
|
||||
fallbackInFlight !== null ||
|
||||
status === 'fallback-pending' ||
|
||||
status === 'fallback-navigated' ||
|
||||
status === 'fatal'
|
||||
) {
|
||||
return { recovered: false, navigated: false, reason: status };
|
||||
}
|
||||
// Fall through to unrecoverable circuit breaker.
|
||||
}
|
||||
}
|
||||
const res = await triggerFallback('webgpu-device-lost');
|
||||
return { recovered: false, ...res };
|
||||
}
|
||||
|
||||
/**
|
||||
* Retries a blocked legacy fallback after an IndexedDB flush error.
|
||||
* Only starts a new single-flight flush when currently `fallback-blocked`.
|
||||
*/
|
||||
function retryFallback() {
|
||||
if (fallbackInFlight) {
|
||||
return fallbackInFlight;
|
||||
}
|
||||
if (status !== 'fallback-blocked') {
|
||||
return Promise.resolve({
|
||||
navigated: false,
|
||||
retryable: false,
|
||||
reason: status,
|
||||
});
|
||||
}
|
||||
return triggerFallback(lastFallbackReason || 'retry-fallback');
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates recovery hooks after app entry boot.
|
||||
*
|
||||
* @param {{ onContextRestored?: (canvas: HTMLCanvasElement | null) => boolean | Promise<boolean>, tryWebGl2Fallback?: (info: unknown) => boolean | Promise<boolean> }} hooks
|
||||
*/
|
||||
function setHooks(hooks) {
|
||||
if (hooks.onContextRestored !== undefined) {
|
||||
onContextRestoredHook = hooks.onContextRestored;
|
||||
}
|
||||
if (hooks.tryWebGl2Fallback !== undefined) {
|
||||
tryWebGl2FallbackHook = hooks.tryWebGl2Fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function dispose() {
|
||||
clearRestoreTimer();
|
||||
}
|
||||
|
||||
return {
|
||||
handleWebGlContextLost,
|
||||
handleWebGlContextRestored,
|
||||
handleWebGpuDeviceLost,
|
||||
handleVisibilityChange,
|
||||
triggerFallback,
|
||||
retryFallback,
|
||||
setHooks,
|
||||
dispose,
|
||||
getState: () => ({
|
||||
status,
|
||||
inputPaused,
|
||||
frameLoopFrozen,
|
||||
totalLossCount,
|
||||
restoreCount,
|
||||
lossCountInWindow: lossTimestamps.length,
|
||||
retryable: status === 'fallback-blocked',
|
||||
lastError,
|
||||
lastFallbackReason,
|
||||
pendingFallbackUrl,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a fatal or retryable error overlay inside `#boot`.
|
||||
* Recreates `#boot` on `doc.body` if the boot skeleton was already removed
|
||||
* after the first canvas frame, keeping zero extra DOM during normal steady
|
||||
* state.
|
||||
*
|
||||
* @param {Document} doc
|
||||
* @param {string} message
|
||||
* @param {{ retryable?: boolean, onRetry?: () => void }} [options]
|
||||
*/
|
||||
export function showBootFatal(doc, message) {
|
||||
const boot = doc.getElementById('boot');
|
||||
export function showBootFatal(doc, message, options = {}) {
|
||||
let boot = doc.getElementById('boot');
|
||||
let msgEl = doc.getElementById('boot-message');
|
||||
|
||||
if (!boot && doc.body && typeof doc.createElement === 'function') {
|
||||
boot = doc.createElement('div');
|
||||
boot.id = 'boot';
|
||||
boot.setAttribute?.('role', 'alert');
|
||||
boot.setAttribute?.('aria-live', 'assertive');
|
||||
if (boot.style) {
|
||||
boot.style.position = 'fixed';
|
||||
boot.style.inset = '0';
|
||||
boot.style.zIndex = '20';
|
||||
boot.style.display = 'flex';
|
||||
boot.style.flexDirection = 'column';
|
||||
boot.style.alignItems = 'center';
|
||||
boot.style.justifyContent = 'center';
|
||||
boot.style.gap = '12px';
|
||||
boot.style.padding = '24px';
|
||||
boot.style.background = 'rgba(20, 20, 24, 0.92)';
|
||||
boot.style.color = '#ffffff';
|
||||
}
|
||||
msgEl = doc.createElement('div');
|
||||
msgEl.id = 'boot-message';
|
||||
if (msgEl.style) {
|
||||
msgEl.style.fontSize = '15px';
|
||||
msgEl.style.lineHeight = '1.5';
|
||||
msgEl.style.textAlign = 'center';
|
||||
msgEl.style.maxWidth = '320px';
|
||||
}
|
||||
boot.append?.(msgEl);
|
||||
doc.body.append?.(boot);
|
||||
}
|
||||
|
||||
if (!boot) {
|
||||
return;
|
||||
}
|
||||
boot.dataset.state = 'fatal';
|
||||
const msgEl = doc.getElementById('boot-message');
|
||||
if (boot.dataset) {
|
||||
boot.dataset.state = 'fatal';
|
||||
}
|
||||
if (msgEl) {
|
||||
msgEl.textContent = message;
|
||||
}
|
||||
|
||||
let retryBtn = doc.getElementById('gpu-fallback-retry');
|
||||
if (options.retryable) {
|
||||
if (!retryBtn && typeof doc.createElement === 'function') {
|
||||
retryBtn = doc.createElement('button');
|
||||
retryBtn.id = 'gpu-fallback-retry';
|
||||
retryBtn.setAttribute?.('type', 'button');
|
||||
retryBtn.textContent = 'Retry';
|
||||
if (retryBtn.style) {
|
||||
retryBtn.style.padding = '10px 20px';
|
||||
retryBtn.style.borderRadius = '8px';
|
||||
retryBtn.style.border = '0';
|
||||
retryBtn.style.background = '#1e6efb';
|
||||
retryBtn.style.color = '#ffffff';
|
||||
retryBtn.style.fontSize = '14px';
|
||||
retryBtn.style.fontWeight = '600';
|
||||
retryBtn.style.cursor = 'pointer';
|
||||
}
|
||||
boot.append?.(retryBtn);
|
||||
}
|
||||
if (retryBtn && options.onRetry) {
|
||||
const btn = /** @type {HTMLButtonElement} */ (retryBtn);
|
||||
btn.disabled = false;
|
||||
btn.onclick = () => {
|
||||
btn.disabled = true;
|
||||
void Promise.resolve(options.onRetry?.()).finally(() => {
|
||||
btn.disabled = false;
|
||||
});
|
||||
};
|
||||
}
|
||||
} else if (retryBtn) {
|
||||
retryBtn.remove?.();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes any runtime `#boot` error banner once recovery or navigation settles.
|
||||
*
|
||||
* @param {Document} doc
|
||||
*/
|
||||
export function hideRuntimeFatal(doc) {
|
||||
const boot = doc.getElementById('boot');
|
||||
if (boot) {
|
||||
boot.remove?.();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -418,6 +927,18 @@ export function showBootFatal(doc, message) {
|
||||
* @param {typeof BroadcastChannel} [env.BroadcastChannelImpl]
|
||||
* @param {ReturnType<typeof createIdbWorkspaceStorage>} [env.workspaceStorage]
|
||||
* @param {() => number} [env.now]
|
||||
* @param {(fn: () => void, ms: number) => unknown} [env.setTimer]
|
||||
* @param {(handle: unknown) => void} [env.clearTimer]
|
||||
* @param {number} [env.restoreTimeoutMs]
|
||||
* @param {number} [env.maxContextLosses]
|
||||
* @param {number} [env.lossWindowMs]
|
||||
* @param {() => void} [env.onFreezeFrameLoop]
|
||||
* @param {() => void} [env.onUnfreezeFrameLoop]
|
||||
* @param {(canvas: HTMLCanvasElement | null) => boolean | Promise<boolean>} [env.onContextRestored]
|
||||
* @param {(info: unknown) => boolean | Promise<boolean>} [env.tryWebGl2Fallback]
|
||||
* @param {string | null} [env.assetBaseUrl]
|
||||
* @param {string} [env.buildId]
|
||||
* @param {number} [env.pdfCacheMaxBytes]
|
||||
*/
|
||||
export async function bootWebHost(env = {}) {
|
||||
const win = env.win || globalThis.window;
|
||||
@@ -502,6 +1023,12 @@ export async function bootWebHost(env = {}) {
|
||||
const manifest = readEmbeddedManifest(doc);
|
||||
const workerLoader = createWorkerLoader(manifest, {
|
||||
baseUrl: win.location.href,
|
||||
assetBaseUrl: env.assetBaseUrl,
|
||||
buildId: env.buildId,
|
||||
});
|
||||
const pdfClient = createPdfPreviewClient({
|
||||
workerLoader,
|
||||
maxCacheBytes: env.pdfCacheMaxBytes,
|
||||
});
|
||||
|
||||
const safeAreaObserver = probe
|
||||
@@ -521,14 +1048,30 @@ export async function bootWebHost(env = {}) {
|
||||
})
|
||||
: null;
|
||||
|
||||
let selectionOverlayActive = false;
|
||||
const imeSelectionGuard = ime
|
||||
? attachImeSelectionGuard(ime, () => selectionOverlayActive)
|
||||
: null;
|
||||
|
||||
let oauthCodeConsumed = false;
|
||||
let inputPaused = false;
|
||||
/** @type {HTMLCanvasElement | null} */
|
||||
let boundCanvas = null;
|
||||
|
||||
/** @param {Event} event */
|
||||
function blockPausedCanvasInput(event) {
|
||||
if (!inputPaused) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault?.();
|
||||
event.stopImmediatePropagation?.();
|
||||
}
|
||||
|
||||
/** @param {string} targetUrl */
|
||||
async function navigateWithFlush(targetUrl) {
|
||||
return flushBeforeNavigation({
|
||||
pauseInput() {
|
||||
inputPaused = true;
|
||||
if (ime) {
|
||||
ime.readOnly = true;
|
||||
}
|
||||
@@ -537,6 +1080,7 @@ export async function bootWebHost(env = {}) {
|
||||
navigate: url => win.location.assign(url),
|
||||
targetUrl,
|
||||
resumeInput() {
|
||||
inputPaused = false;
|
||||
if (ime) {
|
||||
ime.readOnly = false;
|
||||
}
|
||||
@@ -544,23 +1088,61 @@ export async function bootWebHost(env = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
const gpuRecovery = createGpuRecoveryController({
|
||||
getHref: () => win.location.href,
|
||||
isOAuthCodeConsumed: () => oauthCodeConsumed,
|
||||
getActiveCanvas: () => boundCanvas,
|
||||
isDocumentHidden: () => doc.visibilityState === 'hidden',
|
||||
pauseInput() {
|
||||
inputPaused = true;
|
||||
if (ime) {
|
||||
ime.readOnly = true;
|
||||
}
|
||||
},
|
||||
resumeInput() {
|
||||
inputPaused = false;
|
||||
if (ime) {
|
||||
ime.readOnly = false;
|
||||
}
|
||||
},
|
||||
freezeFrameLoop: env.onFreezeFrameLoop,
|
||||
unfreezeFrameLoop: env.onUnfreezeFrameLoop,
|
||||
flushPendingWrites: resolveFlush,
|
||||
navigate: url => win.location.assign(url),
|
||||
showFatal: (message, opts) =>
|
||||
showBootFatal(doc, message, {
|
||||
retryable: Boolean(opts?.retryable),
|
||||
onRetry: opts?.retryable
|
||||
? () => gpuRecovery.retryFallback()
|
||||
: undefined,
|
||||
}),
|
||||
hideFatal: () => hideRuntimeFatal(doc),
|
||||
onContextRestored: env.onContextRestored,
|
||||
tryWebGl2Fallback: env.tryWebGl2Fallback,
|
||||
restoreTimeoutMs: env.restoreTimeoutMs,
|
||||
maxContextLosses: env.maxContextLosses,
|
||||
lossWindowMs: env.lossWindowMs,
|
||||
now: env.now,
|
||||
setTimer: env.setTimer,
|
||||
clearTimer: env.clearTimer,
|
||||
});
|
||||
|
||||
function onVisibilityChange() {
|
||||
gpuRecovery.handleVisibilityChange(doc.visibilityState === 'hidden');
|
||||
}
|
||||
doc.addEventListener?.('visibilitychange', onVisibilityChange);
|
||||
|
||||
async function handleRuntimeGpuLoss() {
|
||||
if (isLegacyShellUrl(win.location.href)) {
|
||||
showBootFatal(doc, 'Graphics context was lost.');
|
||||
return { navigated: false, reason: 'already-legacy' };
|
||||
}
|
||||
const fallback = buildLegacyFallbackUrl(win.location.href, {
|
||||
codeConsumed: oauthCodeConsumed,
|
||||
});
|
||||
return navigateWithFlush(fallback.url);
|
||||
return gpuRecovery.triggerFallback('runtime-gpu-loss');
|
||||
}
|
||||
|
||||
/** @param {Event} event */
|
||||
function onContextLost(event) {
|
||||
if (event && typeof event.preventDefault === 'function') {
|
||||
event.preventDefault();
|
||||
}
|
||||
void handleRuntimeGpuLoss();
|
||||
gpuRecovery.handleWebGlContextLost(event);
|
||||
}
|
||||
|
||||
function onContextRestored() {
|
||||
void gpuRecovery.handleWebGlContextRestored();
|
||||
}
|
||||
|
||||
/** @param {HTMLCanvasElement | null} activeCanvas */
|
||||
@@ -570,18 +1152,44 @@ export async function bootWebHost(env = {}) {
|
||||
}
|
||||
if (boundCanvas && typeof boundCanvas.removeEventListener === 'function') {
|
||||
boundCanvas.removeEventListener('webglcontextlost', onContextLost);
|
||||
boundCanvas.removeEventListener(
|
||||
'webglcontextrestored',
|
||||
onContextRestored
|
||||
);
|
||||
boundCanvas.removeEventListener(
|
||||
'pointerdown',
|
||||
blockPausedCanvasInput,
|
||||
true
|
||||
);
|
||||
boundCanvas.removeEventListener(
|
||||
'pointermove',
|
||||
blockPausedCanvasInput,
|
||||
true
|
||||
);
|
||||
boundCanvas.removeEventListener(
|
||||
'pointerup',
|
||||
blockPausedCanvasInput,
|
||||
true
|
||||
);
|
||||
}
|
||||
boundCanvas = activeCanvas || null;
|
||||
if (boundCanvas && typeof boundCanvas.addEventListener === 'function') {
|
||||
boundCanvas.addEventListener('webglcontextlost', onContextLost);
|
||||
boundCanvas.addEventListener('webglcontextrestored', onContextRestored);
|
||||
boundCanvas.addEventListener('pointerdown', blockPausedCanvasInput, true);
|
||||
boundCanvas.addEventListener('pointermove', blockPausedCanvasInput, true);
|
||||
boundCanvas.addEventListener('pointerup', blockPausedCanvasInput, true);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {{ lost?: Promise<unknown> } | null | undefined} device */
|
||||
function bindWebGpuDevice(device) {
|
||||
/**
|
||||
* @param {{ lost?: Promise<unknown> } | null | undefined} device
|
||||
* @param {{ tryWebGl2Fallback?: (info: unknown) => boolean | Promise<boolean> }} [deviceOpts]
|
||||
*/
|
||||
function bindWebGpuDevice(device, deviceOpts = {}) {
|
||||
if (device && device.lost && typeof device.lost.then === 'function') {
|
||||
void device.lost.then(() => {
|
||||
void handleRuntimeGpuLoss();
|
||||
void device.lost.then(info => {
|
||||
void gpuRecovery.handleWebGpuDeviceLost(info, deviceOpts);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -612,10 +1220,13 @@ export async function bootWebHost(env = {}) {
|
||||
fallback: false,
|
||||
fatal: false,
|
||||
graphics,
|
||||
canvas,
|
||||
get canvas() {
|
||||
return boundCanvas || canvas;
|
||||
},
|
||||
ime,
|
||||
embedLayer,
|
||||
a11yTree,
|
||||
isInputPaused: () => inputPaused,
|
||||
get workspaceStorage() {
|
||||
return workspaceStorage;
|
||||
},
|
||||
@@ -683,9 +1294,24 @@ export async function bootWebHost(env = {}) {
|
||||
return { workspaceStorage, pendingWrites, v1Reader };
|
||||
},
|
||||
workerLoader,
|
||||
pdfClient,
|
||||
gpuRecovery,
|
||||
safeAreaObserver,
|
||||
navigateWithFlush,
|
||||
handleRuntimeGpuLoss,
|
||||
retryGpuFallback: () => gpuRecovery.retryFallback(),
|
||||
setGraphicsRecoveryHooks: hooks => gpuRecovery.setHooks(hooks),
|
||||
setSelectionOverlayActive: active => {
|
||||
selectionOverlayActive = Boolean(active);
|
||||
},
|
||||
executeClipboardAction: params =>
|
||||
executeClipboardAction({
|
||||
...params,
|
||||
clipboard: params.clipboard ?? win.navigator?.clipboard ?? null,
|
||||
isSecureContext: params.isSecureContext ?? win.isSecureContext ?? true,
|
||||
imeEl: ime,
|
||||
doc,
|
||||
}),
|
||||
markOAuthCodeConsumed: () => {
|
||||
oauthCodeConsumed = true;
|
||||
},
|
||||
@@ -758,6 +1384,7 @@ export async function bootWebHost(env = {}) {
|
||||
setWebPreference(key, value, win.localStorage),
|
||||
markFirstFrameReady: () => removeBootSkeleton(doc),
|
||||
dispose: () => {
|
||||
doc.removeEventListener?.('visibilitychange', onVisibilityChange);
|
||||
localWorkspaceChannel?.removeEventListener(
|
||||
'message',
|
||||
handleLocalWorkspaceChanged
|
||||
@@ -766,6 +1393,10 @@ export async function bootWebHost(env = {}) {
|
||||
localWorkspaceListeners.clear();
|
||||
workspaceStorage?.close();
|
||||
safeAreaObserver?.dispose();
|
||||
imeSelectionGuard?.dispose();
|
||||
gpuRecovery.dispose();
|
||||
pdfClient.dispose();
|
||||
workerLoader.dispose();
|
||||
bindCanvas(null);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* Lazy on-demand client for the pure-Rust `hayro` PDF Web Worker.
|
||||
* Spawns zero workers and fetches zero `.wasm` bytes until a caller requests
|
||||
* a PDF page count or page render.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} PdfRenderedPage
|
||||
* @property {number} pageCount
|
||||
* @property {number} widthPx
|
||||
* @property {number} heightPx
|
||||
* @property {Uint8Array} rgba
|
||||
* @property {number} scale
|
||||
* @property {boolean} fromCache
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} PdfWorkerLike
|
||||
* @property {(message: unknown, transfer?: Transferable[]) => void} postMessage
|
||||
* @property {(type: string, listener: (event: MessageEvent) => void) => void} addEventListener
|
||||
* @property {(type: string, listener: (event: MessageEvent) => void) => void} removeEventListener
|
||||
* @property {() => void} [terminate]
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} PdfWorkerLoaderLike
|
||||
* @property {(kind: 'pdf') => PdfWorkerLike} loadWorker
|
||||
* @property {(kind: 'pdf') => boolean} [hasLoadedWorker]
|
||||
* @property {(kind: 'pdf') => boolean} [terminateWorker]
|
||||
*/
|
||||
|
||||
const DEFAULT_MAX_CACHE_BYTES = 16 * 1024 * 1024;
|
||||
const MIN_RENDER_SCALE = 0.25;
|
||||
const MAX_RENDER_SCALE = 4;
|
||||
|
||||
/**
|
||||
* Clamps and normalizes a numeric render scale to match worker rasterization
|
||||
* bounds (`[0.25, 4.0]`).
|
||||
*
|
||||
* @param {number | undefined} scale
|
||||
* @returns {number}
|
||||
*/
|
||||
function normalizeScale(scale) {
|
||||
if (typeof scale !== 'number' || !Number.isFinite(scale) || scale <= 0) {
|
||||
return 1;
|
||||
}
|
||||
const clamped = Math.min(MAX_RENDER_SCALE, Math.max(MIN_RENDER_SCALE, scale));
|
||||
return Math.round(clamped * 100) / 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the deterministic cache and deduplication key for a PDF page render.
|
||||
*
|
||||
* @param {string} docKey
|
||||
* @param {number} pageIndex
|
||||
* @param {number} scale
|
||||
* @returns {string}
|
||||
*/
|
||||
export function buildPdfPageCacheKey(docKey, pageIndex, scale) {
|
||||
return `${docKey}:${pageIndex}:${normalizeScale(scale)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a lazy PDF preview client with request multiplexing, in-flight
|
||||
* deduplication, Transferable zero-copy RGBA delivery, and byte-bounded LRU
|
||||
* eviction for offscreen pages.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {PdfWorkerLoaderLike} options.workerLoader
|
||||
* @param {number} [options.maxCacheBytes]
|
||||
*/
|
||||
export function createPdfPreviewClient(options) {
|
||||
const workerLoader = options.workerLoader;
|
||||
const maxCacheBytes = Math.max(
|
||||
1,
|
||||
options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES
|
||||
);
|
||||
|
||||
/** @type {PdfWorkerLike | null} */
|
||||
let worker = null;
|
||||
let disposed = false;
|
||||
let nextRequestId = 1;
|
||||
let totalCacheBytes = 0;
|
||||
let evictions = 0;
|
||||
let dedupHits = 0;
|
||||
let cacheHits = 0;
|
||||
|
||||
/** @type {Map<number, { resolve: (value: any) => void, reject: (error: Error) => void }>} */
|
||||
const pendingRpc = new Map();
|
||||
|
||||
/** @type {Map<string, Promise<PdfRenderedPage>>} */
|
||||
const inFlightRenders = new Map();
|
||||
|
||||
/** @type {Map<string, Promise<number>>} */
|
||||
const inFlightPageCounts = new Map();
|
||||
|
||||
/** @type {Map<string, number>} */
|
||||
const pageCountCache = new Map();
|
||||
|
||||
/** @type {Map<string, { pageCount: number, widthPx: number, heightPx: number, rgba: Uint8Array, scale: number, byteLength: number }>} */
|
||||
const lruCache = new Map();
|
||||
|
||||
/** @type {Set<string>} */
|
||||
let visibleKeys = new Set();
|
||||
|
||||
/** @param {MessageEvent} event */
|
||||
function handleWorkerMessage(event) {
|
||||
const msg = event?.data;
|
||||
if (!msg || typeof msg !== 'object') {
|
||||
return;
|
||||
}
|
||||
const entry = pendingRpc.get(msg.id);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
pendingRpc.delete(msg.id);
|
||||
if (msg.ok) {
|
||||
entry.resolve(msg.result);
|
||||
} else {
|
||||
entry.reject(new Error(msg.error || 'PDF worker request failed'));
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {Event} event */
|
||||
function handleWorkerError(event) {
|
||||
const message =
|
||||
/** @type {{ message?: string }} */ (
|
||||
/** @type {unknown} */ (event)
|
||||
)?.message || 'PDF worker error';
|
||||
const err = new Error(message);
|
||||
for (const entry of pendingRpc.values()) {
|
||||
entry.reject(err);
|
||||
}
|
||||
pendingRpc.clear();
|
||||
if (worker) {
|
||||
const deadWorker = worker;
|
||||
worker = null;
|
||||
deadWorker.removeEventListener('message', handleWorkerMessage);
|
||||
deadWorker.removeEventListener('error', handleWorkerError);
|
||||
if (typeof workerLoader.terminateWorker === 'function') {
|
||||
workerLoader.terminateWorker('pdf');
|
||||
}
|
||||
deadWorker.terminate?.();
|
||||
}
|
||||
}
|
||||
|
||||
function ensureWorker() {
|
||||
if (disposed) {
|
||||
throw new Error('PDF preview client is disposed');
|
||||
}
|
||||
if (!worker) {
|
||||
worker = workerLoader.loadWorker('pdf');
|
||||
worker.addEventListener('message', handleWorkerMessage);
|
||||
worker.addEventListener('error', handleWorkerError);
|
||||
}
|
||||
return worker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends one RPC message over the lazily spawned PDF worker.
|
||||
*
|
||||
* @param {Record<string, unknown>} payload
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
function sendRpc(payload) {
|
||||
const activeWorker = ensureWorker();
|
||||
const id = nextRequestId++;
|
||||
return new Promise((resolve, reject) => {
|
||||
pendingRpc.set(id, { resolve, reject });
|
||||
activeWorker.postMessage({ ...payload, id });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Evicts least-recently-used entries until `totalCacheBytes <= maxCacheBytes`.
|
||||
* Prefers evicting offscreen keys before visible keys.
|
||||
*
|
||||
* @param {string} [protectedKey]
|
||||
*/
|
||||
function enforceCacheBudget(protectedKey) {
|
||||
if (totalCacheBytes <= maxCacheBytes) {
|
||||
return;
|
||||
}
|
||||
// Pass 1: evict offscreen entries from oldest to newest.
|
||||
for (const [key, item] of lruCache.entries()) {
|
||||
if (totalCacheBytes <= maxCacheBytes) {
|
||||
return;
|
||||
}
|
||||
if (key === protectedKey || visibleKeys.has(key)) {
|
||||
continue;
|
||||
}
|
||||
lruCache.delete(key);
|
||||
totalCacheBytes -= item.byteLength;
|
||||
evictions += 1;
|
||||
}
|
||||
// Pass 2: if still over budget, evict oldest entries except the just-inserted key.
|
||||
for (const [key, item] of lruCache.entries()) {
|
||||
if (totalCacheBytes <= maxCacheBytes) {
|
||||
return;
|
||||
}
|
||||
if (key === protectedKey) {
|
||||
continue;
|
||||
}
|
||||
lruCache.delete(key);
|
||||
totalCacheBytes -= item.byteLength;
|
||||
evictions += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the set of currently visible page cache keys so offscreen pages
|
||||
* are evicted first under memory pressure.
|
||||
*
|
||||
* @param {Iterable<string>} keys
|
||||
*/
|
||||
function setVisibleKeys(keys) {
|
||||
visibleKeys = new Set(keys);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the page count for a PDF document, lazily spawning `pdf-worker`
|
||||
* on the first uncached request.
|
||||
*
|
||||
* @param {{ docKey: string, pdfBytes: Uint8Array }} params
|
||||
* @returns {Promise<number>}
|
||||
*/
|
||||
function getPageCount(params) {
|
||||
if (disposed) {
|
||||
return Promise.reject(new Error('PDF preview client is disposed'));
|
||||
}
|
||||
const cached = pageCountCache.get(params.docKey);
|
||||
if (cached !== undefined) {
|
||||
cacheHits += 1;
|
||||
return Promise.resolve(cached);
|
||||
}
|
||||
const existing = inFlightPageCounts.get(params.docKey);
|
||||
if (existing) {
|
||||
dedupHits += 1;
|
||||
return existing;
|
||||
}
|
||||
const promise = sendRpc({
|
||||
op: 'page_count',
|
||||
pdfBytes: params.pdfBytes,
|
||||
pageIndex: 0,
|
||||
})
|
||||
.then(result => {
|
||||
const count = Number(result.pageCount ?? 0);
|
||||
pageCountCache.set(params.docKey, count);
|
||||
return count;
|
||||
})
|
||||
.finally(() => {
|
||||
inFlightPageCounts.delete(params.docKey);
|
||||
});
|
||||
inFlightPageCounts.set(params.docKey, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders one PDF page to RGBA pixels, deduplicating concurrent requests for
|
||||
* the same `(docKey, pageIndex, scale)` and caching results under the byte
|
||||
* budget.
|
||||
*
|
||||
* @param {{ docKey: string, pdfBytes: Uint8Array, pageIndex: number, scale?: number }} params
|
||||
* @returns {Promise<PdfRenderedPage>}
|
||||
*/
|
||||
function renderPage(params) {
|
||||
if (disposed) {
|
||||
return Promise.reject(new Error('PDF preview client is disposed'));
|
||||
}
|
||||
const scale = normalizeScale(params.scale);
|
||||
const cacheKey = buildPdfPageCacheKey(
|
||||
params.docKey,
|
||||
params.pageIndex,
|
||||
scale
|
||||
);
|
||||
|
||||
const cached = lruCache.get(cacheKey);
|
||||
if (cached) {
|
||||
if (cached.rgba.byteLength === 0) {
|
||||
lruCache.delete(cacheKey);
|
||||
totalCacheBytes = Math.max(0, totalCacheBytes - cached.byteLength);
|
||||
} else {
|
||||
// Refresh LRU recency and return an owned copy so caller transfers cannot empty cache.
|
||||
lruCache.delete(cacheKey);
|
||||
lruCache.set(cacheKey, cached);
|
||||
cacheHits += 1;
|
||||
return Promise.resolve({
|
||||
pageCount: cached.pageCount,
|
||||
widthPx: cached.widthPx,
|
||||
heightPx: cached.heightPx,
|
||||
rgba: cached.rgba.slice(),
|
||||
scale: cached.scale,
|
||||
fromCache: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const wrapPrivateResult = shared =>
|
||||
shared.then(res => ({
|
||||
pageCount: res.pageCount,
|
||||
widthPx: res.widthPx,
|
||||
heightPx: res.heightPx,
|
||||
rgba: res.rgba.slice(),
|
||||
scale: res.scale,
|
||||
fromCache: false,
|
||||
}));
|
||||
|
||||
const inFlight = inFlightRenders.get(cacheKey);
|
||||
if (inFlight) {
|
||||
dedupHits += 1;
|
||||
return wrapPrivateResult(inFlight);
|
||||
}
|
||||
|
||||
const sharedPromise = sendRpc({
|
||||
pdfBytes: params.pdfBytes,
|
||||
pageIndex: params.pageIndex,
|
||||
scale,
|
||||
})
|
||||
.then(result => {
|
||||
const rgba =
|
||||
result.rgba instanceof Uint8Array
|
||||
? result.rgba
|
||||
: new Uint8Array(result.rgba);
|
||||
const pageCount = Number(result.pageCount);
|
||||
const widthPx = Number(result.widthPx);
|
||||
const heightPx = Number(result.heightPx);
|
||||
pageCountCache.set(params.docKey, pageCount);
|
||||
|
||||
const byteLength = rgba.byteLength;
|
||||
if (byteLength <= maxCacheBytes) {
|
||||
const prev = lruCache.get(cacheKey);
|
||||
if (prev) {
|
||||
totalCacheBytes -= prev.byteLength;
|
||||
lruCache.delete(cacheKey);
|
||||
}
|
||||
lruCache.set(cacheKey, {
|
||||
pageCount,
|
||||
widthPx,
|
||||
heightPx,
|
||||
rgba,
|
||||
scale,
|
||||
byteLength,
|
||||
});
|
||||
totalCacheBytes += byteLength;
|
||||
enforceCacheBudget(cacheKey);
|
||||
}
|
||||
|
||||
return {
|
||||
pageCount,
|
||||
widthPx,
|
||||
heightPx,
|
||||
rgba,
|
||||
scale,
|
||||
fromCache: false,
|
||||
};
|
||||
})
|
||||
.finally(() => {
|
||||
inFlightRenders.delete(cacheKey);
|
||||
});
|
||||
|
||||
inFlightRenders.set(cacheKey, sharedPromise);
|
||||
return wrapPrivateResult(sharedPromise);
|
||||
}
|
||||
|
||||
/**
|
||||
* Terminates the PDF worker, clears cached pixel buffers, and rejects any
|
||||
* remaining pending RPCs.
|
||||
*/
|
||||
function dispose() {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
disposed = true;
|
||||
const err = new Error('PDF preview client disposed');
|
||||
for (const entry of pendingRpc.values()) {
|
||||
entry.reject(err);
|
||||
}
|
||||
pendingRpc.clear();
|
||||
inFlightRenders.clear();
|
||||
inFlightPageCounts.clear();
|
||||
pageCountCache.clear();
|
||||
lruCache.clear();
|
||||
visibleKeys.clear();
|
||||
totalCacheBytes = 0;
|
||||
|
||||
if (worker) {
|
||||
worker.removeEventListener('message', handleWorkerMessage);
|
||||
worker.removeEventListener('error', handleWorkerError);
|
||||
if (typeof workerLoader.terminateWorker === 'function') {
|
||||
workerLoader.terminateWorker('pdf');
|
||||
} else {
|
||||
worker.terminate?.();
|
||||
}
|
||||
worker = null;
|
||||
}
|
||||
}
|
||||
|
||||
return Object.freeze({
|
||||
getPageCount,
|
||||
renderPage,
|
||||
setVisibleKeys,
|
||||
dispose,
|
||||
getStats: () => ({
|
||||
workerSpawned: worker !== null,
|
||||
disposed,
|
||||
activeRequests: pendingRpc.size,
|
||||
cacheEntries: lruCache.size,
|
||||
cacheBytes: totalCacheBytes,
|
||||
maxCacheBytes,
|
||||
evictions,
|
||||
dedupHits,
|
||||
cacheHits,
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,951 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* Canvas-drawn text selection overlay, teardrop handles, and mobile clipboard
|
||||
* gesture bridge. Draws all selection visuals on `#app-canvas` with zero
|
||||
* floating DOM nodes.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} Rect
|
||||
* @property {number} x
|
||||
* @property {number} y
|
||||
* @property {number} width
|
||||
* @property {number} height
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} CaretAnchor
|
||||
* @property {number} x
|
||||
* @property {number} y
|
||||
* @property {number} height
|
||||
* @property {'ltr' | 'rtl'} [dir]
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} SafeAreaInsets
|
||||
* @property {number} top
|
||||
* @property {number} right
|
||||
* @property {number} bottom
|
||||
* @property {number} left
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {'copy' | 'cut' | 'paste' | 'select-all'} SelectionActionId
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} SelectionHandleLayout
|
||||
* @property {'start' | 'end'} kind
|
||||
* @property {'left' | 'right'} flare
|
||||
* @property {number} stemX
|
||||
* @property {number} stemTop
|
||||
* @property {number} stemBottom
|
||||
* @property {number} headCx
|
||||
* @property {number} headCy
|
||||
* @property {number} radius
|
||||
* @property {Rect} hitRect
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} SelectionMenuItemLayout
|
||||
* @property {SelectionActionId} id
|
||||
* @property {string} label
|
||||
* @property {number} x
|
||||
* @property {number} y
|
||||
* @property {number} width
|
||||
* @property {number} height
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} SelectionMenuLayout
|
||||
* @property {boolean} visible
|
||||
* @property {'above' | 'below'} placement
|
||||
* @property {number} x
|
||||
* @property {number} y
|
||||
* @property {number} width
|
||||
* @property {number} height
|
||||
* @property {number} arrowX
|
||||
* @property {SelectionMenuItemLayout[]} items
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} SelectionLoupeLayout
|
||||
* @property {boolean} visible
|
||||
* @property {'start' | 'end' | null} handle
|
||||
* @property {number} cx
|
||||
* @property {number} cy
|
||||
* @property {number} radius
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} SelectionOverlayLayout
|
||||
* @property {Rect[]} rects
|
||||
* @property {SelectionHandleLayout} startHandle
|
||||
* @property {SelectionHandleLayout} endHandle
|
||||
* @property {SelectionMenuLayout} menu
|
||||
* @property {SelectionLoupeLayout} loupe
|
||||
* @property {boolean} dragging
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} SelectionOverlayInput
|
||||
* @property {{ width: number, height: number, safeArea?: Partial<SafeAreaInsets> }} viewport
|
||||
* @property {Rect[]} rects
|
||||
* @property {CaretAnchor} caretStart
|
||||
* @property {CaretAnchor} caretEnd
|
||||
* @property {boolean} [dragging]
|
||||
* @property {'start' | 'end' | null} [activeHandle]
|
||||
* @property {SelectionActionId[]} [actions]
|
||||
* @property {boolean} [readOnly]
|
||||
* @property {boolean} [canPaste]
|
||||
* @property {number} [edgeMargin]
|
||||
*/
|
||||
|
||||
const ACTION_LABELS = Object.freeze({
|
||||
copy: 'Copy',
|
||||
cut: 'Cut',
|
||||
paste: 'Paste',
|
||||
'select-all': 'Select All',
|
||||
});
|
||||
|
||||
const ACTION_MIN_WIDTHS = Object.freeze({
|
||||
copy: 64,
|
||||
cut: 56,
|
||||
paste: 68,
|
||||
'select-all': 92,
|
||||
});
|
||||
|
||||
const DEFAULT_ACTIONS = /** @type {const} */ ([
|
||||
'copy',
|
||||
'cut',
|
||||
'paste',
|
||||
'select-all',
|
||||
]);
|
||||
|
||||
const MIN_EDGE_MARGIN_PX = 12;
|
||||
const HANDLE_RADIUS_PX = 7.5;
|
||||
const HANDLE_HIT_HALF_SIZE_PX = 22;
|
||||
const MENU_HEIGHT_PX = 40;
|
||||
const MENU_GAP_PX = 12;
|
||||
const LOUPE_RADIUS_PX = 28;
|
||||
|
||||
/**
|
||||
* Clamps a numeric value to `[min, max]`.
|
||||
*
|
||||
* @param {number} value
|
||||
* @param {number} min
|
||||
* @param {number} max
|
||||
* @returns {number}
|
||||
*/
|
||||
function clamp(value, min, max) {
|
||||
if (max < min) {
|
||||
return min;
|
||||
}
|
||||
return Math.max(min, Math.min(max, value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true when `(x, y)` lies inside `rect`.
|
||||
*
|
||||
* @param {Rect} rect
|
||||
* @param {number} x
|
||||
* @param {number} y
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function pointInRect(rect, x, y) {
|
||||
return (
|
||||
x >= rect.x &&
|
||||
x <= rect.x + rect.width &&
|
||||
y >= rect.y &&
|
||||
y <= rect.y + rect.height
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds one teardrop handle layout with an outward circular head.
|
||||
*
|
||||
* @param {'start' | 'end'} kind
|
||||
* @param {CaretAnchor} caret
|
||||
* @param {'left' | 'right'} flare
|
||||
* @param {number} headCx
|
||||
* @returns {SelectionHandleLayout}
|
||||
*/
|
||||
function buildHandleLayout(kind, caret, flare, headCx) {
|
||||
const stemTop = caret.y;
|
||||
const stemBottom = caret.y + Math.max(12, caret.height);
|
||||
const headCy = stemBottom + HANDLE_RADIUS_PX + 2;
|
||||
const hitLeft = Math.min(caret.x, headCx) - HANDLE_HIT_HALF_SIZE_PX;
|
||||
const hitRight = Math.max(caret.x, headCx) + HANDLE_HIT_HALF_SIZE_PX;
|
||||
const hitTop = stemTop - 8;
|
||||
const hitBottom = headCy + HANDLE_HIT_HALF_SIZE_PX;
|
||||
return {
|
||||
kind,
|
||||
flare,
|
||||
stemX: caret.x,
|
||||
stemTop,
|
||||
stemBottom,
|
||||
headCx,
|
||||
headCy,
|
||||
radius: HANDLE_RADIUS_PX,
|
||||
hitRect: {
|
||||
x: hitLeft,
|
||||
y: hitTop,
|
||||
width: hitRight - hitLeft,
|
||||
height: hitBottom - hitTop,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes pure layout geometry for selection highlights, outward-flared
|
||||
* teardrop handles, and the floating action menu.
|
||||
*
|
||||
* @param {SelectionOverlayInput} input
|
||||
* @returns {SelectionOverlayLayout}
|
||||
*/
|
||||
export function computeSelectionOverlayLayout(input) {
|
||||
const safeTop = Math.max(0, input.viewport.safeArea?.top ?? 0);
|
||||
const safeRight = Math.max(0, input.viewport.safeArea?.right ?? 0);
|
||||
const safeBottom = Math.max(0, input.viewport.safeArea?.bottom ?? 0);
|
||||
const safeLeft = Math.max(0, input.viewport.safeArea?.left ?? 0);
|
||||
const edgeMargin = Math.max(
|
||||
MIN_EDGE_MARGIN_PX,
|
||||
input.edgeMargin ?? MIN_EDGE_MARGIN_PX
|
||||
);
|
||||
|
||||
const rects = (input.rects || []).map(r => ({
|
||||
x: r.x,
|
||||
y: r.y,
|
||||
width: Math.max(0, r.width),
|
||||
height: Math.max(0, r.height),
|
||||
}));
|
||||
|
||||
const start = input.caretStart;
|
||||
const end = input.caretEnd;
|
||||
const startIsVisualLeft =
|
||||
start.x < end.x || (start.x === end.x && start.dir !== 'rtl');
|
||||
/** @type {'left' | 'right'} */
|
||||
const startFlare = startIsVisualLeft ? 'left' : 'right';
|
||||
/** @type {'left' | 'right'} */
|
||||
const endFlare = startIsVisualLeft ? 'right' : 'left';
|
||||
|
||||
const flareOffset = HANDLE_RADIUS_PX * 0.9;
|
||||
let startHeadCx =
|
||||
start.x + (startFlare === 'left' ? -flareOffset : flareOffset);
|
||||
let endHeadCx = end.x + (endFlare === 'left' ? -flareOffset : flareOffset);
|
||||
|
||||
const startHeadCy =
|
||||
start.y + Math.max(12, start.height) + HANDLE_RADIUS_PX + 2;
|
||||
const endHeadCy = end.y + Math.max(12, end.height) + HANDLE_RADIUS_PX + 2;
|
||||
const minCenterGap = HANDLE_RADIUS_PX * 2 + 4;
|
||||
if (Math.abs(startHeadCy - endHeadCy) < HANDLE_RADIUS_PX * 2 + 2) {
|
||||
const gap = Math.abs(endHeadCx - startHeadCx);
|
||||
if (gap < minCenterGap) {
|
||||
const push = (minCenterGap - gap) / 2;
|
||||
startHeadCx += startFlare === 'left' ? -push : push;
|
||||
endHeadCx += endFlare === 'left' ? -push : push;
|
||||
}
|
||||
}
|
||||
|
||||
const startHandle = buildHandleLayout(
|
||||
'start',
|
||||
start,
|
||||
startFlare,
|
||||
startHeadCx
|
||||
);
|
||||
const endHandle = buildHandleLayout('end', end, endFlare, endHeadCx);
|
||||
|
||||
const requestedActions = input.actions
|
||||
? [...input.actions]
|
||||
: [...DEFAULT_ACTIONS];
|
||||
const filteredActions = requestedActions.filter(id => {
|
||||
if (input.readOnly && (id === 'cut' || id === 'paste')) {
|
||||
return false;
|
||||
}
|
||||
if (input.canPaste === false && id === 'paste') {
|
||||
return false;
|
||||
}
|
||||
return Boolean(ACTION_LABELS[id]);
|
||||
});
|
||||
|
||||
const maxBarWidth = Math.max(
|
||||
120,
|
||||
input.viewport.width - safeLeft - safeRight - edgeMargin * 2
|
||||
);
|
||||
const rawWidth = filteredActions.reduce(
|
||||
(sum, id) => sum + ACTION_MIN_WIDTHS[id],
|
||||
0
|
||||
);
|
||||
const scale = rawWidth > maxBarWidth ? maxBarWidth / rawWidth : 1;
|
||||
const barWidth = Math.min(rawWidth, maxBarWidth);
|
||||
|
||||
const bounds = rects.reduce(
|
||||
(acc, r) => ({
|
||||
minX: Math.min(acc.minX, r.x),
|
||||
minY: Math.min(acc.minY, r.y),
|
||||
maxX: Math.max(acc.maxX, r.x + r.width),
|
||||
maxY: Math.max(acc.maxY, r.y + r.height),
|
||||
}),
|
||||
{
|
||||
minX: Math.min(start.x, end.x),
|
||||
minY: Math.min(start.y, end.y),
|
||||
maxX: Math.max(start.x, end.x),
|
||||
maxY: Math.max(start.y + start.height, end.y + end.height),
|
||||
}
|
||||
);
|
||||
|
||||
const anchorMidX = (bounds.minX + bounds.maxX) / 2;
|
||||
const minX = safeLeft + edgeMargin;
|
||||
const maxX = Math.max(
|
||||
minX,
|
||||
input.viewport.width - safeRight - edgeMargin - barWidth
|
||||
);
|
||||
const menuX = clamp(anchorMidX - barWidth / 2, minX, maxX);
|
||||
|
||||
const aboveY = bounds.minY - MENU_GAP_PX - MENU_HEIGHT_PX;
|
||||
const belowY =
|
||||
Math.max(bounds.maxY, startHandle.headCy, endHandle.headCy) +
|
||||
HANDLE_RADIUS_PX +
|
||||
MENU_GAP_PX;
|
||||
const fitsAbove = aboveY >= safeTop + 8;
|
||||
/** @type {'above' | 'below'} */
|
||||
const placement = fitsAbove ? 'above' : 'below';
|
||||
const menuY = fitsAbove
|
||||
? aboveY
|
||||
: clamp(
|
||||
belowY,
|
||||
safeTop + 8,
|
||||
Math.max(
|
||||
safeTop + 8,
|
||||
input.viewport.height - safeBottom - MENU_HEIGHT_PX - 8
|
||||
)
|
||||
);
|
||||
|
||||
let cursorX = menuX;
|
||||
const items = filteredActions.map(id => {
|
||||
const itemWidth = ACTION_MIN_WIDTHS[id] * scale;
|
||||
const item = {
|
||||
id,
|
||||
label: ACTION_LABELS[id],
|
||||
x: cursorX,
|
||||
y: menuY,
|
||||
width: itemWidth,
|
||||
height: MENU_HEIGHT_PX,
|
||||
};
|
||||
cursorX += itemWidth;
|
||||
return item;
|
||||
});
|
||||
|
||||
const dragging = Boolean(input.dragging);
|
||||
const activeHandle = dragging ? input.activeHandle || 'end' : null;
|
||||
const loupeAnchor = activeHandle === 'start' ? start : end;
|
||||
const loupeCx = clamp(
|
||||
loupeAnchor.x,
|
||||
safeLeft + LOUPE_RADIUS_PX + 8,
|
||||
input.viewport.width - safeRight - LOUPE_RADIUS_PX - 8
|
||||
);
|
||||
const loupeCy = Math.max(
|
||||
safeTop + LOUPE_RADIUS_PX + 8,
|
||||
loupeAnchor.y - LOUPE_RADIUS_PX - 14
|
||||
);
|
||||
|
||||
return {
|
||||
rects,
|
||||
startHandle,
|
||||
endHandle,
|
||||
menu: {
|
||||
visible: !dragging && items.length > 0 && rects.length > 0,
|
||||
placement,
|
||||
x: menuX,
|
||||
y: menuY,
|
||||
width: barWidth,
|
||||
height: MENU_HEIGHT_PX,
|
||||
arrowX: clamp(anchorMidX, menuX + 16, menuX + barWidth - 16),
|
||||
items,
|
||||
},
|
||||
loupe: {
|
||||
visible: dragging,
|
||||
handle: activeHandle,
|
||||
cx: loupeCx,
|
||||
cy: loupeCy,
|
||||
radius: LOUPE_RADIUS_PX,
|
||||
},
|
||||
dragging,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Traces a rounded rectangle path on a Canvas 2D context.
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx
|
||||
* @param {number} x
|
||||
* @param {number} y
|
||||
* @param {number} width
|
||||
* @param {number} height
|
||||
* @param {number} radius
|
||||
*/
|
||||
function traceRoundedRect(ctx, x, y, width, height, radius) {
|
||||
const r = Math.min(radius, width / 2, height / 2);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + r, y);
|
||||
ctx.lineTo(x + width - r, y);
|
||||
ctx.quadraticCurveTo(x + width, y, x + width, y + r);
|
||||
ctx.lineTo(x + width, y + height - r);
|
||||
ctx.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
|
||||
ctx.lineTo(x + r, y + height);
|
||||
ctx.quadraticCurveTo(x, y + height, x, y + height - r);
|
||||
ctx.lineTo(x, y + r);
|
||||
ctx.quadraticCurveTo(x, y, x + r, y);
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a single teardrop handle on a Canvas 2D context.
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx
|
||||
* @param {SelectionHandleLayout} handle
|
||||
* @param {string} accentColor
|
||||
* @param {string} ringColor
|
||||
*/
|
||||
function drawTeardropHandle(ctx, handle, accentColor, ringColor) {
|
||||
ctx.save();
|
||||
ctx.strokeStyle = accentColor;
|
||||
ctx.lineWidth = 2.2;
|
||||
ctx.lineCap = 'round';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(handle.stemX, handle.stemTop);
|
||||
ctx.lineTo(handle.stemX, handle.stemBottom);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(handle.stemX, handle.stemBottom - 1);
|
||||
ctx.lineTo(handle.headCx, handle.headCy);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.fillStyle = accentColor;
|
||||
ctx.beginPath();
|
||||
ctx.arc(handle.headCx, handle.headCy, handle.radius, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
|
||||
ctx.strokeStyle = ringColor;
|
||||
ctx.lineWidth = 1.6;
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws the selection highlight, dual teardrop handles, optional magnifier
|
||||
* loupe, and floating action bar directly on a 2D canvas context.
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx
|
||||
* @param {SelectionOverlayLayout} layout
|
||||
* @param {{ theme?: 'light' | 'dark', activeActionId?: SelectionActionId | null }} [options]
|
||||
*/
|
||||
export function drawSelectionOverlay(ctx, layout, options = {}) {
|
||||
const dark = options.theme === 'dark';
|
||||
const accent = dark ? '#4c9aff' : '#1e6efb';
|
||||
const selectionFill = dark
|
||||
? 'rgba(76, 154, 255, 0.28)'
|
||||
: 'rgba(30, 110, 251, 0.2)';
|
||||
const menuBg = dark ? '#242731' : '#181a20';
|
||||
const menuBorder = dark
|
||||
? 'rgba(255, 255, 255, 0.14)'
|
||||
: 'rgba(255, 255, 255, 0.1)';
|
||||
const menuDivider = 'rgba(255, 255, 255, 0.16)';
|
||||
const menuText = '#ffffff';
|
||||
const activeBg = 'rgba(255, 255, 255, 0.14)';
|
||||
const ringColor = dark ? '#141414' : '#ffffff';
|
||||
|
||||
ctx.save();
|
||||
ctx.fillStyle = selectionFill;
|
||||
for (const r of layout.rects) {
|
||||
traceRoundedRect(ctx, r.x, r.y, r.width, r.height, 4);
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
drawTeardropHandle(ctx, layout.startHandle, accent, ringColor);
|
||||
drawTeardropHandle(ctx, layout.endHandle, accent, ringColor);
|
||||
|
||||
if (layout.loupe.visible) {
|
||||
ctx.save();
|
||||
ctx.shadowColor = 'rgba(0, 0, 0, 0.26)';
|
||||
ctx.shadowBlur = 14;
|
||||
ctx.shadowOffsetY = 4;
|
||||
ctx.fillStyle = dark ? '#22252e' : '#ffffff';
|
||||
ctx.beginPath();
|
||||
ctx.arc(
|
||||
layout.loupe.cx,
|
||||
layout.loupe.cy,
|
||||
layout.loupe.radius,
|
||||
0,
|
||||
Math.PI * 2
|
||||
);
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
|
||||
ctx.save();
|
||||
ctx.strokeStyle = accent;
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
ctx.arc(
|
||||
layout.loupe.cx,
|
||||
layout.loupe.cy,
|
||||
layout.loupe.radius,
|
||||
0,
|
||||
Math.PI * 2
|
||||
);
|
||||
ctx.stroke();
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(layout.loupe.cx, layout.loupe.cy - 10);
|
||||
ctx.lineTo(layout.loupe.cx, layout.loupe.cy + 10);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
if (layout.menu.visible) {
|
||||
const { x, y, width, height, arrowX, placement, items } = layout.menu;
|
||||
ctx.save();
|
||||
ctx.shadowColor = 'rgba(0, 0, 0, 0.28)';
|
||||
ctx.shadowBlur = 16;
|
||||
ctx.shadowOffsetY = 6;
|
||||
ctx.fillStyle = menuBg;
|
||||
traceRoundedRect(ctx, x, y, width, height, 10);
|
||||
ctx.fill();
|
||||
|
||||
// Pointer beak
|
||||
ctx.beginPath();
|
||||
if (placement === 'above') {
|
||||
ctx.moveTo(arrowX - 6, y + height);
|
||||
ctx.lineTo(arrowX + 6, y + height);
|
||||
ctx.lineTo(arrowX, y + height + 6);
|
||||
} else {
|
||||
ctx.moveTo(arrowX - 6, y);
|
||||
ctx.lineTo(arrowX + 6, y);
|
||||
ctx.lineTo(arrowX, y - 6);
|
||||
}
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
|
||||
ctx.save();
|
||||
ctx.strokeStyle = menuBorder;
|
||||
ctx.lineWidth = 1;
|
||||
traceRoundedRect(ctx, x + 0.5, y + 0.5, width - 1, height - 1, 10);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.font =
|
||||
'600 13px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
|
||||
for (let i = 0; i < items.length; i += 1) {
|
||||
const item = items[i];
|
||||
if (options.activeActionId === item.id) {
|
||||
ctx.fillStyle = activeBg;
|
||||
traceRoundedRect(
|
||||
ctx,
|
||||
item.x + 2,
|
||||
item.y + 2,
|
||||
item.width - 4,
|
||||
item.height - 4,
|
||||
8
|
||||
);
|
||||
ctx.fill();
|
||||
}
|
||||
ctx.fillStyle = menuText;
|
||||
ctx.fillText(
|
||||
item.label,
|
||||
item.x + item.width / 2,
|
||||
item.y + item.height / 2
|
||||
);
|
||||
|
||||
if (i < items.length - 1) {
|
||||
ctx.strokeStyle = menuDivider;
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(item.x + item.width, item.y + 9);
|
||||
ctx.lineTo(item.x + item.width, item.y + item.height - 9);
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a clipboard action synchronously inside the user gesture stack.
|
||||
* Uses `navigator.clipboard` in secure contexts and falls back to `#ime`
|
||||
* transient copy on non-HTTPS origins. Never deletes text on Cut if the
|
||||
* clipboard write fails.
|
||||
*
|
||||
* @param {Object} params
|
||||
* @param {SelectionActionId} params.action
|
||||
* @param {() => string} params.getSelectedText
|
||||
* @param {() => unknown} [params.getSelectionToken]
|
||||
* @param {(captured?: { token: unknown, text: string }) => void} [params.deleteSelection]
|
||||
* @param {(text: string) => void} [params.insertText]
|
||||
* @param {() => void} [params.selectAll]
|
||||
* @param {{ writeText?: (text: string) => Promise<void>, readText?: () => Promise<string> } | null} [params.clipboard]
|
||||
* @param {boolean} [params.isSecureContext]
|
||||
* @param {HTMLTextAreaElement | null} [params.imeEl]
|
||||
* @param {Document | null} [params.doc]
|
||||
* @returns {Promise<{ ok: boolean, action: SelectionActionId, method?: string, text?: string, reason?: string }>}
|
||||
*/
|
||||
export async function executeClipboardAction(params) {
|
||||
const {
|
||||
action,
|
||||
getSelectedText,
|
||||
getSelectionToken,
|
||||
deleteSelection,
|
||||
insertText,
|
||||
selectAll,
|
||||
clipboard = globalThis.navigator?.clipboard ?? null,
|
||||
isSecureContext = globalThis.isSecureContext ?? true,
|
||||
imeEl = null,
|
||||
doc = globalThis.document ?? null,
|
||||
} = params;
|
||||
|
||||
if (action === 'select-all') {
|
||||
selectAll?.();
|
||||
return { ok: true, action, method: 'editor' };
|
||||
}
|
||||
|
||||
/** @param {string} text */
|
||||
async function writeTextInGesture(text) {
|
||||
let asyncErrorReason = null;
|
||||
if (
|
||||
isSecureContext &&
|
||||
clipboard &&
|
||||
typeof clipboard.writeText === 'function'
|
||||
) {
|
||||
try {
|
||||
await clipboard.writeText(text);
|
||||
return { ok: true, method: 'async-clipboard' };
|
||||
} catch (error) {
|
||||
asyncErrorReason =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
}
|
||||
if (imeEl && doc && typeof doc.execCommand === 'function') {
|
||||
const prevReadOnly = imeEl.readOnly;
|
||||
try {
|
||||
imeEl.readOnly = false;
|
||||
imeEl.value = text;
|
||||
imeEl.focus?.({ preventScroll: true });
|
||||
imeEl.setSelectionRange?.(0, text.length);
|
||||
const copied = Boolean(doc.execCommand('copy'));
|
||||
imeEl.value = '';
|
||||
imeEl.setSelectionRange?.(0, 0);
|
||||
imeEl.readOnly = prevReadOnly;
|
||||
return copied
|
||||
? { ok: true, method: 'exec-command-fallback' }
|
||||
: {
|
||||
ok: false,
|
||||
reason: asyncErrorReason || 'exec-command-copy-rejected',
|
||||
};
|
||||
} catch (error) {
|
||||
imeEl.value = '';
|
||||
imeEl.readOnly = prevReadOnly;
|
||||
return {
|
||||
ok: false,
|
||||
reason:
|
||||
asyncErrorReason ||
|
||||
(error instanceof Error ? error.message : String(error)),
|
||||
};
|
||||
}
|
||||
}
|
||||
return { ok: false, reason: asyncErrorReason || 'clipboard-unavailable' };
|
||||
}
|
||||
|
||||
if (action === 'copy' || action === 'cut') {
|
||||
const selectedText = getSelectedText();
|
||||
const hasTokenFn = typeof getSelectionToken === 'function';
|
||||
const initialToken = hasTokenFn ? getSelectionToken() : undefined;
|
||||
if (
|
||||
action === 'cut' &&
|
||||
typeof deleteSelection === 'function' &&
|
||||
(!hasTokenFn || initialToken === null || initialToken === undefined)
|
||||
) {
|
||||
return { ok: false, action, reason: 'missing-selection-token' };
|
||||
}
|
||||
const writeRes = await writeTextInGesture(selectedText);
|
||||
if (!writeRes.ok) {
|
||||
return { ok: false, action, reason: writeRes.reason };
|
||||
}
|
||||
if (action === 'cut') {
|
||||
const currentText = getSelectedText();
|
||||
const tokenChanged =
|
||||
hasTokenFn && !Object.is(getSelectionToken(), initialToken);
|
||||
if (tokenChanged || currentText !== selectedText) {
|
||||
return {
|
||||
ok: false,
|
||||
action,
|
||||
reason: 'selection-changed-during-cut',
|
||||
};
|
||||
}
|
||||
deleteSelection?.({ token: initialToken, text: selectedText });
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
action,
|
||||
method: writeRes.method,
|
||||
text: selectedText,
|
||||
};
|
||||
}
|
||||
|
||||
if (action === 'paste') {
|
||||
if (
|
||||
isSecureContext &&
|
||||
clipboard &&
|
||||
typeof clipboard.readText === 'function'
|
||||
) {
|
||||
try {
|
||||
const text = await clipboard.readText();
|
||||
insertText?.(text);
|
||||
return { ok: true, action, method: 'async-clipboard', text };
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
action,
|
||||
reason: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
return { ok: false, action, reason: 'clipboard-read-unavailable' };
|
||||
}
|
||||
|
||||
return { ok: false, action, reason: 'unknown-action' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Suppresses native `#ime` context menus and residual text selection while
|
||||
* the canvas selection overlay owns the active selection.
|
||||
*
|
||||
* @param {HTMLTextAreaElement} imeEl
|
||||
* @param {() => boolean} isOverlayActive
|
||||
*/
|
||||
export function attachImeSelectionGuard(imeEl, isOverlayActive) {
|
||||
/** @param {Event} event */
|
||||
function preventNativeMenu(event) {
|
||||
if (isOverlayActive()) {
|
||||
event.preventDefault?.();
|
||||
}
|
||||
}
|
||||
|
||||
imeEl.addEventListener?.('contextmenu', preventNativeMenu);
|
||||
imeEl.addEventListener?.('selectstart', preventNativeMenu);
|
||||
|
||||
return {
|
||||
dispose() {
|
||||
imeEl.removeEventListener?.('contextmenu', preventNativeMenu);
|
||||
imeEl.removeEventListener?.('selectstart', preventNativeMenu);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a pointer hit-testing and drag state machine for the canvas
|
||||
* selection overlay.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {() => SelectionOverlayInput | null} options.getInput
|
||||
* @param {(handle: 'start' | 'end', x: number, y: number) => void} [options.onDragHandle]
|
||||
* @param {(action: SelectionActionId) => Promise<unknown> | unknown} [options.onAction]
|
||||
* @param {(layout: SelectionOverlayLayout | null) => void} [options.onLayoutChange]
|
||||
*/
|
||||
export function createSelectionOverlayController(options) {
|
||||
/** @type {'start' | 'end' | null} */
|
||||
let draggingHandle = null;
|
||||
/** @type {SelectionActionId | null} */
|
||||
let pressedMenuAction = null;
|
||||
/** @type {SelectionActionId | null} */
|
||||
let activeActionId = null;
|
||||
|
||||
/** @returns {SelectionOverlayLayout | null} */
|
||||
function getLayout() {
|
||||
const raw = options.getInput();
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
return computeSelectionOverlayLayout({
|
||||
...raw,
|
||||
dragging: draggingHandle !== null,
|
||||
activeHandle: draggingHandle,
|
||||
});
|
||||
}
|
||||
|
||||
function notify() {
|
||||
options.onLayoutChange?.(getLayout());
|
||||
}
|
||||
|
||||
/**
|
||||
* Hit-tests the floating menu items first, then the two teardrop handles.
|
||||
*
|
||||
* @param {number} x
|
||||
* @param {number} y
|
||||
* @returns {{ kind: 'menu', action: SelectionActionId } | { kind: 'handle', handle: 'start' | 'end' } | null}
|
||||
*/
|
||||
function hitTest(x, y) {
|
||||
const layout = getLayout();
|
||||
if (!layout) {
|
||||
return null;
|
||||
}
|
||||
if (layout.menu.visible) {
|
||||
for (const item of layout.menu.items) {
|
||||
if (pointInRect(item, x, y)) {
|
||||
return { kind: 'menu', action: item.id };
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pointInRect(layout.endHandle.hitRect, x, y)) {
|
||||
return { kind: 'handle', handle: 'end' };
|
||||
}
|
||||
if (pointInRect(layout.startHandle.hitRect, x, y)) {
|
||||
return { kind: 'handle', handle: 'start' };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Captures a menu press or teardrop handle drag on pointer down.
|
||||
* Menu actions wait until pointer up so touch events carry browser user
|
||||
* activation and users can cancel by sliding off the button.
|
||||
*
|
||||
* @param {number} x
|
||||
* @param {number} y
|
||||
*/
|
||||
function onPointerDown(x, y) {
|
||||
const hit = hitTest(x, y);
|
||||
if (!hit) {
|
||||
pressedMenuAction = null;
|
||||
activeActionId = null;
|
||||
return { handled: false, hit: null, actionPromise: null };
|
||||
}
|
||||
if (hit.kind === 'menu') {
|
||||
pressedMenuAction = hit.action;
|
||||
activeActionId = hit.action;
|
||||
notify();
|
||||
return { handled: true, hit, actionPromise: null };
|
||||
}
|
||||
draggingHandle = hit.handle;
|
||||
pressedMenuAction = null;
|
||||
activeActionId = null;
|
||||
notify();
|
||||
return { handled: true, hit, actionPromise: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} x
|
||||
* @param {number} y
|
||||
*/
|
||||
function onPointerMove(x, y) {
|
||||
if (draggingHandle) {
|
||||
options.onDragHandle?.(draggingHandle, x, y);
|
||||
notify();
|
||||
return true;
|
||||
}
|
||||
if (pressedMenuAction) {
|
||||
const hit = hitTest(x, y);
|
||||
const nextActive =
|
||||
hit && hit.kind === 'menu' && hit.action === pressedMenuAction
|
||||
? pressedMenuAction
|
||||
: null;
|
||||
if (nextActive !== activeActionId) {
|
||||
activeActionId = nextActive;
|
||||
notify();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes a handle drag or invokes a menu action on pointer up when the
|
||||
* release point remains on the pressed button. Runs synchronously inside the
|
||||
* `pointerup` user-activation stack.
|
||||
*
|
||||
* @param {number} [x]
|
||||
* @param {number} [y]
|
||||
*/
|
||||
function onPointerUp(x, y) {
|
||||
const wasDragging = draggingHandle !== null;
|
||||
const pendingAction = pressedMenuAction;
|
||||
draggingHandle = null;
|
||||
pressedMenuAction = null;
|
||||
activeActionId = null;
|
||||
|
||||
if (pendingAction) {
|
||||
const hit =
|
||||
typeof x === 'number' && typeof y === 'number' ? hitTest(x, y) : null;
|
||||
const confirmed =
|
||||
hit !== null && hit.kind === 'menu' && hit.action === pendingAction;
|
||||
notify();
|
||||
if (confirmed) {
|
||||
const actionPromise = Promise.resolve(
|
||||
options.onAction?.(pendingAction)
|
||||
);
|
||||
return {
|
||||
handled: true,
|
||||
action: pendingAction,
|
||||
cancelled: false,
|
||||
actionPromise,
|
||||
};
|
||||
}
|
||||
return {
|
||||
handled: true,
|
||||
action: null,
|
||||
cancelled: true,
|
||||
actionPromise: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (wasDragging) {
|
||||
notify();
|
||||
return {
|
||||
handled: true,
|
||||
action: null,
|
||||
cancelled: false,
|
||||
actionPromise: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
handled: false,
|
||||
action: null,
|
||||
cancelled: false,
|
||||
actionPromise: null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears active handle drag and pressed menu state on pointer cancel.
|
||||
*/
|
||||
function onPointerCancel() {
|
||||
const hadState =
|
||||
draggingHandle !== null ||
|
||||
pressedMenuAction !== null ||
|
||||
activeActionId !== null;
|
||||
draggingHandle = null;
|
||||
pressedMenuAction = null;
|
||||
activeActionId = null;
|
||||
if (hadState) {
|
||||
notify();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
return {
|
||||
getLayout,
|
||||
hitTest,
|
||||
onPointerDown,
|
||||
onPointerMove,
|
||||
onPointerUp,
|
||||
onPointerCancel,
|
||||
isDragging: () => draggingHandle !== null,
|
||||
getActiveActionId: () => activeActionId,
|
||||
getPressedMenuAction: () => pressedMenuAction,
|
||||
};
|
||||
}
|
||||
@@ -14,6 +14,8 @@
|
||||
* @typedef {Object} BuildManifest
|
||||
* @property {string} shellVersion
|
||||
* @property {string} buildHash
|
||||
* @property {string} [buildId]
|
||||
* @property {string | null} [assetBaseUrl]
|
||||
* @property {string | null} [appEntryJs]
|
||||
* @property {Record<PreviewWorkerKind, WorkerAssetSpec>} workers
|
||||
* @property {Record<string, string>} fonts
|
||||
@@ -30,7 +32,11 @@ export function freezeBuildManifest(raw) {
|
||||
if (!raw || typeof raw !== 'object') {
|
||||
throw new TypeError('Build manifest must be an object');
|
||||
}
|
||||
if (!raw.buildHash || typeof raw.buildHash !== 'string') {
|
||||
const effectiveBuildId =
|
||||
(typeof raw.buildId === 'string' && raw.buildId) ||
|
||||
(typeof raw.buildHash === 'string' && raw.buildHash) ||
|
||||
'';
|
||||
if (!effectiveBuildId) {
|
||||
throw new TypeError('Build manifest requires a non-empty buildHash');
|
||||
}
|
||||
/** @type {Record<string, Readonly<WorkerAssetSpec>>} */
|
||||
@@ -52,9 +58,15 @@ export function freezeBuildManifest(raw) {
|
||||
}
|
||||
const workers = Object.freeze(frozenWorkers);
|
||||
const fonts = Object.freeze({ ...raw.fonts });
|
||||
const assetBaseUrl =
|
||||
typeof raw.assetBaseUrl === 'string' && raw.assetBaseUrl.trim()
|
||||
? raw.assetBaseUrl.trim()
|
||||
: null;
|
||||
return Object.freeze({
|
||||
shellVersion: String(raw.shellVersion || 'mobile-v1'),
|
||||
buildHash: raw.buildHash,
|
||||
buildHash: effectiveBuildId,
|
||||
buildId: effectiveBuildId,
|
||||
assetBaseUrl,
|
||||
appEntryJs: typeof raw.appEntryJs === 'string' ? raw.appEntryJs : null,
|
||||
workers: /** @type {Record<PreviewWorkerKind, WorkerAssetSpec>} */ (
|
||||
workers
|
||||
@@ -79,20 +91,33 @@ export function readEmbeddedManifest(doc, elementId = 'affine-build-manifest') {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a pinned asset URL against the site root (`new URL('/', baseUrl)`)
|
||||
* so nested routes like `/workspace/123` never turn `/assets/...` or
|
||||
* `./assets/...` into `/workspace/assets/...` 404s.
|
||||
* Resolves a pinned asset URL against the locked asset root or site root so
|
||||
* nested routes and dual-tab shell cookie switches never cause 404 errors.
|
||||
*
|
||||
* @param {string} assetUrl
|
||||
* @param {string} baseUrl
|
||||
* @param {string} buildHash
|
||||
* @param {string} buildId
|
||||
* @param {string | null} [assetBaseUrl]
|
||||
* @returns {string}
|
||||
*/
|
||||
function pinUrl(assetUrl, baseUrl, buildHash) {
|
||||
function pinUrl(assetUrl, baseUrl, buildId, assetBaseUrl = null) {
|
||||
const siteRoot = new URL('/', baseUrl);
|
||||
const resolved = new URL(assetUrl, siteRoot);
|
||||
if (!resolved.pathname.includes(buildHash)) {
|
||||
resolved.searchParams.set('v', buildHash);
|
||||
let resolved;
|
||||
if (assetBaseUrl) {
|
||||
const normalizedRoot = assetBaseUrl.endsWith('/')
|
||||
? assetBaseUrl
|
||||
: `${assetBaseUrl}/`;
|
||||
const lockedRoot = new URL(normalizedRoot, siteRoot);
|
||||
const trimmed =
|
||||
assetUrl.startsWith('/') && !assetUrl.startsWith('//')
|
||||
? assetUrl.slice(1)
|
||||
: assetUrl;
|
||||
resolved = new URL(trimmed, lockedRoot);
|
||||
} else {
|
||||
resolved = new URL(assetUrl, siteRoot);
|
||||
}
|
||||
if (!resolved.pathname.includes(buildId)) {
|
||||
resolved.searchParams.set('v', buildId);
|
||||
}
|
||||
return resolved.toString();
|
||||
}
|
||||
@@ -125,26 +150,47 @@ export function buildWorkerBootstrapSource(hostOrigin, scriptUrl, wasmUrl) {
|
||||
* @param {BuildManifest} rawManifest
|
||||
* @param {Object} [options]
|
||||
* @param {string} [options.baseUrl]
|
||||
* @param {string | null} [options.assetBaseUrl]
|
||||
* @param {string} [options.buildId]
|
||||
* @param {(url: string, opts: WorkerOptions) => Worker} [options.createWorker]
|
||||
* @param {(blob: Blob) => string} [options.createObjectURL]
|
||||
* @param {(url: string) => void} [options.revokeObjectURL]
|
||||
* @param {typeof fetch} [options.fetchImpl]
|
||||
*/
|
||||
export function createWorkerLoader(rawManifest, options = {}) {
|
||||
const manifest = freezeBuildManifest(rawManifest);
|
||||
const manifest = freezeBuildManifest({
|
||||
...rawManifest,
|
||||
buildId: options.buildId || rawManifest.buildId || rawManifest.buildHash,
|
||||
assetBaseUrl:
|
||||
options.assetBaseUrl !== undefined
|
||||
? options.assetBaseUrl
|
||||
: rawManifest.assetBaseUrl,
|
||||
});
|
||||
const baseUrl =
|
||||
options.baseUrl ||
|
||||
(globalThis.location === undefined
|
||||
? 'https://app.affine.pro/'
|
||||
: globalThis.location.href);
|
||||
const lockedAssetBaseUrl = manifest.assetBaseUrl || null;
|
||||
const lockedBuildId = manifest.buildId || manifest.buildHash;
|
||||
const hostOrigin = new URL(baseUrl).origin;
|
||||
const createWorker =
|
||||
options.createWorker || ((url, workerOpts) => new Worker(url, workerOpts));
|
||||
const createObjectURL =
|
||||
options.createObjectURL || (blob => URL.createObjectURL(blob));
|
||||
const revokeObjectURL =
|
||||
options.revokeObjectURL ||
|
||||
(url => {
|
||||
if (typeof URL.revokeObjectURL === 'function') {
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
});
|
||||
const fetchImpl = options.fetchImpl || globalThis.fetch;
|
||||
|
||||
/** @type {Map<string, Worker>} */
|
||||
const workerCache = new Map();
|
||||
/** @type {Map<string, string>} */
|
||||
const workerBlobUrls = new Map();
|
||||
|
||||
/**
|
||||
* Resolves pinned `{ script, wasm }` asset URLs for one preview worker.
|
||||
@@ -158,8 +204,8 @@ export function createWorkerLoader(rawManifest, options = {}) {
|
||||
throw new Error(`Unknown worker kind: ${kind}`);
|
||||
}
|
||||
return {
|
||||
script: pinUrl(entry.script, baseUrl, manifest.buildHash),
|
||||
wasm: pinUrl(entry.wasm, baseUrl, manifest.buildHash),
|
||||
script: pinUrl(entry.script, baseUrl, lockedBuildId, lockedAssetBaseUrl),
|
||||
wasm: pinUrl(entry.wasm, baseUrl, lockedBuildId, lockedAssetBaseUrl),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -174,7 +220,7 @@ export function createWorkerLoader(rawManifest, options = {}) {
|
||||
if (!entry) {
|
||||
throw new Error(`Unknown font script: ${scriptName}`);
|
||||
}
|
||||
return pinUrl(entry, baseUrl, manifest.buildHash);
|
||||
return pinUrl(entry, baseUrl, lockedBuildId, lockedAssetBaseUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -195,12 +241,53 @@ export function createWorkerLoader(rawManifest, options = {}) {
|
||||
const blobUrl = createObjectURL(blob);
|
||||
const worker = createWorker(blobUrl, {
|
||||
type: 'module',
|
||||
name: `affine-${kind}-${manifest.buildHash}`,
|
||||
name: `affine-${kind}-${lockedBuildId}`,
|
||||
});
|
||||
workerCache.set(kind, worker);
|
||||
workerBlobUrls.set(kind, blobUrl);
|
||||
return worker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true when a worker of `kind` has already been spawned.
|
||||
*
|
||||
* @param {PreviewWorkerKind} kind
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function hasLoadedWorker(kind) {
|
||||
return workerCache.has(kind);
|
||||
}
|
||||
|
||||
/**
|
||||
* Terminates and removes a spawned worker of `kind`.
|
||||
*
|
||||
* @param {PreviewWorkerKind} kind
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function terminateWorker(kind) {
|
||||
const worker = workerCache.get(kind);
|
||||
if (!worker) {
|
||||
return false;
|
||||
}
|
||||
workerCache.delete(kind);
|
||||
const blobUrl = workerBlobUrls.get(kind);
|
||||
if (blobUrl) {
|
||||
workerBlobUrls.delete(kind);
|
||||
revokeObjectURL(blobUrl);
|
||||
}
|
||||
worker.terminate?.();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Terminates all spawned preview workers.
|
||||
*/
|
||||
function dispose() {
|
||||
for (const kind of workerCache.keys()) {
|
||||
terminateWorker(/** @type {PreviewWorkerKind} */ (kind));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches an on-demand TTF/OTF font binary pinned to this page's build hash.
|
||||
*
|
||||
@@ -218,9 +305,14 @@ export function createWorkerLoader(rawManifest, options = {}) {
|
||||
|
||||
return Object.freeze({
|
||||
manifest,
|
||||
buildId: lockedBuildId,
|
||||
assetBaseUrl: lockedAssetBaseUrl,
|
||||
resolveWorkerAssets,
|
||||
resolveFontUrl,
|
||||
loadWorker,
|
||||
hasLoadedWorker,
|
||||
terminateWorker,
|
||||
dispose,
|
||||
loadFont,
|
||||
});
|
||||
}
|
||||
@@ -5,6 +5,8 @@ const OPCODE_MERMAID_SVG = 2;
|
||||
const OPCODE_MATH_SVG = 3;
|
||||
const OPCODE_TYPST_SVG = 4;
|
||||
const OPCODE_PDF_PAGE = 5;
|
||||
const OPCODE_PDF_PAGE_SCALED = 6;
|
||||
const OPCODE_PDF_PAGE_COUNT = 7;
|
||||
|
||||
const KIND_OPCODES = {
|
||||
mermaid: OPCODE_MERMAID_SVG,
|
||||
@@ -151,6 +153,24 @@ function prependPageIndex(pageIndex, body) {
|
||||
return buf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepends a 4-byte little-endian `pageIndex` and 4-byte little-endian `scale`
|
||||
* float header to a byte payload.
|
||||
*
|
||||
* @param {number} pageIndex
|
||||
* @param {number} scale
|
||||
* @param {Uint8Array} body
|
||||
* @returns {Uint8Array}
|
||||
*/
|
||||
function prependPageIndexAndScale(pageIndex, scale, body) {
|
||||
const buf = new Uint8Array(8 + body.length);
|
||||
const view = new DataView(buf.buffer);
|
||||
view.setUint32(0, pageIndex >>> 0, true);
|
||||
view.setFloat32(4, scale, true);
|
||||
buf.set(body, 8);
|
||||
return buf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a dedicated preview Web Worker for one capability (`mermaid`, `math`,
|
||||
* `typst`, or `pdf`), reading its pinned `.wasm` URL from
|
||||
@@ -213,6 +233,7 @@ export function startPreviewWorker(kind) {
|
||||
|
||||
/** @type {Uint8Array} */
|
||||
let payloadBytes;
|
||||
let opcode = defaultOpcode;
|
||||
if (kind === 'mermaid') {
|
||||
const themeTag =
|
||||
msg.theme === 'light' ? 1 : msg.theme === 'dark' ? 2 : 0;
|
||||
@@ -230,12 +251,28 @@ export function startPreviewWorker(kind) {
|
||||
msg.pdfBytes instanceof Uint8Array
|
||||
? msg.pdfBytes
|
||||
: new Uint8Array(msg.pdfBytes || []);
|
||||
payloadBytes = prependPageIndex(Number(msg.pageIndex ?? 0), pdfBytes);
|
||||
if (msg.op === 'page_count') {
|
||||
opcode = OPCODE_PDF_PAGE_COUNT;
|
||||
payloadBytes = pdfBytes;
|
||||
} else if (
|
||||
typeof msg.scale === 'number' &&
|
||||
Number.isFinite(msg.scale) &&
|
||||
msg.scale > 0
|
||||
) {
|
||||
opcode = OPCODE_PDF_PAGE_SCALED;
|
||||
payloadBytes = prependPageIndexAndScale(
|
||||
Number(msg.pageIndex ?? 0),
|
||||
msg.scale,
|
||||
pdfBytes
|
||||
);
|
||||
} else {
|
||||
payloadBytes = prependPageIndex(Number(msg.pageIndex ?? 0), pdfBytes);
|
||||
}
|
||||
} else {
|
||||
payloadBytes = encoder.encode(String(msg.latex ?? msg.source ?? ''));
|
||||
}
|
||||
|
||||
const frame = invokeRaw(exports, defaultOpcode, payloadBytes);
|
||||
const frame = invokeRaw(exports, opcode, payloadBytes);
|
||||
if (frame.length === 0 || frame[0] !== 1) {
|
||||
throw new Error(decoder.decode(frame.subarray(1)) || 'worker error');
|
||||
}
|
||||
@@ -262,6 +299,14 @@ export function startPreviewWorker(kind) {
|
||||
frame.byteLength
|
||||
);
|
||||
const pageCount = view.getUint32(1, true);
|
||||
if (msg.op === 'page_count') {
|
||||
globalThis.postMessage({
|
||||
id,
|
||||
ok: true,
|
||||
result: { kind, pageCount },
|
||||
});
|
||||
return;
|
||||
}
|
||||
const widthPx = view.getUint32(5, true);
|
||||
const heightPx = view.getUint32(9, true);
|
||||
const rgba = frame.slice(13);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user