diff --git a/.github/workflows/native-playground.yml b/.github/workflows/native-playground.yml index 9e6bb1e5c7..6b5776af30 100644 --- a/.github/workflows/native-playground.yml +++ b/.github/workflows/native-playground.yml @@ -404,13 +404,15 @@ jobs: - name: Build WebAssembly bundle and run headless Chromium smoke test run: | mkdir -p artifacts ../../blocksuite/crates/playground/web/pkg - cargo build --locked --profile wasm-release-size -p playground --lib --target wasm32-unknown-unknown + WASM_RUSTFLAGS="$(printf '%s\037%s\037%s' "--remap-path-prefix=$(cd ../.. && pwd)=/src" "--remap-path-prefix=${CARGO_HOME:-$HOME/.cargo}=/cargo" "-Ctarget-feature=+simd128")" + CARGO_ENCODED_RUSTFLAGS="$WASM_RUSTFLAGS" cargo build --locked --profile wasm-release-size -p playground --lib --target wasm32-unknown-unknown wasm-bindgen --target web --out-dir ../../blocksuite/crates/playground/web/pkg target/wasm32-unknown-unknown/wasm-release-size/playground.wasm wasm-opt -Oz --strip-debug --strip-producers \ --enable-bulk-memory \ --enable-nontrapping-float-to-int \ --enable-sign-ext \ --enable-mutable-globals \ + --enable-simd \ ../../blocksuite/crates/playground/web/pkg/playground_bg.wasm \ -o ../../blocksuite/crates/playground/web/pkg/playground_bg.opt.wasm mv ../../blocksuite/crates/playground/web/pkg/playground_bg.opt.wasm ../../blocksuite/crates/playground/web/pkg/playground_bg.wasm diff --git a/.github/workflows/np-mobile.yml b/.github/workflows/np-mobile.yml index 345cdf7323..9ff2f527ce 100644 --- a/.github/workflows/np-mobile.yml +++ b/.github/workflows/np-mobile.yml @@ -177,25 +177,27 @@ jobs: mkdir -p /tmp/preview-wasm/pkg REPO_ROOT="$(cd ../.. && pwd)" CARGO_HOME_DIR="${CARGO_HOME:-$HOME/.cargo}" - WORKER_RUSTFLAGS="$(printf '%s\037%s' "--remap-path-prefix=${REPO_ROOT}=/src" "--remap-path-prefix=${CARGO_HOME_DIR}=/cargo")" + WASM_RUSTFLAGS="$(printf '%s\037%s\037%s' "--remap-path-prefix=${REPO_ROOT}=/src" "--remap-path-prefix=${CARGO_HOME_DIR}=/cargo" "-Ctarget-feature=+simd128")" for kind in mermaid math typst pdf; do - CARGO_ENCODED_RUSTFLAGS="$WORKER_RUSTFLAGS" cargo rustc --locked --target wasm32-unknown-unknown --profile wasm-worker-size -p blocksuite-preview --lib --crate-type cdylib --no-default-features --features "${kind},wasm-worker" + CARGO_ENCODED_RUSTFLAGS="$WASM_RUSTFLAGS" cargo rustc --locked --target wasm32-unknown-unknown --profile wasm-worker-size -p blocksuite-preview --lib --crate-type cdylib --no-default-features --features "${kind},wasm-worker" wasm-opt -Oz --strip-debug --strip-producers \ --enable-bulk-memory \ --enable-nontrapping-float-to-int \ --enable-sign-ext \ --enable-mutable-globals \ + --enable-simd \ "target/wasm32-unknown-unknown/wasm-worker-size/blocksuite_preview.wasm" \ -o "/tmp/preview-wasm/${kind}.wasm" test -s "/tmp/preview-wasm/${kind}.wasm" done - cargo build --locked --profile wasm-release-size -p playground --lib --target wasm32-unknown-unknown + CARGO_ENCODED_RUSTFLAGS="$WASM_RUSTFLAGS" cargo build --locked --profile wasm-release-size -p playground --lib --target wasm32-unknown-unknown wasm-bindgen --target web --out-dir /tmp/preview-wasm/pkg target/wasm32-unknown-unknown/wasm-release-size/playground.wasm wasm-opt -Oz --strip-debug --strip-producers \ --enable-bulk-memory \ --enable-nontrapping-float-to-int \ --enable-sign-ext \ --enable-mutable-globals \ + --enable-simd \ /tmp/preview-wasm/pkg/playground_bg.wasm \ -o /tmp/preview-wasm/pkg/playground_bg.opt.wasm mv /tmp/preview-wasm/pkg/playground_bg.opt.wasm /tmp/preview-wasm/pkg/playground_bg.wasm diff --git a/blocksuite/crates/editor/src/database/render_kanban_card.rs b/blocksuite/crates/editor/src/database/render_kanban_card.rs index c03121db38..d44f488b0d 100644 --- a/blocksuite/crates/editor/src/database/render_kanban_card.rs +++ b/blocksuite/crates/editor/src/database/render_kanban_card.rs @@ -580,22 +580,7 @@ pub(super) fn render_kanban_card( .map_or((ratio, label), |p| format_database_progress(p.value)); let bar_w = (inner_w - 40.0).max(24.0); let bar_y = py + 5.0; - prims.push(DatabasePrim::Quad { - rect: FlowRect::new(inner_x, bar_y, bar_w, 8.0), - fill: Some(ctx.palette.background_secondary), - border: Some(ctx.palette.border), - radius: 4.0, - dashed: false, - }); - if ratio > 0.0 { - prims.push(DatabasePrim::Quad { - rect: FlowRect::new(inner_x, bar_y, (bar_w * ratio).max(4.0), 8.0), - fill: Some(ctx.palette.brand), - border: None, - radius: 4.0, - dashed: false, - }); - } + ctx.push_progress_bar(prims, inner_x, bar_y, bar_w, ratio); prims.push(ctx.single_line_clipped( &label, InlineStyle::new( diff --git a/blocksuite/crates/editor/src/database/render_table.rs b/blocksuite/crates/editor/src/database/render_table.rs index 0f4795207e..5adb020227 100644 --- a/blocksuite/crates/editor/src/database/render_table.rs +++ b/blocksuite/crates/editor/src/database/render_table.rs @@ -575,22 +575,7 @@ fn render_table_row( let (ratio, label) = format_database_progress(raw); let bar_w = (inner_w - 42.0).max(24.0); let bar_y = cell_rect.y + 13.0; - prims.push(DatabasePrim::Quad { - rect: FlowRect::new(inner_x, bar_y, bar_w, 8.0), - fill: Some(ctx.palette.background_secondary), - border: Some(ctx.palette.border), - radius: 4.0, - dashed: false, - }); - if ratio > 0.0 { - prims.push(DatabasePrim::Quad { - rect: FlowRect::new(inner_x, bar_y, (bar_w * ratio).max(4.0), 8.0), - fill: Some(ctx.palette.brand), - border: None, - radius: 4.0, - dashed: false, - }); - } + ctx.push_progress_bar(prims, inner_x, bar_y, bar_w, ratio); prims.push(ctx.single_line_clipped( &label, InlineStyle::new( diff --git a/blocksuite/crates/editor/src/database/render_types.rs b/blocksuite/crates/editor/src/database/render_types.rs index 2b82d3eafa..3c4a9e2b26 100644 --- a/blocksuite/crates/editor/src/database/render_types.rs +++ b/blocksuite/crates/editor/src/database/render_types.rs @@ -109,6 +109,33 @@ impl DbRenderCtx<'_> { } } + /// Pushes the 8 px progress track, and the brand fill when `ratio` is above zero. + pub(super) fn push_progress_bar( + &self, + prims: &mut Vec, + x: f32, + y: f32, + width: f32, + ratio: f32, + ) { + prims.push(DatabasePrim::Quad { + rect: FlowRect::new(x, y, width, 8.0), + fill: Some(self.palette.background_secondary), + border: Some(self.palette.border), + radius: 4.0, + dashed: false, + }); + if ratio > 0.0 { + prims.push(DatabasePrim::Quad { + rect: FlowRect::new(x, y, (width * ratio).max(4.0), 8.0), + fill: Some(self.palette.brand), + border: None, + radius: 4.0, + dashed: false, + }); + } + } + pub(super) fn inline( &self, text: &str, diff --git a/blocksuite/crates/preview/BENCHMARK.md b/blocksuite/crates/preview/BENCHMARK.md index 75f6ee3168..61d85ed606 100644 --- a/blocksuite/crates/preview/BENCHMARK.md +++ b/blocksuite/crates/preview/BENCHMARK.md @@ -58,16 +58,23 @@ The nine-family mean is 1,602 KiB (1.56 MiB) and the peak is 4,078 KiB (3.98 MiB Each preview capability builds independently under the unified `packages/frontend/Cargo.toml` workspace for `wasm32-unknown-unknown` with `--no-default-features --features ,wasm-worker` so the main Web application pays zero upfront preview bundle cost. -Production web packaging builds all four workers as standalone `cdylib` modules with `cargo rustc --profile wasm-worker-size --lib --crate-type cdylib` (`opt-level = "z"`, `lto = "fat"`, `codegen-units = 1`, `strip = "debuginfo"`), remaps workspace and Cargo paths via `CARGO_ENCODED_RUSTFLAGS`, and post-processes every `.wasm` with Binaryen `wasm-opt -Oz --strip-debug --strip-producers`. `mermaid` and `typst` workers omit `svg-text` (the Web host renders their SVG directly), and `merman` keeps all 35 diagram families with Dagre, ELK (`layout-elk`), and Cytoscape (`layout-cytoscape`) layout engines enabled: +Production web packaging builds each of the four workers as a standalone `cdylib` module with `cargo rustc --profile wasm-worker-size --lib --crate-type cdylib` (`opt-level = "z"`, `lto = "fat"`, `codegen-units = 1`, `strip = "debuginfo"`). +`CARGO_ENCODED_RUSTFLAGS` holds three flags: `--remap-path-prefix==/src`, `--remap-path-prefix==/cargo`, and `-Ctarget-feature=+simd128`. +Binaryen then processes each `.wasm` file with `wasm-opt -Oz --strip-debug --strip-producers --enable-bulk-memory --enable-nontrapping-float-to-int --enable-sign-ext --enable-mutable-globals --enable-simd`. +`.github/workflows/np-mobile.yml` runs these commands. + +The build does not enable `relaxed-simd`, because Safari 17 and Safari 18 do not support it. +The `mermaid` and `typst` workers omit `svg-text`, because the Web host renders their SVG directly. +`merman` keeps all 35 diagram families and the Dagre, ELK (`layout-elk`), and Cytoscape (`layout-cytoscape`) layout engines. | Worker Feature | Profile | Stripped + `wasm-opt -Oz` Raw Size | `gzip -9` Size | | --- | --- | ---: | ---: | -| `math,wasm-worker` (RaTeX + `svg-raster` outlines) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 3,159,126 B (3.01 MiB) | 1,214,695 B (1.16 MiB) | -| `pdf,wasm-worker` (`hayro 0.9.0`, zero `resvg`) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 4,201,826 B (4.01 MiB) | 1,735,013 B (1.65 MiB) | -| `mermaid,wasm-worker` (`merman 0.11.0`, zero `svg-text`, with ELK) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 10,860,584 B (10.36 MiB) | 4,202,097 B (4.01 MiB) | -| `typst,wasm-worker` (`typst 0.15.1`, zero `svg-text`) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 19,515,404 B (18.61 MiB) | 8,187,963 B (7.81 MiB) | +| `math,wasm-worker` (RaTeX + `svg-raster` outlines) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 3,073,023 B (2.93 MiB) | 1,198,027 B (1.14 MiB) | +| `pdf,wasm-worker` (`hayro 0.9.0`, zero `resvg`) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 3,175,888 B (3.03 MiB) | 1,521,787 B (1.45 MiB) | +| `mermaid,wasm-worker` (`merman 0.11.0`, zero `svg-text`, with ELK) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 10,698,577 B (10.20 MiB) | 4,146,907 B (3.95 MiB) | +| `typst,wasm-worker` (`typst 0.15.1`, zero `svg-text`) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 19,354,592 B (18.46 MiB) | 8,141,108 B (7.76 MiB) | -Measured on Linux x86-64 with Rust `1.98.1` and Binaryen `version_123` (`wasm-opt -Oz --strip-debug --strip-producers --enable-bulk-memory --enable-nontrapping-float-to-int --enable-sign-ext --enable-mutable-globals`). +Measured on Linux x86-64 with Rust `1.98.1` and Binaryen `version_123`, with the flags above. ## 4. Native Build and Toolchain Audit diff --git a/packages/frontend/Cargo.lock b/packages/frontend/Cargo.lock index 98f576bd7d..311d8344df 100644 --- a/packages/frontend/Cargo.lock +++ b/packages/frontend/Cargo.lock @@ -6027,7 +6027,6 @@ checksum = "3c8480887e8803986d96a7173729565520d4bbb721ad6b7ad6941a22897207aa" dependencies = [ "serde", "slotmap", - "smallvec", ] [[package]] diff --git a/packages/frontend/Cargo.toml b/packages/frontend/Cargo.toml index 66885c2a74..981a6ad963 100644 --- a/packages/frontend/Cargo.toml +++ b/packages/frontend/Cargo.toml @@ -185,7 +185,7 @@ spin = { version = "0.10", default-features = false, features = ["mutex", "spin_ sqlx = { version = "0.8.6", default-features = false, features = ["sqlite", "migrate", "runtime-tokio", "chrono"] } strum = { version = "0.28", features = ["derive"] } swash = "0.2.6" -taffy = { version = "=0.15.0", default-features = false, features = ["std", "taffy_tree", "flexbox", "grid", "block_layout", "float_layout", "content_size"] } +taffy = { version = "=0.15.0", default-features = false, features = ["std", "taffy_tree", "flexbox", "block_layout", "float_layout", "content_size"] } thiserror = "2.0.12" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ttf-parser = "0.25" diff --git a/packages/frontend/hosts/web/scripts/chromium-harness.mjs b/packages/frontend/hosts/web/scripts/chromium-harness.mjs new file mode 100644 index 0000000000..a820e2c6b2 --- /dev/null +++ b/packages/frontend/hosts/web/scripts/chromium-harness.mjs @@ -0,0 +1,446 @@ +// @ts-check + +/** + * Lifecycle owner for the real-browser verification scripts. + * + * One harness owns one temporary work directory and each process group that + * the script starts. The Chromium profile is in the work directory. Chromium + * also uses the work directory as its temporary directory, so the harness + * removes the files that Chromium leaves there. + * + * Each process starts detached, as the leader of its own process group, so + * one signal reaches the process and all its descendants. The harness does + * not own a server behind a URL that the caller passes in, and never signals + * that server. + * + * A normal end, a failed assertion, `SIGINT`, and `SIGTERM` all go through + * `close()`. `close()` waits a limited time for each process group, and + * removes the work directory only after each process group is gone. A forced + * `process.exit()` cannot wait, so the `exit` handler kills each process group + * and then removes the work directory. + * + * When the harness cannot signal a process group, or the group stays alive, + * the work directory stays and its path goes to stderr. + * + * Uses a preinstalled Chromium and never runs `playwright install`. + */ + +import { execFileSync, spawn } from 'node:child_process'; +import { + closeSync, + existsSync, + mkdirSync, + mkdtempSync, + openSync, + readSync, + rmSync, +} from 'node:fs'; +import { constants, tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; + +const DEFAULT_LIMITS = { + /** How long a process group has to end after `SIGTERM`. */ + termGraceMs: 2000, + /** How long a process group has to be gone after `SIGKILL`. */ + groupGoneTimeoutMs: 2000, + /** How long a server has to answer its health check. */ + serverHealthTimeoutMs: 20000, +}; +const GROUP_PROBE_INTERVAL_MS = 20; +const SERVER_HEALTH_INTERVAL_MS = 100; +const DEVTOOLS_TIMEOUT_MS = 15000; + +const CHROMIUM_ARGS = [ + '--headless=new', + '--no-sandbox', + '--enable-unsafe-swiftshader', + '--disable-dev-shm-usage', + '--disable-background-networking', + '--no-first-run', + '--no-default-browser-check', + '--password-store=basic', + '--use-mock-keychain', + '--disable-sync', + '--disable-extensions', + '--disable-component-update', + '--disable-dbus', + '--metrics-recording-only', + '--remote-debugging-port=0', +]; + +/** + * @typedef {object} OwnedGroup + * @property {string} label + * @property {number} pgid + * @property {import('node:child_process').ChildProcess} child + * @property {Promise} exited Resolves when Node has reaped the direct child. + * @property {boolean} gone + */ + +/** + * Sends `signal` to a process group and reports the answer of the kernel. + * + * @param {number} pgid + * @param {NodeJS.Signals | 0} signal + * @returns {'alive' | 'gone' | 'denied'} + */ +function signalGroup(pgid, signal) { + try { + process.kill(-pgid, signal); + return 'alive'; + } catch (err) { + const code = /** @type {NodeJS.ErrnoException} */ (err).code; + if (code === 'ESRCH') { + return 'gone'; + } + if (code === 'EPERM') { + return 'denied'; + } + throw err; + } +} + +/** @param {string} bin */ +function isShellScriptWrapper(bin) { + try { + const fd = openSync(bin, 'r'); + try { + const buf = Buffer.alloc(2); + return readSync(fd, buf, 0, 2, 0) === 2 && buf.toString() === '#!'; + } finally { + closeSync(fd); + } + } catch { + return false; + } +} + +/** + * Uses the path from `CHROME_PATH` or `CHROME_BIN` as given. Without one, it + * prefers a real browser binary. A launcher script (a snap or a distribution + * wrapper) is used only when no binary is found. + */ +function findChromiumBinary() { + const explicit = process.env.CHROME_PATH || process.env.CHROME_BIN; + if (explicit) { + if (!existsSync(explicit)) { + throw new Error( + `The browser path from CHROME_PATH or CHROME_BIN does not exist: ${explicit}` + ); + } + return explicit; + } + const candidates = [ + ...(process.platform === 'darwin' + ? [ + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + '/Applications/Chromium.app/Contents/MacOS/Chromium', + ] + : []), + '/usr/bin/google-chrome-stable', + '/usr/bin/google-chrome', + '/usr/bin/chromium', + '/usr/bin/chromium-browser', + ]; + let wrapperFallback = null; + for (const bin of candidates) { + if (!existsSync(bin)) { + continue; + } + if (isShellScriptWrapper(bin)) { + wrapperFallback ??= 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 (wrapperFallback) { + return wrapperFallback; + } + throw new Error('No preinstalled Chromium binary found on this machine'); +} + +/** + * @param {{ tmpPrefix: string, limits?: Partial }} options + * `tmpPrefix` names the work directory under the system temporary directory. + * `limits` replaces time limits. Only the lifecycle tests pass it. + */ +export function createChromiumHarness({ tmpPrefix, limits: limitOverrides }) { + const limits = { ...DEFAULT_LIMITS, ...limitOverrides }; + const workTmp = mkdtempSync(join(tmpdir(), tmpPrefix)); + const profileDir = join(workTmp, 'chrome-profile'); + mkdirSync(profileDir); + + /** @type {OwnedGroup[]} */ + const groups = []; + /** `close()` aborts this controller. Then the teardown is in progress. */ + const teardown = new AbortController(); + /** @type {Promise | null} */ + let closing = null; + + /** + * Removes the work directory, or keeps it and prints why. + * + * @param {string[]} problems + */ + const releaseWorkTmp = problems => { + if (problems.length === 0) { + try { + rmSync(workTmp, { + recursive: true, + force: true, + maxRetries: 5, + retryDelay: 100, + }); + return; + } catch (err) { + problems = [`removal failed: ${String(err)}`]; + } + } + console.error(`[chromium-harness] kept ${workTmp}: ${problems.join('; ')}`); + }; + + /** + * @param {OwnedGroup} group + * @param {boolean} denied + */ + const describeSurvivor = (group, denied) => + `${group.label} process group ${group.pgid} ${ + denied ? 'cannot be signalled (EPERM)' : 'is still alive' + }`; + + /** + * Stops one process group and waits until it is gone. + * + * @param {OwnedGroup} group + * @returns {Promise} The reason the group survives, or `null`. + */ + const reapGroup = async group => { + if (group.gone) { + return null; + } + let answer = signalGroup(group.pgid, 'SIGTERM'); + if (answer === 'alive') { + /** @type {NodeJS.Timeout | undefined} */ + let grace; + await Promise.race([ + group.exited, + new Promise(resolve => { + grace = setTimeout(resolve, limits.termGraceMs); + }), + ]); + clearTimeout(grace); + } + if (!group.gone && answer !== 'gone') { + // Kill the members that ignore `SIGTERM` or outlive the direct child. + // Then probe. A zombie still answers signal 0. On macOS, a group that + // holds only zombies answers `EPERM` until the system reaps them. Thus + // only `ESRCH` means that every member is reaped. + answer = signalGroup(group.pgid, 'SIGKILL'); + const deadline = Date.now() + limits.groupGoneTimeoutMs; + while (answer !== 'gone' && Date.now() < deadline) { + await delay(GROUP_PROBE_INTERVAL_MS); + answer = signalGroup(group.pgid, 0); + } + } + if (answer === 'gone') { + group.gone = true; + } + if (group.gone) { + return null; + } + // Let the script end although this child cannot be reaped. + group.child.unref(); + group.child.stdout?.destroy(); + group.child.stderr?.destroy(); + return describeSurvivor(group, answer === 'denied'); + }; + + const close = () => { + teardown.abort(); + closing ??= (async () => { + const survivors = await Promise.all(groups.map(reapGroup)); + process.off('exit', onExit); + process.off('SIGINT', onSignal); + process.off('SIGTERM', onSignal); + releaseWorkTmp(survivors.filter(reason => reason !== null)); + })(); + return closing; + }; + + // The event loop has stopped: no child can be awaited, and a zombie still + // answers signal 0. Kill each group without a probe. + const onExit = () => { + const problems = []; + for (const group of groups) { + if (!group.gone && signalGroup(group.pgid, 'SIGKILL') === 'denied') { + problems.push(describeSurvivor(group, true)); + } + } + releaseWorkTmp(problems); + }; + + /** @param {NodeJS.Signals} signal */ + const onSignal = signal => { + void close().then(() => process.exit(128 + constants.signals[signal])); + }; + + process.on('exit', onExit); + process.on('SIGINT', onSignal); + process.on('SIGTERM', onSignal); + + /** @param {string} label */ + const refuseDuringTeardown = label => { + if (teardown.signal.aborted) { + throw new Error(`Refused ${label}: teardown is in progress`); + } + }; + + /** + * Starts a detached process and registers its process group. + * + * @param {string} label + * @param {string} bin + * @param {string[]} args + * @param {import('node:child_process').SpawnOptions} options + */ + const spawnOwned = (label, bin, args, options) => { + refuseDuringTeardown(`start of ${label}`); + const child = spawn(bin, args, { ...options, detached: true }); + const pgid = child.pid; + /** @type {Promise} */ + const exited = new Promise(resolve => { + child.once('exit', () => resolve()); + child.once('error', () => resolve()); + }); + if (pgid === undefined) { + throw new Error(`Failed to start ${label}: ${bin}`); + } + const group = { label, pgid, child, exited, gone: false }; + // The group can be empty when its leader exits. Record that now. Later, + // the system can give the same ID to a process group of a different owner. + child.once('exit', () => { + group.gone = signalGroup(pgid, 0) === 'gone'; + }); + groups.push(group); + return child; + }; + + /** + * Starts a server and waits until `/healthz` answers. + * + * @param {{ bin: string, args: string[], baseUrl: string }} options + */ + const startServer = async ({ bin, args, baseUrl }) => { + const server = spawnOwned('server', bin, args, { + stdio: ['ignore', 'pipe', 'pipe'], + }); + let logs = ''; + for (const stream of [server.stdout, server.stderr]) { + stream?.on('data', chunk => { + logs += String(chunk); + }); + } + const deadline = Date.now() + limits.serverHealthTimeoutMs; + let healthy = false; + while ( + !healthy && + !teardown.signal.aborted && + server.exitCode === null && + server.signalCode === null && + Date.now() < deadline + ) { + try { + // The time limit and the teardown each stop a request in flight. + const res = await fetch(`${baseUrl}/healthz`, { + signal: AbortSignal.any([ + teardown.signal, + AbortSignal.timeout(Math.max(1, deadline - Date.now())), + ]), + }); + healthy = res.ok && Date.now() <= deadline; + } catch { + // Server still booting, or the request stopped. + } + if (!healthy) { + await delay(SERVER_HEALTH_INTERVAL_MS); + } + } + // A signal can start the teardown while the health request is in flight. + refuseDuringTeardown(`use of the server at ${baseUrl}`); + if (!healthy) { + throw new Error( + `Server at ${baseUrl} did not become healthy\nServer logs:\n${logs}` + ); + } + }; + + /** + * Starts headless Chromium on the harness profile. + * + * @returns {Promise} The DevTools HTTP port. + */ + const launchChromium = async () => { + const chrome = spawnOwned( + 'Chromium', + findChromiumBinary(), + [...CHROMIUM_ARGS, `--user-data-dir=${profileDir}`, 'about:blank'], + { + stdio: ['ignore', 'ignore', 'pipe'], + env: { + ...process.env, + TMPDIR: workTmp, + // Chromium on macOS reads this name and not `TMPDIR`. + MAC_CHROMIUM_TMPDIR: workTmp, + DBUS_SESSION_BUS_ADDRESS: 'disabled:', + DBUS_SYSTEM_BUS_ADDRESS: 'disabled:', + }, + } + ); + const stderr = /** @type {import('node:stream').Readable} */ ( + chrome.stderr + ); + /** @type {string} */ + const browserWsUrl = await new Promise((resolveWs, rejectWs) => { + let stderrBuf = ''; + const timer = setTimeout( + () => rejectWs(new Error(`Chromium DevTools timeout: ${stderrBuf}`)), + DEVTOOLS_TIMEOUT_MS + ); + /** @param {unknown} chunk */ + const onData = chunk => { + stderrBuf += String(chunk); + const m = stderrBuf.match(/DevTools listening on (ws:\/\/\S+)/); + if (m) { + clearTimeout(timer); + stderr.off('data', onData); + stderr.resume(); + resolveWs(m[1]); + } + }; + stderr.on('data', onData); + chrome.once('exit', code => { + clearTimeout(timer); + rejectWs(new Error(`Chromium exited early (${code}): ${stderrBuf}`)); + }); + }); + refuseDuringTeardown('use of Chromium'); + return new URL(browserWsUrl).port; + }; + + return { workTmp, profileDir, startServer, launchChromium, close }; +} diff --git a/packages/frontend/hosts/web/scripts/stage-canary-dual-shell.mjs b/packages/frontend/hosts/web/scripts/stage-canary-dual-shell.mjs index f616f33851..e09d89d184 100644 --- a/packages/frontend/hosts/web/scripts/stage-canary-dual-shell.mjs +++ b/packages/frontend/hosts/web/scripts/stage-canary-dual-shell.mjs @@ -33,7 +33,7 @@ import { fileURLToPath } from 'node:url'; const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); const FRONTEND_ROOT = resolve(WEB_ROOT, '../..'); -const REPO_ROOT = resolve(FRONTEND_ROOT, '..'); +const REPO_ROOT = resolve(FRONTEND_ROOT, '../..'); const WORKER_KINDS = ['mermaid', 'math', 'typst', 'pdf']; const MIN_REAL_WASM_BYTES = 10 * 1024; const PREVIEW_WORKER_REQUIRED_EXPORTS = [ diff --git a/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-browser.mjs b/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-browser.mjs index 34f8e66972..6c9e04f6e4 100644 --- a/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-browser.mjs +++ b/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-browser.mjs @@ -8,28 +8,22 @@ * IndexedDB v3 CRDT persistence across WebGPU crash fallback (`native` <-> `legacy`). * * Uses the prebuilt `/tmp/preview-wasm` bundle (`playground_bg.wasm` + 4 preview - * `.wasm` workers) and preinstalled Chromium (never runs `playwright install`), - * always cleaning up child processes by exact PID inside `finally`. + * `.wasm` workers). `chromium-harness.mjs` owns the Chromium process group and + * the temporary work directory. */ import assert from 'node:assert/strict'; -import { execFileSync, spawn } from 'node:child_process'; import { - closeSync, existsSync, mkdirSync, - mkdtempSync, - openSync, readFileSync, - readSync, - rmSync, statSync, writeFileSync, } from 'node:fs'; import { createServer } from 'node:http'; -import { tmpdir } from 'node:os'; import { extname, join, normalize, resolve } from 'node:path'; +import { createChromiumHarness } from './chromium-harness.mjs'; import { stageCanaryDualShell } from './stage-canary-dual-shell.mjs'; import { verifyZeroThirdPartyJs } from './verify-zero-third-party-js.mjs'; @@ -42,69 +36,6 @@ const MIME_TYPES = { '.ttf': 'font/ttf', }; -function isShellScriptWrapper(bin) { - try { - const fd = openSync(bin, 'r'); - try { - const buf = Buffer.alloc(64); - const n = readSync(fd, buf, 0, buf.length, 0); - return n >= 2 && buf[0] === 0x23 && buf[1] === 0x21; - } 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 wrapperFallback = null; - for (const bin of candidates) { - if (!bin || !existsSync(bin)) { - continue; - } - if (isShellScriptWrapper(bin)) { - wrapperFallback ??= 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(s => s.trim()) - .find(Boolean); - if (found) { - return found; - } - } - if (wrapperFallback) { - return wrapperFallback; - } - throw new Error('No preinstalled Chromium binary found on this machine'); -} - -function chromeEnv() { - return { - ...process.env, - DBUS_SESSION_BUS_ADDRESS: 'disabled:', - DBUS_SYSTEM_BUS_ADDRESS: 'disabled:', - }; -} - function parseShellCookie(cookieHeader) { const raw = String(cookieHeader || ''); for (const part of raw.split(';')) { @@ -120,12 +51,10 @@ function parseShellCookie(cookieHeader) { } const wasmDirArg = process.argv[2] || '/tmp/preview-wasm'; -const tmpBase = mkdtempSync(join(tmpdir(), 'affine-dual-ci-')); -const legacyDistDir = join(tmpBase, 'legacy-mobile-dist'); -const stagedRoot = join(tmpBase, 'static-root'); -const profileDir = join(tmpBase, 'chrome-profile'); +const harness = createChromiumHarness({ tmpPrefix: 'affine-dual-ci-' }); +const legacyDistDir = join(harness.workTmp, 'legacy-mobile-dist'); +const stagedRoot = join(harness.workTmp, 'static-root'); mkdirSync(join(legacyDistDir, 'js'), { recursive: true }); -mkdirSync(profileDir, { recursive: true }); // Build an `@affine/mobile`-shaped dist directory (`assets-manifest.json` + `index.html` + `js/mobile-legacy.js`) // that opens same-origin `local:workspace:` IndexedDB v3 directly without Web Locks and verifies/appends CRDT updates. @@ -366,31 +295,6 @@ const addr = server.address(); const port = typeof addr === 'object' && addr ? addr.port : 0; const baseUrl = `http://127.0.0.1:${port}`; -const chromeBin = findChromiumBinary(); -const chromeProc = spawn( - chromeBin, - [ - '--headless=new', - '--no-sandbox', - '--enable-unsafe-swiftshader', - '--disable-dev-shm-usage', - '--disable-background-networking', - '--no-first-run', - '--no-default-browser-check', - '--password-store=basic', - '--use-mock-keychain', - '--disable-sync', - '--disable-extensions', - '--disable-component-update', - '--disable-dbus', - '--metrics-recording-only', - '--remote-debugging-port=0', - `--user-data-dir=${profileDir}`, - 'about:blank', - ], - { stdio: ['ignore', 'ignore', 'pipe'], env: chromeEnv() } -); - /** @type {WebSocket[]} */ const openSockets = []; @@ -504,27 +408,7 @@ async function waitFor(evalJs, expr, timeoutMs = 15000) { } try { - const browserWs = 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(browserWs).port; + const debugPort = await harness.launchChromium(); const listTargets = async () => (await fetch(`http://127.0.0.1:${debugPort}/json/list`)).json(); const initialTargets = await listTargets(); @@ -867,39 +751,5 @@ try { } } server.close(); - if (chromeProc.exitCode === null && chromeProc.signalCode === null) { - await new Promise(resolve => { - const killTimer = setTimeout(() => { - try { - chromeProc.kill('SIGKILL'); - } catch { - // ignore - } - resolve(); - }, 2500); - chromeProc.once('exit', () => { - clearTimeout(killTimer); - resolve(); - }); - try { - chromeProc.kill('SIGTERM'); - } catch { - clearTimeout(killTimer); - resolve(); - } - }); - } - try { - rmSync(tmpBase, { - recursive: true, - force: true, - maxRetries: 5, - retryDelay: 100, - }); - } catch (cleanupErr) { - console.warn( - 'Warning: failed to remove temporary browser profile dir:', - cleanupErr - ); - } + await harness.close(); } diff --git a/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-e2e.mjs b/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-e2e.mjs index fed12a055f..0bafd21ee1 100644 --- a/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-e2e.mjs +++ b/packages/frontend/hosts/web/scripts/verify-canary-dual-shell-e2e.mjs @@ -24,31 +24,22 @@ * `flushPendingBeforeRedirect` into same-origin IndexedDB, writes fallback marker, * navigates to `?shell=legacy`, and confirms `mobile-legacy` reads back the exact edit. * - * Never runs `playwright install`. Kills all spawned child processes by exact PID in `finally`. + * `chromium-harness.mjs` owns the `affine-server` and Chromium process groups and the + * temporary work directory. A server behind `--base-url` is not owned. */ import assert from 'node:assert/strict'; -import { execFileSync, spawn } from 'node:child_process'; -import { - closeSync, - existsSync, - mkdirSync, - mkdtempSync, - openSync, - readSync, - rmSync, - writeFileSync, -} from 'node:fs'; +import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; import { createServer } from 'node:net'; -import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; +import { createChromiumHarness } from './chromium-harness.mjs'; import { stageCanaryDualShell } from './stage-canary-dual-shell.mjs'; import { verifyZeroThirdPartyJs } from './verify-zero-third-party-js.mjs'; const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); -const REPO_ROOT = resolve(WEB_ROOT, '../../..'); +const REPO_ROOT = resolve(WEB_ROOT, '../../../..'); const MOBILE_UA = 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36'; const CRAWLER_UA = 'Twitterbot/1.0'; @@ -83,73 +74,6 @@ function parseCliArgs(argv) { return args; } -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 chromeEnv() { - const env = { ...process.env }; - if (!/^(unix|tcp):/.test(env.DBUS_SESSION_BUS_ADDRESS || '')) { - env.DBUS_SESSION_BUS_ADDRESS = 'unix:path=/nonexistent/affine-no-dbus'; - } - return env; -} - async function allocateFreePort() { return new Promise((resolvePort, rejectPort) => { const srv = createServer(); @@ -166,22 +90,6 @@ async function allocateFreePort() { }); } -async function waitForHealthz(baseUrl, timeoutMs = 20000) { - const deadline = Date.now() + timeoutMs; - while (Date.now() < deadline) { - try { - const res = await fetch(`${baseUrl}/healthz`); - if (res.ok) { - return; - } - } catch { - // Server still booting. - } - await new Promise(r => setTimeout(r, 100)); - } - throw new Error(`Timed out waiting for ${baseUrl}/healthz`); -} - function resolveServerBin(explicitBin) { const candidates = [ explicitBin, @@ -361,13 +269,11 @@ if (outDir) { mkdirSync(outDir, { recursive: true }); } -const workTmp = mkdtempSync(join(tmpdir(), 'affine-canary-dual-shell-e2e-')); -const staticRoot = join(workTmp, 'static-root'); -const chromeProfileDir = join(workTmp, 'chrome-profile'); -mkdirSync(chromeProfileDir, { recursive: true }); +const harness = createChromiumHarness({ + tmpPrefix: 'affine-canary-dual-shell-e2e-', +}); +const staticRoot = join(harness.workTmp, 'static-root'); -let serverProc = null; -let chromeProc = null; /** @type {Array<{ close: () => void }>} */ const openTabs = []; @@ -415,10 +321,9 @@ try { } const port = await allocateFreePort(); baseUrl = `http://127.0.0.1:${port}`; - let serverLogs = ''; - serverProc = spawn( - serverBin, - [ + await harness.startServer({ + bin: serverBin, + args: [ '--role', 'front', '--deployment-mode', @@ -436,69 +341,12 @@ try { '--database-url', databaseUrl, ], - { stdio: ['ignore', 'pipe', 'pipe'], env: process.env } - ); - serverProc.stdout?.on('data', chunk => { - serverLogs += String(chunk); + baseUrl, }); - serverProc.stderr?.on('data', chunk => { - serverLogs += String(chunk); - }); - try { - await waitForHealthz(baseUrl, 20000); - } catch (err) { - throw new Error( - `${err instanceof Error ? err.message : String(err)}\nServer logs:\n${serverLogs}` - ); - } } // 3. Launch real Headless Chromium (existing binary, never playwright install). - const chromeBin = findChromiumBinary(); - chromeProc = spawn( - chromeBin, - [ - '--headless=new', - '--no-sandbox', - '--enable-unsafe-swiftshader', - '--disable-dev-shm-usage', - '--disable-background-networking', - '--no-first-run', - '--no-default-browser-check', - '--password-store=basic', - '--use-mock-keychain', - '--disable-sync', - '--disable-extensions', - '--disable-component-update', - '--metrics-recording-only', - '--remote-debugging-port=0', - `--user-data-dir=${chromeProfileDir}`, - 'about:blank', - ], - { stdio: ['ignore', 'ignore', 'pipe'], env: chromeEnv() } - ); - - const browserWsUrl = 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(browserWsUrl).port; + const debugPort = await harness.launchChromium(); const openNewTab = async () => { const res = await fetch( `http://127.0.0.1:${debugPort}/json/new?about:blank`, @@ -2142,28 +1990,5 @@ try { for (const tab of openTabs) { tab.close(); } - if (chromeProc && chromeProc.pid) { - try { - process.kill(chromeProc.pid, 'SIGTERM'); - } catch { - // Already exited. - } - } - if (serverProc && serverProc.pid) { - try { - process.kill(serverProc.pid, 'SIGTERM'); - } catch { - // Already exited. - } - } - try { - rmSync(workTmp, { - recursive: true, - force: true, - maxRetries: 5, - retryDelay: 100, - }); - } catch { - // Ignore transient Chrome profile lock on teardown. - } + await harness.close(); } diff --git a/packages/frontend/hosts/web/tests/chromium-harness.test.mjs b/packages/frontend/hosts/web/tests/chromium-harness.test.mjs new file mode 100644 index 0000000000..0d348b0477 --- /dev/null +++ b/packages/frontend/hosts/web/tests/chromium-harness.test.mjs @@ -0,0 +1,554 @@ +// @ts-check + +/** + * Lifecycle tests for `scripts/chromium-harness.mjs`. + * + * Each test starts this file again as a `runner` process that owns a harness. + * The harness starts this file as a fake `server`, and the server starts a + * `grandchild` in its process group. The server and the grandchild each hold a + * TCP socket of the test open. The kernel closes that socket when its process + * dies, so the test waits for events and never for a fixed time. + */ + +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { + existsSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, + writeSync, +} from 'node:fs'; +import { createServer as createHttpServer } from 'node:http'; +import { connect, createServer as createTcpServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; + +import { createChromiumHarness } from '../scripts/chromium-harness.mjs'; + +const SELF = fileURLToPath(import.meta.url); + +/** For the scenarios where the harness waits until a time limit ends. */ +const SHORT_LIMITS = { termGraceMs: 50, groupGoneTimeoutMs: 100 }; + +/** + * The runner scenarios. `server` is the mode of the fake server, `signals` + * patches the answers for process-group signals, and `limits` goes to the + * harness. + * + * @type {Record} + */ +const RUNNER_SCENARIOS = { + close: {}, + throw: {}, + wait: {}, + exit: {}, + 'denied-close': { signals: 'denied', limits: SHORT_LIMITS }, + 'denied-exit': { signals: 'denied' }, + 'alive-close': { signals: 'alive', limits: SHORT_LIMITS }, + 'kill-denied-close': { + server: 'ignore-term', + signals: 'denied-after-term', + limits: SHORT_LIMITS, + }, + 'reaped-late-close': { signals: 'denied-until-reaped' }, + 'signal-during-health': {}, + 'health-hangs': { limits: { serverHealthTimeoutMs: 100 } }, + 'launch-fails': {}, +}; + +/** Listens on a free TCP port and keeps each accepted socket open. */ +async function listenLiveness() { + /** @type {import('node:net').Socket[]} */ + const held = []; + const server = createTcpServer(socket => { + socket.on('error', () => {}); + socket.resume(); + held.push(socket); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + return /** @type {import('node:net').AddressInfo} */ (server.address()).port; +} + +/** Ignores `SIGTERM`: only the `SIGKILL` of its process group stops it. */ +async function runGrandchild() { + process.on('SIGTERM', () => {}); + process.stdout.write(`${await listenLiveness()}\n`); +} + +/** + * `plain` answers the health check. `ignore-term` also ignores `SIGTERM`. + * `signal-on-health` ignores `SIGTERM` and never answers the health check. It + * sends `SIGTERM` to the runner when the health request arrives. + * + * @param {string[]} args Health port, info file path, and mode. + */ +async function runFakeServer([healthPort, infoPath, mode]) { + const grandchild = spawn(process.execPath, [SELF, 'grandchild'], { + stdio: ['ignore', 'pipe', 'inherit'], + }); + const [grandchildPort] = await once(grandchild.stdout, 'data'); + writeFileSync( + infoPath, + JSON.stringify({ + pgid: process.pid, + livenessPorts: [await listenLiveness(), Number(String(grandchildPort))], + }) + ); + if (mode !== 'plain') { + process.on('SIGTERM', () => {}); + } + createHttpServer((req, res) => { + if (req.url === '/exit') { + res.end(() => process.exit(0)); + } else if (mode === 'signal-on-health') { + process.kill(process.ppid, 'SIGTERM'); + } else { + res.end('ok'); + } + }).listen(Number(healthPort), '127.0.0.1'); +} + +/** + * Replaces the answer of the kernel for process-group signals. + * + * - `denied`: each signal gets `EPERM`. + * - `alive`: each probe finds the group. + * - `denied-after-term`: `SIGTERM` arrives. Each other signal gets `EPERM`. + * - `denied-until-reaped`: the answers of macOS for a group that holds only + * zombies. After Node reaps the leader, the next three signals arrive but + * get `EPERM`. Then the kernel answers again. + * + * @param {string} mode + * @returns {() => number} How many `EPERM` answers of `denied-until-reaped` are still to come. + */ +function patchGroupSignals(mode) { + const realKill = process.kill.bind(process); + const deny = () => { + throw Object.assign(new Error('kill EPERM'), { code: 'EPERM' }); + }; + /** @param {number} pid */ + const isReaped = pid => { + try { + realKill(pid, 0); + return false; + } catch { + return true; + } + }; + let transientDenials = mode === 'denied-until-reaped' ? 3 : 0; + process.kill = (pid, signal) => { + if (pid >= 0) { + return realKill(pid, signal); + } + if ( + mode === 'denied' || + (mode === 'denied-after-term' && signal !== 'SIGTERM') + ) { + deny(); + } + if (mode === 'alive' && signal === 0) { + return true; + } + if (transientDenials > 0 && isReaped(-pid)) { + transientDenials -= 1; + try { + realKill(pid, signal); + } catch { + // The group is gone. + } + deny(); + } + return realKill(pid, signal); + }; + return () => transientDenials; +} + +/** + * @param {string[]} args Scenario, info file path, and health port. + */ +async function runRunner([scenario, infoPath, healthPort]) { + const { server = 'plain', signals, limits } = RUNNER_SCENARIOS[scenario]; + const harness = createChromiumHarness({ + tmpPrefix: 'affine-harness-test-', + limits, + }); + const baseUrl = `http://127.0.0.1:${healthPort}`; + /** + * @param {string} mode + * @param {string} [healthUrl] + */ + const startServer = (mode, healthUrl = baseUrl) => + harness.startServer({ + bin: process.execPath, + args: [SELF, 'server', healthPort, infoPath, mode], + baseUrl: healthUrl, + }); + /** @param {object} fields */ + const report = fields => { + writeSync( + 1, + `${JSON.stringify({ workTmp: harness.workTmp, ...fields })}\n` + ); + }; + + /** + * Runs a start that fails, closes the harness, and reports the error. + * + * @param {() => Promise} start + */ + const reportFailedStart = async start => { + let message = ''; + try { + await start(); + } catch (err) { + message = String(err); + } finally { + await harness.close(); + } + report({ message }); + }; + + if (scenario === 'launch-fails') { + await reportFailedStart(() => harness.launchChromium()); + return; + } + + if (scenario === 'health-hangs') { + // The health URL is a listener in this process that never answers. Thus + // the health request is in flight when the time limit ends. + const silent = createHttpServer(() => {}).listen(0, '127.0.0.1'); + await once(silent, 'listening'); + const { port } = /** @type {import('node:net').AddressInfo} */ ( + silent.address() + ); + await reportFailedStart(() => + startServer('plain', `http://127.0.0.1:${port}`) + ); + silent.close(); + silent.closeAllConnections(); + return; + } + + if (scenario === 'signal-during-health') { + const refusals = []; + for (const mode of ['signal-on-health', 'plain']) { + try { + await startServer(mode); + refusals.push(null); + } catch (err) { + refusals.push(String(err)); + } + } + report({ refusals }); + await once(process.stdin, 'data'); + process.stdin.pause(); + // The escalation to `SIGKILL` can stop the server before this request. + await fetch(`${baseUrl}/exit`).catch(() => {}); + return; + } + + await startServer(server); + const pendingDenials = signals ? patchGroupSignals(signals) : () => 0; + report({}); + // The test says when to go on. The `wait` scenario never gets this line. + await once(process.stdin, 'data'); + process.stdin.pause(); + if (scenario === 'exit' || scenario === 'denied-exit') { + process.exit(7); + } + try { + assert.notEqual(scenario, 'throw'); + } finally { + await harness.close(); + } + // The scenario is void if the harness did not get each `EPERM` answer. + assert.equal(pendingDenials(), 0); +} + +async function allocateFreePort() { + const server = createTcpServer(); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const { port } = /** @type {import('node:net').AddressInfo} */ ( + server.address() + ); + server.close(); + await once(server, 'close'); + return port; +} + +/** + * Connects to a liveness port. The result resolves when the peer process is + * dead: the kernel then ends, resets, or refuses the connection. + * + * @param {number} port + * @returns {Promise} + */ +function watchLiveness(port) { + const socket = connect(port, '127.0.0.1'); + socket.on('error', () => {}); + socket.resume(); + return new Promise(resolve => { + socket.once('close', () => resolve()); + }); +} + +/** + * Starts a runner and resolves after its first report line. + * + * @param {import('node:test').TestContext} t + * @param {string} scenario + * @param {NodeJS.ProcessEnv} [env] + */ +async function startScenario(t, scenario, env = {}) { + const scratch = mkdtempSync(join(tmpdir(), 'affine-harness-scratch-')); + const infoPath = join(scratch, 'info.json'); + /** @returns {{ pgid: number, livenessPorts: number[] } | null} */ + const readInfo = () => + existsSync(infoPath) ? JSON.parse(readFileSync(infoPath, 'utf8')) : null; + const runner = spawn( + process.execPath, + [SELF, 'runner', scenario, infoPath, String(await allocateFreePort())], + { stdio: 'pipe', env: { ...process.env, ...env } } + ); + /** @type {string | null} */ + let workTmp = null; + let dead = false; + // A harness defect must not leave processes or directories behind the test. + t.after(() => { + runner.kill('SIGKILL'); + const info = readInfo(); + if (info && !dead) { + try { + process.kill(-info.pgid, 'SIGKILL'); + } catch { + // Already gone. + } + } + if (workTmp) { + rmSync(workTmp, { recursive: true, force: true }); + } + rmSync(scratch, { recursive: true, force: true }); + }); + let stdout = ''; + let stderr = ''; + runner.stderr.on('data', chunk => { + stderr += String(chunk); + }); + /** @type {Promise<{ code: number | null, signal: string | null }>} */ + const exit = once(runner, 'close').then(([code, signal]) => ({ + code, + signal, + })); + /** @type {Promise>} */ + const firstReport = new Promise((resolve, reject) => { + runner.stdout.on('data', chunk => { + stdout += String(chunk); + const end = stdout.indexOf('\n'); + if (end >= 0) { + resolve(JSON.parse(stdout.slice(0, end))); + } + }); + void exit.then(() => + reject(new Error(`The runner ended before its report: ${stderr}`)) + ); + }); + const report = await firstReport; + workTmp = report.workTmp; + const info = readInfo(); + const allDead = Promise.all( + (info?.livenessPorts ?? []).map(watchLiveness) + ).then(() => { + dead = true; + }); + return { + report, + info, + exit, + allDead, + stderr: () => stderr, + /** Tells the runner to go on. */ + go: () => runner.stdin.end('go\n'), + /** @param {NodeJS.Signals} signal */ + signal: signal => runner.kill(signal), + }; +} + +/** @param {number} pgid */ +function assertGroupGone(pgid) { + assert.throws(() => process.kill(-pgid, 0), { code: 'ESRCH' }); +} + +const END_PATHS = [ + { name: 'normal end', scenario: 'close', code: 0, reaped: true }, + { name: 'failed assertion', scenario: 'throw', code: 1, reaped: true }, + { name: 'SIGINT', scenario: 'wait', code: 130, reaped: true }, + { name: 'SIGTERM', scenario: 'wait', code: 143, reaped: true }, + { + name: 'close() while the group answers EPERM until the system reaps it', + scenario: 'reaped-late-close', + code: 0, + reaped: true, + }, + // `process.exit()` cannot wait for the reap: only the deaths are checked. + { name: 'process.exit()', scenario: 'exit', code: 7, reaped: false }, +]; + +const SURVIVOR_PATHS = [ + { + name: 'close() cannot signal the group', + scenario: 'denied-close', + code: 0, + reason: 'cannot be signalled (EPERM)', + }, + { + name: 'process.exit() cannot signal the group', + scenario: 'denied-exit', + code: 7, + reason: 'cannot be signalled (EPERM)', + }, + { + name: 'close() sends SIGTERM to a group that ignores it, and cannot send SIGKILL', + scenario: 'kill-denied-close', + code: 0, + reason: 'cannot be signalled (EPERM)', + }, + { + name: 'close() finds the group still alive', + scenario: 'alive-close', + code: 0, + reason: 'is still alive', + }, +]; + +function registerTests() { + void test('each way to end stops the owned process group and removes the work directory', async t => { + for (const path of END_PATHS) { + await t.test(path.name, { timeout: 60000 }, async st => { + const run = await startScenario(st, path.scenario); + assert.ok(run.info); + assert.equal(existsSync(run.report.workTmp), true); + if (path.scenario === 'wait') { + run.signal(/** @type {NodeJS.Signals} */ (path.name)); + } else { + run.go(); + } + assert.deepEqual(await run.exit, { code: path.code, signal: null }); + await run.allDead; + if (path.reaped) { + assertGroupGone(run.info.pgid); + } + assert.equal(existsSync(run.report.workTmp), false); + assert.doesNotMatch(run.stderr(), /\[chromium-harness\]/); + }); + } + }); + + void test('a process group that cannot be signalled or stays alive keeps the work directory and prints its path', async t => { + for (const path of SURVIVOR_PATHS) { + await t.test(path.name, { timeout: 60000 }, async st => { + const run = await startScenario(st, path.scenario); + assert.ok(run.info); + run.go(); + assert.deepEqual(await run.exit, { code: path.code, signal: null }); + assert.equal(existsSync(run.report.workTmp), true); + assert.ok( + run + .stderr() + .includes( + `[chromium-harness] kept ${run.report.workTmp}: server process group ${run.info.pgid} ${path.reason}` + ), + run.stderr() + ); + }); + } + }); + + void test( + 'a signal during the server health check refuses that server and each later start', + { timeout: 60000 }, + async t => { + const run = await startScenario(t, 'signal-during-health'); + assert.ok(run.info); + run.go(); + assert.match( + run.report.refusals[0], + /Refused use of the server at http:\/\/127\.0\.0\.1:\d+: teardown is in progress/ + ); + assert.match( + run.report.refusals[1], + /Refused start of server: teardown is in progress/ + ); + assert.deepEqual(await run.exit, { code: 143, signal: null }); + await run.allDead; + assertGroupGone(run.info.pgid); + assert.equal(existsSync(run.report.workTmp), false); + } + ); + + void test( + 'a health request without an answer stops at the time limit, the server start fails, and close() removes the work directory', + { timeout: 60000 }, + async t => { + const run = await startScenario(t, 'health-hangs'); + assert.match(run.report.message, /did not become healthy/); + assert.deepEqual(await run.exit, { code: 0, signal: null }); + await run.allDead; + assert.equal(existsSync(run.report.workTmp), false); + assert.doesNotMatch(run.stderr(), /\[chromium-harness\]/); + } + ); + + void test('the harness uses the browser path from CHROME_PATH as given, and close() removes the work directory after a failed launch', async t => { + const scratch = mkdtempSync(join(tmpdir(), 'affine-harness-chrome-')); + t.after(() => rmSync(scratch, { recursive: true, force: true })); + // The wrapper records its start in a marker file and exits before + // DevTools is ready. + const wrapper = join(scratch, 'chrome-wrapper'); + const marker = `${wrapper}.started`; + writeFileSync(wrapper, '#!/bin/sh\n: > "$0.started"\nexit 22\n', { + mode: 0o755, + }); + const paths = [ + { + name: 'a shell wrapper starts, and CHROME_BIN does not replace it', + env: { CHROME_PATH: wrapper, CHROME_BIN: process.execPath }, + message: /Chromium exited early \(22\)/, + started: true, + }, + { + name: 'a path that does not exist is an error, and CHROME_BIN does not replace it', + env: { CHROME_PATH: join(scratch, 'missing'), CHROME_BIN: wrapper }, + message: /CHROME_PATH or CHROME_BIN does not exist/, + started: false, + }, + ]; + for (const path of paths) { + await t.test(path.name, { timeout: 60000 }, async st => { + rmSync(marker, { force: true }); + const run = await startScenario(st, 'launch-fails', path.env); + assert.match(run.report.message, path.message); + assert.equal(existsSync(marker), path.started); + assert.deepEqual(await run.exit, { code: 0, signal: null }); + assert.equal(existsSync(run.report.workTmp), false); + }); + } + }); +} + +const [role, ...roleArgs] = process.argv.slice(2); +if (role === 'runner') { + await runRunner(roleArgs); +} else if (role === 'server') { + await runFakeServer(roleArgs); +} else if (role === 'grandchild') { + await runGrandchild(); +} else { + registerTests(); +} diff --git a/packages/ui/AGENTS.md b/packages/ui/AGENTS.md index c893d7c8c5..e64511cc5e 100644 --- a/packages/ui/AGENTS.md +++ b/packages/ui/AGENTS.md @@ -8,7 +8,7 @@ This directory belongs to the client Cargo workspace rooted at `packages/fronten ### Workspace boundaries - `packages/ui/tokens` (`ui-tokens`): Zero-dependency crate (`#![forbid(unsafe_code)]`) exposing generated `tokens` (`tokens.rs`), `icons` (`icons.rs`), and the five tracked repository font slices via `bundled_font_bytes()`, while keeping `extract-tokens.mjs --check` and standalone `rustc --edition 2024 --test` gates intact. - `packages/ui/ui`: Single fused internal GPU UI library (vendored once without upstream sync hooks, zero internal `proc-macro = true` crates, zero external UI-kit dependencies). It knows **nothing** about BlockSuite or AFFiNE (`packages/frontend/scripts/check-invariants.sh` rejects `blocksuite` and `affine` inside `packages/ui/ui`) and embeds zero fonts (fonts are registered by the application via `cx.text_system().add_fonts(...)`). -- `packages/ui/kit` (`ui-kit`): Domain-neutral cross-platform component library (`#![forbid(unsafe_code)]`) depending only on `ui` and `ui-tokens`. Provides `LogicalEdges`, `LogicalStyled`, `SafeArea`, `VirtualList`, `SwipeDialog` (`Sheet`), and `SwipeMenu`. `packages/frontend/scripts/check-invariants.sh` rejects BlockSuite/AFFiNE terms and physical left/right layout helpers inside `packages/ui/kit/src`. +- `packages/ui/kit` (`ui-kit`): Domain-neutral cross-platform component library (`#![forbid(unsafe_code)]`) depending only on `ui` and `ui-tokens`. Provides `LogicalEdges`, `LogicalStyled`, `SafeArea`, `VirtualList`, and `SwipeDialog` (`Sheet`). `packages/frontend/scripts/check-invariants.sh` rejects BlockSuite/AFFiNE terms and physical left/right layout helpers inside `packages/ui/kit/src`. ### Platform matrix `packages/ui/ui` compiles cleanly across four targets from one crate: diff --git a/packages/ui/kit/src/lib.rs b/packages/ui/kit/src/lib.rs index f2b5201ad3..40ce73a021 100644 --- a/packages/ui/kit/src/lib.rs +++ b/packages/ui/kit/src/lib.rs @@ -10,7 +10,6 @@ pub mod logical; pub mod micro_icon; pub mod safe_area; pub mod sheet; -pub mod swipe_menu; pub mod virtual_list; pub use breadcrumb::{ @@ -29,5 +28,4 @@ pub use sheet::{ SWIPE_DIALOG_CLOSE_MS, SWIPE_DIALOG_OPEN_MS, Sheet, SwipeDialog, SwipeDialogSnapshot, SwipeDialogState, }; -pub use swipe_menu::{SWIPE_MENU_SNAP_MS, SwipeMenu, SwipeMenuSnapshot, SwipeMenuState}; pub use virtual_list::{ScrollAnchor, VirtualList, VirtualListMetrics, VirtualWindow}; diff --git a/packages/ui/kit/src/swipe_menu.rs b/packages/ui/kit/src/swipe_menu.rs deleted file mode 100644 index c89b056aa5..0000000000 --- a/packages/ui/kit/src/swipe_menu.rs +++ /dev/null @@ -1,369 +0,0 @@ -//! Closed-form swipe-to-reveal action menu state machine with logical LTR/RTL direction support. - -use ui::{Direction, Motion, MotionCurve}; - -/// Default snap duration for [`SwipeMenu`] (`230 ms`, `MotionCurve::SWIPE_MENU`). -pub const SWIPE_MENU_SNAP_MS: f64 = 230.0; -/// Velocity threshold (logical pixels per second) that commits a swipe open or closed. -const SWIPE_MENU_VELOCITY_THRESHOLD: f64 = 240.0; - -/// Pure-data state of a [`SwipeMenu`]. -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum SwipeMenuState { - Closed, - Open, - Snapping { motion: Motion, target_open: bool }, - Dragging { logical_offset: f64 }, -} - -/// Deterministic snapshot of a [`SwipeMenu`] evaluated at one scheduler timestamp. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct SwipeMenuSnapshot { - /// Reveal distance in logical inline-end direction (`0.0..=action_width`). - pub logical_offset: f64, - /// Physical horizontal translation (`-logical_offset` in LTR, `+logical_offset` in RTL). - pub physical_offset: f64, - pub is_open: bool, - pub is_animating: bool, - /// Whether menu input interception is active. Drops to `false` on frame 0 of `close()`. - pub accepts_input: bool, -} - -impl SwipeMenuSnapshot { - /// Deterministic byte representation for frame-rate replay invariance checks. - pub fn to_bytes(self) -> [u8; 19] { - let mut out = [0u8; 19]; - out[..8].copy_from_slice(&self.logical_offset.to_bits().to_le_bytes()); - out[8..16].copy_from_slice(&self.physical_offset.to_bits().to_le_bytes()); - out[16] = u8::from(self.is_open); - out[17] = u8::from(self.is_animating); - out[18] = u8::from(self.accepts_input); - out - } -} - -/// Closed-form swipe-menu controller with continuous mid-flight interruption and RTL mirroring. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct SwipeMenu { - action_width: f64, - state: SwipeMenuState, - snap_curve: MotionCurve, - snap_duration_ms: f64, -} - -impl SwipeMenu { - pub const fn new(action_width: f64) -> Self { - Self { - action_width, - state: SwipeMenuState::Closed, - snap_curve: MotionCurve::SWIPE_MENU, - snap_duration_ms: SWIPE_MENU_SNAP_MS, - } - } - - pub const fn action_width(&self) -> f64 { - self.action_width - } - - pub const fn state(&self) -> SwipeMenuState { - self.state - } - - /// Evaluates logical reveal offset (`0.0..=action_width`) at `now_ms`. - pub fn logical_offset_at(&self, now_ms: f64) -> f64 { - let max = self.action_width.max(0.0); - match self.state { - SwipeMenuState::Closed => 0.0, - SwipeMenuState::Open => max, - SwipeMenuState::Snapping { motion, .. } => motion.value_at(now_ms).clamp(0.0, max), - SwipeMenuState::Dragging { logical_offset } => logical_offset.clamp(0.0, max), - } - } - - /// Evaluates signed physical x-translation (`-logical` in LTR, `+logical` in RTL). - pub fn physical_offset_at(&self, now_ms: f64, direction: Direction) -> f64 { - let logical = self.logical_offset_at(now_ms); - match direction { - Direction::Ltr => -logical, - Direction::Rtl => logical, - } - } - - pub fn is_animating(&self, now_ms: f64) -> bool { - matches!( - self.state, - SwipeMenuState::Snapping { motion, .. } if !motion.is_finished(now_ms) - ) - } - - /// Snaps the menu open from its exact current offset. - pub fn open(&mut self, now_ms: f64) { - let max = self.action_width.max(0.0); - let from = self.logical_offset_at(now_ms); - if max <= 0.0 || from >= max { - self.state = SwipeMenuState::Open; - return; - } - let duration = self.snap_duration_ms * ((max - from) / max); - self.state = SwipeMenuState::Snapping { - motion: Motion::new(from, max, self.snap_curve, now_ms, duration), - target_open: true, - }; - } - - /// Snaps the menu closed from its exact current offset. - pub fn close(&mut self, now_ms: f64) { - let max = self.action_width.max(0.0); - let from = self.logical_offset_at(now_ms); - if max <= 0.0 || from <= 0.0 { - self.state = SwipeMenuState::Closed; - return; - } - let duration = self.snap_duration_ms * (from / max); - self.state = SwipeMenuState::Snapping { - motion: Motion::new(from, 0.0, self.snap_curve, now_ms, duration), - target_open: false, - }; - } - - /// Freezes the current offset into interactive drag mode. - pub fn begin_drag(&mut self, now_ms: f64) { - let logical_offset = self.logical_offset_at(now_ms); - self.state = SwipeMenuState::Dragging { logical_offset }; - } - - /// Applies a physical horizontal pointer delta `dx` (`-dx` reveals in LTR, `+dx` reveals in RTL), - /// starting continuously from the current offset at `now_ms` even if called mid-snap. - pub fn drag_by_physical(&mut self, physical_dx: f64, direction: Direction, now_ms: f64) { - let logical_delta = match direction { - Direction::Ltr => -physical_dx, - Direction::Rtl => physical_dx, - }; - let current = self.logical_offset_at(now_ms); - self.state = SwipeMenuState::Dragging { - logical_offset: (current + logical_delta).clamp(0.0, self.action_width.max(0.0)), - }; - } - - /// Releases drag and snaps open or closed based on logical reveal distance and physical velocity. - pub fn end_drag(&mut self, physical_velocity_x: f64, direction: Direction, now_ms: f64) { - let logical_velocity = match direction { - Direction::Ltr => -physical_velocity_x, - Direction::Rtl => physical_velocity_x, - }; - let current = self.logical_offset_at(now_ms); - let max = self.action_width.max(0.0); - let should_open = if logical_velocity.abs() >= SWIPE_MENU_VELOCITY_THRESHOLD { - logical_velocity > 0.0 - } else { - current >= max * 0.5 - }; - if should_open { - self.open(now_ms); - } else { - self.close(now_ms); - } - } - - /// Promotes a finished snap transition into its resting `Open` or `Closed` state. - pub fn settle(&mut self, now_ms: f64) { - if let SwipeMenuState::Snapping { - motion, - target_open, - } = self.state - && motion.is_finished(now_ms) - { - self.state = if target_open { - SwipeMenuState::Open - } else { - SwipeMenuState::Closed - }; - } - } - - /// Evaluates the deterministic snapshot at `now_ms` for `direction`. - pub fn snapshot_at(&self, now_ms: f64, direction: Direction) -> SwipeMenuSnapshot { - let logical_offset = self.logical_offset_at(now_ms); - let physical_offset = self.physical_offset_at(now_ms, direction); - let is_animating = self.is_animating(now_ms); - let is_open = match self.state { - SwipeMenuState::Open => true, - SwipeMenuState::Closed => false, - SwipeMenuState::Snapping { target_open, .. } => { - if is_animating { - logical_offset > 0.0 - } else { - target_open - } - } - SwipeMenuState::Dragging { .. } => logical_offset > 0.0, - }; - let accepts_input = match self.state { - SwipeMenuState::Open => true, - SwipeMenuState::Closed => false, - SwipeMenuState::Snapping { target_open, .. } => target_open, - SwipeMenuState::Dragging { .. } => logical_offset > 0.0, - }; - SwipeMenuSnapshot { - logical_offset, - physical_offset, - is_open, - is_animating, - accepts_input, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn replay_at_fps(fps: f64, direction: Direction) -> [u8; 19] { - let step_ms = 1000.0 / fps; - let mut menu = SwipeMenu::new(144.0); - menu.open(0.0); - - let mut t = 0.0; - let mut reversed = false; - while t < 500.0 { - if !reversed && t >= 90.0 { - let before = menu.logical_offset_at(90.0); - menu.close(90.0); - let after = menu.logical_offset_at(90.0); - assert!( - (before - after).abs() < 1e-12, - "reversal must stay continuous" - ); - menu.open(140.0); - reversed = true; - } - menu.settle(t); - t += step_ms; - } - menu.settle(500.0); - menu.snapshot_at(500.0, direction).to_bytes() - } - - #[test] - fn swipe_menu_four_rate_replay_is_byte_identical_in_ltr_and_rtl() { - for direction in [Direction::Ltr, Direction::Rtl] { - let baseline = replay_at_fps(60.0, direction); - for fps in [120.0, 24.0, 7.0] { - assert_eq!( - replay_at_fps(fps, direction), - baseline, - "mismatch at {fps} fps ({direction:?})" - ); - } - } - } - - fn sample_schedule_at_fps(fps: f64, direction: Direction) -> [[u8; 19]; 4] { - let step_ms = 1000.0 / fps; - let mut menu = SwipeMenu::new(144.0); - menu.open(0.0); - - let mut mid_open = None; - let mut rev_frame0 = None; - let mut mid_close = None; - let mut t = 0.0; - while t < 500.0 { - if mid_open.is_none() && t >= 100.0 { - mid_open = Some(menu.snapshot_at(100.0, direction).to_bytes()); - } - if rev_frame0.is_none() && t >= 120.0 { - menu.close(120.0); - rev_frame0 = Some(menu.snapshot_at(120.0, direction).to_bytes()); - } - if mid_close.is_none() && t >= 200.0 { - mid_close = Some(menu.snapshot_at(200.0, direction).to_bytes()); - } - menu.settle(t); - t += step_ms; - } - menu.settle(500.0); - let terminal = menu.snapshot_at(500.0, direction).to_bytes(); - [ - mid_open.expect("mid-open sample"), - rev_frame0.expect("reversal frame 0 sample"), - mid_close.expect("mid-close sample"), - terminal, - ] - } - - #[test] - fn swipe_menu_mid_flight_reversal_and_terminal_match_across_60_90_120_144_hz() { - for direction in [Direction::Ltr, Direction::Rtl] { - let baseline = sample_schedule_at_fps(60.0, direction); - for fps in [90.0, 120.0, 144.0] { - assert_eq!( - sample_schedule_at_fps(fps, direction), - baseline, - "mid-flight/reversal/terminal mismatch at {fps} Hz ({direction:?})" - ); - } - } - } - - #[test] - fn swipe_menu_mirrors_drag_and_offset_between_ltr_and_rtl() { - let mut ltr = SwipeMenu::new(120.0); - let mut rtl = SwipeMenu::new(120.0); - - ltr.begin_drag(0.0); - ltr.drag_by_physical(-80.0, Direction::Ltr, 0.0); - rtl.begin_drag(0.0); - rtl.drag_by_physical(80.0, Direction::Rtl, 0.0); - - assert_eq!(ltr.logical_offset_at(0.0), 80.0); - assert_eq!(rtl.logical_offset_at(0.0), 80.0); - assert_eq!(ltr.physical_offset_at(0.0, Direction::Ltr), -80.0); - assert_eq!(rtl.physical_offset_at(0.0, Direction::Rtl), 80.0); - - ltr.end_drag(-300.0, Direction::Ltr, 10.0); - rtl.end_drag(300.0, Direction::Rtl, 10.0); - ltr.settle(400.0); - rtl.settle(400.0); - assert_eq!(ltr.state(), SwipeMenuState::Open); - assert_eq!(rtl.state(), SwipeMenuState::Open); - assert_eq!( - ltr.physical_offset_at(400.0, Direction::Ltr), - -rtl.physical_offset_at(400.0, Direction::Rtl) - ); - } - - #[test] - fn swipe_menu_releases_input_on_first_frame_of_close() { - let mut menu = SwipeMenu::new(120.0); - menu.open(0.0); - assert!(menu.snapshot_at(0.0, Direction::Ltr).accepts_input); - - menu.settle(300.0); - assert!(menu.snapshot_at(300.0, Direction::Ltr).accepts_input); - - menu.close(300.0); - let frame0 = menu.snapshot_at(300.0, Direction::Ltr); - assert!(!frame0.accepts_input); - assert!(frame0.logical_offset > 0.0); - assert!(frame0.is_animating); - - let mid = menu.snapshot_at(380.0, Direction::Rtl); - assert!(!mid.accepts_input); - assert!(mid.logical_offset > 0.0 && mid.logical_offset < 120.0); - } - - #[test] - fn swipe_menu_drag_by_physical_mid_snap_is_continuous() { - let mut menu = SwipeMenu::new(120.0); - menu.open(0.0); - let before = menu.logical_offset_at(100.0); - assert!(before > 0.0 && before < 120.0); - - menu.drag_by_physical(-5.0, Direction::Ltr, 100.0); - let after = menu.logical_offset_at(100.0); - assert!( - (after - (before + 5.0).min(120.0)).abs() < 1e-12, - "drag_by_physical during Snapping must stay continuous: before={before}, after={after}" - ); - } -} diff --git a/packages/ui/tokens/extract-tokens.mjs b/packages/ui/tokens/extract-tokens.mjs index dd3b8a38d5..5c0ad09f7c 100644 --- a/packages/ui/tokens/extract-tokens.mjs +++ b/packages/ui/tokens/extract-tokens.mjs @@ -613,11 +613,6 @@ function generateTokensRs(nodeModulesDir) { const lightData = buildThemeSection(lightMerged); const darkData = buildThemeSection(darkMerged); - const radii = [...root.entries()] - .filter(([k]) => /radius/i.test(k)) - .sort(([a], [b]) => cmpCodeUnit(a, b)) - .map(([k, v]) => [k, parsePxStrict(v, k)]); - const pickColor = (map, key) => { const c = resolveColorVar(map, key); if (!c) { @@ -754,8 +749,6 @@ pub struct TypographyTokens { pub line_height_base_px: f32, pub editor_width_px: f32, pub paragraph_space_px: f32, - pub popover_radius_px: f32, - pub radii: &'static [(&'static str, f32)], } pub const TYPOGRAPHY: TypographyTokens = TypographyTokens { @@ -775,10 +768,6 @@ pub const TYPOGRAPHY: TypographyTokens = TypographyTokens { line_height_base_px: ${formatF32(resolvedLineHeightPx)}, editor_width_px: ${formatF32(requirePx(root, '--affine-editor-width'))}, paragraph_space_px: ${formatF32(requirePx(root, '--affine-paragraph-space'))}, - popover_radius_px: ${formatF32(requirePx(root, '--affine-popover-radius'))}, - radii: &[ -${radii.map(([k, v]) => ` (${rustStr(k)}, ${formatF32(v)}),`).join('\n')} - ], }; #[derive(Debug, Clone, Copy)] @@ -857,7 +846,6 @@ mod tests { assert_strictly_sorted(DARK_THEME.colors, "DARK_THEME.colors"); assert_strictly_sorted(LIGHT_THEME.shadows, "LIGHT_THEME.shadows"); assert_strictly_sorted(DARK_THEME.shadows, "DARK_THEME.shadows"); - assert_strictly_sorted(TYPOGRAPHY.radii, "TYPOGRAPHY.radii"); for &(k, v) in LIGHT_THEME.colors { assert_eq!(LIGHT_THEME.color(k), Some(v), "LIGHT_THEME.color({k})"); diff --git a/packages/ui/tokens/tokens.rs b/packages/ui/tokens/tokens.rs index 8a1664716b..87322f9bbf 100644 --- a/packages/ui/tokens/tokens.rs +++ b/packages/ui/tokens/tokens.rs @@ -70,8 +70,6 @@ pub struct TypographyTokens { pub line_height_base_px: f32, pub editor_width_px: f32, pub paragraph_space_px: f32, - pub popover_radius_px: f32, - pub radii: &'static [(&'static str, f32)], } pub const TYPOGRAPHY: TypographyTokens = TypographyTokens { @@ -91,10 +89,6 @@ pub const TYPOGRAPHY: TypographyTokens = TypographyTokens { line_height_base_px: 23.0_f32, editor_width_px: 944.0_f32, paragraph_space_px: 8.0_f32, - popover_radius_px: 12.0_f32, - radii: &[ - ("--affine-popover-radius", 12.0_f32), - ], }; #[derive(Debug, Clone, Copy)] @@ -1571,7 +1565,6 @@ mod tests { assert_strictly_sorted(DARK_THEME.colors, "DARK_THEME.colors"); assert_strictly_sorted(LIGHT_THEME.shadows, "LIGHT_THEME.shadows"); assert_strictly_sorted(DARK_THEME.shadows, "DARK_THEME.shadows"); - assert_strictly_sorted(TYPOGRAPHY.radii, "TYPOGRAPHY.radii"); for &(k, v) in LIGHT_THEME.colors { assert_eq!(LIGHT_THEME.color(k), Some(v), "LIGHT_THEME.color({k})"); diff --git a/packages/ui/ui/src/fast/layout.rs b/packages/ui/ui/src/fast/layout.rs index 9f4fa56d6d..7b7bc26af3 100644 --- a/packages/ui/ui/src/fast/layout.rs +++ b/packages/ui/ui/src/fast/layout.rs @@ -2,8 +2,8 @@ use crate::collections::{FxHashMap, FxHashSet, FxHasher}; use crate::{ - AbsoluteLength, App, AvailableSpace, DefiniteLength, Edges, GridTemplate, LayoutId, Length, - Pixels, Size, Style, Window, + AbsoluteLength, App, AvailableSpace, DefiniteLength, Edges, LayoutId, Length, Pixels, Size, + Style, Window, fast::stats::LayoutStats, taffy::{MeasureFn, NodeContext, TaffyLayoutEngine, ToTaffy as _}, util::round_to_device_pixel, @@ -1328,22 +1328,6 @@ fn layout_fingerprint(style: &Style, rem_size: Pixels, scale_factor: f32) -> u64 each(hasher, &size.width); each(hasher, &size.height); } - fn placement(hasher: &mut FxHasher, placement: &crate::GridPlacement) { - match placement { - crate::GridPlacement::Line(line) => (0u8, *line).hash(hasher), - crate::GridPlacement::Span(span) => (1u8, *span).hash(hasher), - crate::GridPlacement::Auto => 2u8.hash(hasher), - } - } - fn template(hasher: &mut FxHasher, template: &Option) { - match template { - Some(template) => { - (1u8, template.repeat).hash(hasher); - mem::discriminant(&template.min_size).hash(hasher); - } - None => 0u8.hash(hasher), - } - } let mut hasher = FxHasher::default(); let hasher = &mut hasher; @@ -1384,17 +1368,5 @@ fn layout_fingerprint(style: &Style, rem_size: Pixels, scale_factor: f32) -> u64 length(hasher, &style.flex_basis); style.flex_grow.to_bits().hash(hasher); style.flex_shrink.to_bits().hash(hasher); - template(hasher, &style.grid_rows); - template(hasher, &style.grid_cols); - match &style.grid_location { - Some(location) => { - 1u8.hash(hasher); - for line in [&location.row, &location.column] { - placement(hasher, &line.start); - placement(hasher, &line.end); - } - } - None => 0u8.hash(hasher), - } hasher.finish() } diff --git a/packages/ui/ui/src/geometry.rs b/packages/ui/ui/src/geometry.rs index f0d3ac0c8f..0120709cd9 100644 --- a/packages/ui/ui/src/geometry.rs +++ b/packages/ui/ui/src/geometry.rs @@ -8,14 +8,13 @@ use core::fmt::Debug; use derive_more::{Add, AddAssign, Div, DivAssign, Mul, Neg, Sub, SubAssign}; use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; use std::borrow::Cow; -use std::ops::{AddAssign, Range}; +use std::ops::AddAssign; use std::{ cmp::{self, PartialOrd}, fmt::{self, Display}, hash::Hash, ops::{Add, Div, Mul, MulAssign, Neg, Sub}, }; -use taffy::prelude::{TaffyGridLine, TaffyGridSpan}; use crate::{App, DisplayId}; @@ -4590,37 +4589,6 @@ impl From<()> for Length { } } -/// A location in a grid layout. -#[derive(Clone, PartialEq, Debug, Serialize, Deserialize, Default)] -pub struct GridLocation { - /// The rows this item uses within the grid. - pub row: Range, - /// The columns this item uses within the grid. - pub column: Range, -} - -/// The placement of an item within a grid layout's column or row. -#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize, Default)] -pub enum GridPlacement { - /// The grid line index to place this item. - Line(i16), - /// The number of grid lines to span. - Span(u16), - /// Automatically determine the placement, equivalent to Span(1) - #[default] - Auto, -} - -impl From for taffy::GridPlacement { - fn from(placement: GridPlacement) -> Self { - match placement { - GridPlacement::Line(index) => taffy::GridPlacement::from_line_index(index), - GridPlacement::Span(span) => taffy::GridPlacement::from_span(span), - GridPlacement::Auto => taffy::GridPlacement::Auto, - } - } -} - /// Provides a trait for types that can calculate half of their value. /// /// The `Half` trait is used for types that can be evenly divided, returning a new instance of the same type diff --git a/packages/ui/ui/src/platform/wgpu/fast/rounded_clip.rs b/packages/ui/ui/src/platform/wgpu/fast/rounded_clip.rs index 16685d5c79..0abf405b00 100644 --- a/packages/ui/ui/src/platform/wgpu/fast/rounded_clip.rs +++ b/packages/ui/ui/src/platform/wgpu/fast/rounded_clip.rs @@ -251,7 +251,6 @@ pub(crate) fn shader(source: &str) -> String { "fs_underline", "fs_mono_sprite", "fs_poly_sprite", - "fs_surface", "fs_subpixel_sprite", ] { let Some(start) = source.find(&format!("fn {name}(")) else { diff --git a/packages/ui/ui/src/platform/wgpu/shaders.wgsl b/packages/ui/ui/src/platform/wgpu/shaders.wgsl index 1be84a0585..48bc155855 100644 --- a/packages/ui/ui/src/platform/wgpu/shaders.wgsl +++ b/packages/ui/ui/src/platform/wgpu/shaders.wgsl @@ -1412,54 +1412,3 @@ fn fs_poly_sprite(input: PolySpriteVarying) -> @location(0) vec4 { } return blend_color(color, sprite.opacity * saturate(0.5 - distance * scale)); } - -// --- surfaces --- // - -struct SurfaceParams { - bounds: Bounds, - content_mask: Bounds, -} - -@group(1) @binding(0) var surface_locals: SurfaceParams; -@group(1) @binding(1) var t_y: texture_2d; -@group(1) @binding(2) var t_cb_cr: texture_2d; -@group(1) @binding(3) var s_surface: sampler; - -const ycbcr_to_RGB = mat4x4( - vec4( 1.0000f, 1.0000f, 1.0000f, 0.0), - vec4( 0.0000f, -0.3441f, 1.7720f, 0.0), - vec4( 1.4020f, -0.7141f, 0.0000f, 0.0), - vec4(-0.7010f, 0.5291f, -0.8860f, 1.0), -); - -struct SurfaceVarying { - @builtin(position) position: vec4, - @location(0) texture_position: vec2, - @location(3) clip_distances: vec4, -} - -@vertex -fn vs_surface(@builtin(vertex_index) vertex_id: u32) -> SurfaceVarying { - let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); - - var out = SurfaceVarying(); - out.position = to_device_position(unit_vertex, surface_locals.bounds); - out.texture_position = unit_vertex; - out.clip_distances = distance_from_clip_rect(unit_vertex, surface_locals.bounds, surface_locals.content_mask); - return out; -} - -@fragment -fn fs_surface(input: SurfaceVarying) -> @location(0) vec4 { - // Alpha clip after using the derivatives. - if (any(input.clip_distances < vec4(0.0))) { - return vec4(0.0); - } - - let y_cb_cr = vec4( - textureSampleLevel(t_y, s_surface, input.texture_position, 0.0).r, - textureSampleLevel(t_cb_cr, s_surface, input.texture_position, 0.0).rg, - 1.0); - - return ycbcr_to_RGB * y_cb_cr; -} diff --git a/packages/ui/ui/src/platform/wgpu/wgpu_renderer.rs b/packages/ui/ui/src/platform/wgpu/wgpu_renderer.rs index ac2e95a342..019b59a6c4 100644 --- a/packages/ui/ui/src/platform/wgpu/wgpu_renderer.rs +++ b/packages/ui/ui/src/platform/wgpu/wgpu_renderer.rs @@ -68,13 +68,6 @@ impl From> for PodBounds { } } -#[repr(C)] -#[derive(Clone, Copy, Pod, Zeroable)] -struct SurfaceParams { - bounds: PodBounds, - content_mask: PodBounds, -} - #[repr(C)] #[derive(Clone, Copy, Pod, Zeroable)] pub(crate) struct GammaParams { @@ -128,8 +121,6 @@ pub(crate) struct WgpuPipelines { pub(crate) mono_sprites: wgpu::RenderPipeline, pub(crate) subpixel_sprites: Option, pub(crate) poly_sprites: wgpu::RenderPipeline, - #[allow(dead_code)] - surfaces: wgpu::RenderPipeline, } /// One frame allocation of instance data, ready to bind. @@ -157,7 +148,6 @@ pub(crate) struct WgpuBindGroupLayouts { pub(crate) globals: wgpu::BindGroupLayout, pub(crate) instances: wgpu::BindGroupLayout, pub(crate) texture: wgpu::BindGroupLayout, - surfaces: wgpu::BindGroupLayout, } /// Shared GPU context reference, used to coordinate device recovery across multiple windows. @@ -587,56 +577,11 @@ impl WgpuRendererCore { ], }); - let surfaces = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("surfaces_layout"), - entries: &[ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: NonZeroU64::new( - std::mem::size_of::() as u64 - ), - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { filterable: true }, - view_dimension: wgpu::TextureViewDimension::D2, - multisampled: false, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 2, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { filterable: true }, - view_dimension: wgpu::TextureViewDimension::D2, - multisampled: false, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 3, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), - count: None, - }, - ], - }); - WgpuBindGroupLayouts { fast_rounded_clip: crate::platform::wgpu::fast::rounded_clip::Bindings::new(device), globals, instances, texture, - surfaces, } } @@ -943,19 +888,6 @@ impl WgpuRendererCore { &layouts.instances, Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, - &[Some(color_target.clone())], - 1, - &shader_module, - ); - - let surfaces = create_pipeline( - "surfaces", - "vs_surface", - "fs_surface", - &layouts.globals, - &layouts.surfaces, - None, - wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target)], 1, &shader_module, @@ -970,7 +902,6 @@ impl WgpuRendererCore { mono_sprites, subpixel_sprites, poly_sprites, - surfaces, } } diff --git a/packages/ui/ui/src/style.rs b/packages/ui/ui/src/style.rs index 46dc76776a..7edc176c7a 100644 --- a/packages/ui/ui/src/style.rs +++ b/packages/ui/ui/src/style.rs @@ -9,7 +9,7 @@ use crate::refineable::Refineable; use crate::{ AbsoluteLength, App, Background, BackgroundTag, BorderStyle, Bounds, ContentMask, Corners, CornersRefinement, CursorStyle, DefiniteLength, DevicePixels, Edges, EdgesRefinement, Font, - FontFallbacks, FontFeatures, FontStyle, FontWeight, GridLocation, Hsla, Length, Pixels, Point, + FontFallbacks, FontFeatures, FontStyle, FontWeight, Hsla, Length, Pixels, Point, PointRefinement, Rgba, SharedString, Size, SizeRefinement, Styled, TextRun, Window, black, phi, point, px, quad, rems, size, }; @@ -137,137 +137,6 @@ impl ObjectFit { } } -/// The minimum size of a column or row in a grid layout -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Serialize, Deserialize)] -pub enum GridTemplateMinSize { - /// The column or row size may be 0 - #[default] - Zero, - /// The column or row size can be determined by the min content - MinContent, - /// The column or row size can be determined by the max content - MaxContent, -} - -/// A simplified representation of the grid-template-* value -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Serialize, Deserialize)] -pub struct GridTemplate { - /// How this template directive should be repeated - pub repeat: u16, - /// The minimum size in the repeat(<>, minmax(_, 1fr)) equation - pub min_size: GridTemplateMinSize, -} -#[derive(Clone, Default)] -pub struct GridTemplateRefinement { - pub repeat: Option, - pub min_size: Option, -} - -impl crate::refineable::IsEmpty for GridTemplateRefinement { - fn is_empty(&self) -> bool { - let mut empty = true; - { - empty = empty && self.repeat.is_none(); - } - { - empty = empty && self.min_size.is_none(); - } - empty - } -} - -impl crate::refineable::Refineable for GridTemplate { - type Refinement = GridTemplateRefinement; - - fn refine(&mut self, refinement: &Self::Refinement) { - if let Some(ref val) = refinement.repeat { - self.repeat = val.clone(); - } - if let Some(ref val) = refinement.min_size { - self.min_size = val.clone(); - } - } - - fn refined(mut self, refinement: Self::Refinement) -> Self { - self.refine(&refinement); - self - } - - fn is_superset_of(&self, refinement: &Self::Refinement) -> bool { - let mut sup = true; - { - sup = sup && refinement.repeat.as_ref().is_none_or(|v| &self.repeat == v); - } - { - sup = sup - && refinement - .min_size - .as_ref() - .is_none_or(|v| &self.min_size == v); - } - sup - } - - fn subtract(&self, refinement: &Self::Refinement) -> Self::Refinement { - let mut out = GridTemplateRefinement::default(); - if refinement.repeat.as_ref() != Some(&self.repeat) { - out.repeat = Some(self.repeat.clone()); - } - if refinement.min_size.as_ref() != Some(&self.min_size) { - out.min_size = Some(self.min_size.clone()); - } - out - } -} - -impl crate::refineable::Refineable for GridTemplateRefinement { - type Refinement = GridTemplateRefinement; - - fn refine(&mut self, refinement: &Self::Refinement) { - if let Some(ref val) = refinement.repeat { - self.repeat = Some(val.clone()); - } - if let Some(ref val) = refinement.min_size { - self.min_size = Some(val.clone()); - } - } - - fn refined(mut self, refinement: Self::Refinement) -> Self { - self.refine(&refinement); - self - } - - fn is_superset_of(&self, refinement: &Self::Refinement) -> bool { - let mut sup = true; - { - sup = sup - && refinement - .repeat - .as_ref() - .is_none_or(|v| self.repeat.as_ref() == Some(v)); - } - { - sup = sup - && refinement - .min_size - .as_ref() - .is_none_or(|v| self.min_size.as_ref() == Some(v)); - } - sup - } - - fn subtract(&self, refinement: &Self::Refinement) -> Self::Refinement { - let mut out = GridTemplateRefinement::default(); - if self.repeat != refinement.repeat { - out.repeat = self.repeat.clone(); - } - if self.min_size != refinement.min_size { - out.min_size = self.min_size.clone(); - } - out - } -} - /// The CSS styling that can be applied to an element via the `Styled` trait #[derive(Clone, Debug)] pub struct Style { @@ -383,17 +252,6 @@ pub struct Style { /// The opacity of this element pub opacity: Option, - /// The grid columns of this element - /// Roughly equivalent to the Tailwind `grid-cols-` - pub grid_cols: Option, - - /// The row span of this element - /// Equivalent to the Tailwind `grid-rows-` - pub grid_rows: Option, - - /// The grid location of this element - pub grid_location: Option, - /// Inline layout direction inherited along the element tree. pub direction: LayoutDirection, @@ -474,12 +332,6 @@ pub struct StyleRefinement { #[serde(default, skip_serializing_if = "Option::is_none")] pub opacity: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - pub grid_cols: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub grid_rows: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub grid_location: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] pub direction: Option, #[cfg(debug_assertions)] #[serde(default, skip_serializing_if = "Option::is_none")] @@ -591,15 +443,6 @@ impl crate::refineable::IsEmpty for StyleRefinement { { empty = empty && self.opacity.is_none(); } - { - empty = empty && self.grid_cols.is_none(); - } - { - empty = empty && self.grid_rows.is_none(); - } - { - empty = empty && self.grid_location.is_none(); - } { empty = empty && self.direction.is_none(); } @@ -696,15 +539,6 @@ impl crate::refineable::Refineable for Style { if let Some(ref val) = refinement.opacity { self.opacity = Some(val.clone()); } - if let Some(ref val) = refinement.grid_cols { - self.grid_cols = Some(val.clone()); - } - if let Some(ref val) = refinement.grid_rows { - self.grid_rows = Some(val.clone()); - } - if let Some(ref val) = refinement.grid_location { - self.grid_location = Some(val.clone()); - } if let Some(ref val) = refinement.direction { self.direction = *val; } @@ -912,27 +746,6 @@ impl crate::refineable::Refineable for Style { .as_ref() .is_none_or(|v| self.opacity.as_ref() == Some(v)); } - { - sup = sup - && refinement - .grid_cols - .as_ref() - .is_none_or(|v| self.grid_cols.as_ref() == Some(v)); - } - { - sup = sup - && refinement - .grid_rows - .as_ref() - .is_none_or(|v| self.grid_rows.as_ref() == Some(v)); - } - { - sup = sup - && refinement - .grid_location - .as_ref() - .is_none_or(|v| self.grid_location.as_ref() == Some(v)); - } { sup = sup && refinement @@ -1034,15 +847,6 @@ impl crate::refineable::Refineable for Style { if self.opacity != refinement.opacity { out.opacity = self.opacity.clone(); } - if self.grid_cols != refinement.grid_cols { - out.grid_cols = self.grid_cols.clone(); - } - if self.grid_rows != refinement.grid_rows { - out.grid_rows = self.grid_rows.clone(); - } - if self.grid_location != refinement.grid_location { - out.grid_location = self.grid_location.clone(); - } if refinement.direction.as_ref() != Some(&self.direction) { out.direction = Some(self.direction); } @@ -1139,15 +943,6 @@ impl crate::refineable::Refineable for StyleRefinement { if let Some(ref val) = refinement.opacity { self.opacity = Some(val.clone()); } - if let Some(ref val) = refinement.grid_cols { - self.grid_cols = Some(val.clone()); - } - if let Some(ref val) = refinement.grid_rows { - self.grid_rows = Some(val.clone()); - } - if let Some(ref val) = refinement.grid_location { - self.grid_location = Some(val.clone()); - } if let Some(ref val) = refinement.direction { self.direction = Some(*val); } @@ -1355,27 +1150,6 @@ impl crate::refineable::Refineable for StyleRefinement { .as_ref() .is_none_or(|v| self.opacity.as_ref() == Some(v)); } - { - sup = sup - && refinement - .grid_cols - .as_ref() - .is_none_or(|v| self.grid_cols.as_ref() == Some(v)); - } - { - sup = sup - && refinement - .grid_rows - .as_ref() - .is_none_or(|v| self.grid_rows.as_ref() == Some(v)); - } - { - sup = sup - && refinement - .grid_location - .as_ref() - .is_none_or(|v| self.grid_location.as_ref() == Some(v)); - } { sup = sup && refinement @@ -1481,15 +1255,6 @@ impl crate::refineable::Refineable for StyleRefinement { if self.opacity != refinement.opacity { out.opacity = self.opacity.clone(); } - if self.grid_cols != refinement.grid_cols { - out.grid_cols = self.grid_cols.clone(); - } - if self.grid_rows != refinement.grid_rows { - out.grid_rows = self.grid_rows.clone(); - } - if self.grid_location != refinement.grid_location { - out.grid_location = self.grid_location.clone(); - } if self.direction != refinement.direction { out.direction = self.direction; } @@ -1511,13 +1276,6 @@ impl Styled for StyleRefinement { } } -impl StyleRefinement { - /// The grid location of this element - pub fn grid_location_mut(&mut self) -> &mut GridLocation { - self.grid_location.get_or_insert_default() - } -} - /// The value of the visibility property, similar to the CSS property `visibility` #[derive(Default, Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] pub enum Visibility { @@ -2559,9 +2317,6 @@ impl Default for Style { text: TextStyleRefinement::default(), mouse_cursor: None, opacity: None, - grid_rows: None, - grid_cols: None, - grid_location: None, direction: LayoutDirection::Inherit, #[cfg(debug_assertions)] @@ -2989,7 +2744,6 @@ impl From for HighlightStyle { /// Used to control how child nodes are aligned. /// For Flexbox it controls alignment in the cross axis -/// For Grid it controls alignment in the block axis /// /// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items) #[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] @@ -3016,30 +2770,15 @@ pub enum AlignItems { /// Stretch to fill the container Stretch, } -/// Used to control how child nodes are aligned. -/// Does not apply to Flexbox, and will be ignored if specified on a flex container -/// For Grid it controls alignment in the inline axis -/// -/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items) -pub type JustifyItems = AlignItems; /// Used to control how the specified nodes is aligned. /// Overrides the parent Node's `AlignItems` property. /// For Flexbox it controls alignment in the cross axis -/// For Grid it controls alignment in the block axis /// /// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-self) pub type AlignSelf = AlignItems; -/// Used to control how the specified nodes is aligned. -/// Overrides the parent Node's `JustifyItems` property. -/// Does not apply to Flexbox, and will be ignored if specified on a flex child -/// For Grid it controls alignment in the inline axis -/// -/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self) -pub type JustifySelf = AlignItems; /// Sets the distribution of space between and around content items /// For Flexbox it controls alignment in the cross axis -/// For Grid it controls alignment in the block axis /// /// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-content) #[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] @@ -3076,14 +2815,13 @@ pub enum AlignContent { /// Sets the distribution of space between and around content items /// For Flexbox it controls alignment in the main axis -/// For Grid it controls alignment in the inline axis /// /// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content) pub type JustifyContent = AlignContent; /// Sets the layout used for the children of this node /// -/// The default values depends on on which feature flags are enabled. The order of precedence is: Flex, Grid, Block, None. +/// The default values depends on on which feature flags are enabled. The order of precedence is: Flex, Block, None. #[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)] // Copy of taffy::style type of the same name, to derive JsonSchema. pub enum Display { @@ -3092,8 +2830,6 @@ pub enum Display { /// The children will follow the flexbox layout algorithm #[default] Flex, - /// The children will follow the CSS Grid layout algorithm - Grid, /// The children will not be laid out, and will follow absolute positioning None, } @@ -3154,7 +2890,7 @@ pub enum FlexDirection { /// be displayed anyway, be clipped, or trigger the container to become a scroll container. However it also has secondary effects on layout, /// the main ones being: /// -/// - The automatic minimum size Flexbox/CSS Grid items with non-`Visible` overflow is `0` rather than being content based +/// - The automatic minimum size of Flexbox items with non-`Visible` overflow is `0` rather than being content based /// - `Overflow::Scroll` nodes have space in the layout reserved for a scrollbar (width controlled by the `scrollbar_width` property) /// /// In Taffy, we only implement the layout related secondary effects as we are not concerned with drawing/painting. The amount of space reserved for @@ -3164,17 +2900,17 @@ pub enum FlexDirection { #[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)] // Copy of taffy::style type of the same name, to derive JsonSchema. pub enum Overflow { - /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content. + /// The automatic minimum size of this node as a flexbox item should be based on the size of its content. /// Content that overflows this node *should* contribute to the scroll region of its parent. #[default] Visible, - /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content. + /// The automatic minimum size of this node as a flexbox item should be based on the size of its content. /// Content that overflows this node should *not* contribute to the scroll region of its parent. Clip, - /// The automatic minimum size of this node as a flexbox/grid item should be `0`. + /// The automatic minimum size of this node as a flexbox item should be `0`. /// Content that overflows this node should *not* contribute to the scroll region of its parent. Hidden, - /// The automatic minimum size of this node as a flexbox/grid item should be `0`. Additionally, space should be reserved + /// The automatic minimum size of this node as a flexbox item should be `0`. Additionally, space should be reserved /// for a scrollbar. The amount of space reserved is controlled by the `scrollbar_width` property. /// Content that overflows this node should *not* contribute to the scroll region of its parent. Scroll, @@ -3239,7 +2975,6 @@ impl From for taffy::style::Display { match value { Display::Block => Self::Block, Display::Flex => Self::Flex, - Display::Grid => Self::Grid, Display::None => Self::None, } } diff --git a/packages/ui/ui/src/styled.rs b/packages/ui/ui/src/styled.rs index cb37e1ffc8..cf514fc4e0 100644 --- a/packages/ui/ui/src/styled.rs +++ b/packages/ui/ui/src/styled.rs @@ -1,9 +1,8 @@ use crate::{ self as gpui, AbsoluteLength, AlignContent, AlignItems, AlignSelf, BorderStyle, CursorStyle, DefiniteLength, Display, Fill, FlexDirection, FlexWrap, Font, FontFeatures, FontStyle, - FontWeight, GridPlacement, GridTemplate, GridTemplateMinSize, Hsla, JustifyContent, Length, - SharedString, StrikethroughStyle, StyleRefinement, TextAlign, TextOverflow, - TextStyleRefinement, UnderlineStyle, WhiteSpace, px, relative, rems, + FontWeight, Hsla, JustifyContent, Length, SharedString, StrikethroughStyle, StyleRefinement, + TextAlign, TextOverflow, TextStyleRefinement, UnderlineStyle, WhiteSpace, px, relative, rems, }; use smallvec::SmallVec; const ELLIPSIS: SharedString = SharedString::new_static("…"); @@ -341,13 +340,6 @@ pub trait Styled: Sized { self } - /// Sets the display type of the element to `grid`. - /// [Docs](https://tailwindcss.com/docs/display) - fn grid(mut self) -> Self { - self.style().display = Some(Display::Grid); - self - } - /// Sets the display type of the element to `none`. /// [Docs](https://tailwindcss.com/docs/display) fn hidden(mut self) -> Self { @@ -602,38 +594,6 @@ pub trait Styled: Sized { self } - /// Sets the grid columns of this element. - fn grid_cols(mut self, cols: u16) -> Self { - self.style().grid_cols = Some(GridTemplate { - repeat: cols, - min_size: GridTemplateMinSize::Zero, - }); - self - } - - /// Sets the grid rows of this element. - fn grid_rows(mut self, rows: u16) -> Self { - self.style().grid_rows = Some(GridTemplate { - repeat: rows, - min_size: GridTemplateMinSize::Zero, - }); - self - } - - /// Sets the row start of this element. - fn row_start(mut self, start: i16) -> Self { - let grid_location = self.style().grid_location_mut(); - grid_location.row.start = GridPlacement::Line(start); - self - } - - /// Sets the row end of this element. - fn row_end(mut self, end: i16) -> Self { - let grid_location = self.style().grid_location_mut(); - grid_location.row.end = GridPlacement::Line(end); - self - } - /// Draws a debug border around this element. #[cfg(debug_assertions)] fn debug(mut self) -> Self { diff --git a/packages/ui/ui/src/taffy.rs b/packages/ui/ui/src/taffy.rs index 735c6ea4a9..1ba85563f5 100644 --- a/packages/ui/ui/src/taffy.rs +++ b/packages/ui/ui/src/taffy.rs @@ -1,17 +1,16 @@ use crate::collections::FxHashSet; use crate::{ - AbsoluteLength, App, Bounds, DefiniteLength, Edges, GridTemplate, Length, Pixels, Point, Size, - Style, Window, size, + AbsoluteLength, App, Bounds, DefiniteLength, Edges, Length, Pixels, Point, Size, Style, Window, + size, util::{ ceil_to_device_pixel, round_half_toward_zero, round_stroke_to_device_pixel, round_to_device_pixel, }, }; -use std::{fmt::Debug, ops::Range}; +use std::fmt::Debug; use taffy::{ TaffyTree, TraversePartialTree as _, geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize}, - prelude::{max_content, min_content}, style::AvailableSpace as TaffyAvailableSpace, tree::NodeId, }; @@ -251,7 +250,7 @@ impl TaffyLayoutEngine { // to integer device-pixel lengths. // // 2. Post-layout edge snapping. After Taffy resolves the tree, layout - // relationships such as flex shares, grid tracks, percentages, and + // relationships such as flex shares, percentages, and // centering can produce new fractional edge positions. Boxes now // have edges in absolute coordinates, and snapping must decide // where those edges land on the device-pixel grid. @@ -392,48 +391,6 @@ pub(crate) trait ToTaffy { impl ToTaffy for Style { fn to_taffy(&self, rem_size: Pixels, scale_factor: f32) -> taffy::style::Style { - use taffy::style_helpers::{fr, length, minmax, repeat}; - - fn to_grid_line( - placement: &Range, - ) -> taffy::Line { - taffy::Line { - start: placement.start.into(), - end: placement.end.into(), - } - } - - fn to_grid_repeat( - unit: &Option, - ) -> Vec> { - unit.map(|template| { - match template.min_size { - // grid-template-*: repeat(, minmax(0, 1fr)); - crate::GridTemplateMinSize::Zero => { - vec![repeat( - template.repeat, - vec![minmax(length(0.0_f32), fr(1.0_f32))], - )] - } - // grid-template-*: repeat(, minmax(min-content, 1fr)); - crate::GridTemplateMinSize::MinContent => { - vec![repeat( - template.repeat, - vec![minmax(min_content(), fr(1.0_f32))], - )] - } - // grid-template-*: repeat(, minmax(0, max-content)) - crate::GridTemplateMinSize::MaxContent => { - vec![repeat( - template.repeat, - vec![minmax(length(0.0_f32), max_content())], - )] - } - } - }) - .unwrap_or_default() - } - taffy::style::Style { display: self.display.into(), direction: match self.direction { @@ -463,18 +420,6 @@ impl ToTaffy for Style { flex_basis: self.flex_basis.to_taffy(rem_size, scale_factor), flex_grow: self.flex_grow, flex_shrink: self.flex_shrink, - grid_template_rows: to_grid_repeat(&self.grid_rows), - grid_template_columns: to_grid_repeat(&self.grid_cols), - grid_row: self - .grid_location - .as_ref() - .map(|location| to_grid_line(&location.row)) - .unwrap_or_default(), - grid_column: self - .grid_location - .as_ref() - .map(|location| to_grid_line(&location.column)) - .unwrap_or_default(), ..Default::default() } }