diff --git a/.github/workflows/native-playground.yml b/.github/workflows/native-playground.yml index f227fbdd38..5a3be785f0 100644 --- a/.github/workflows/native-playground.yml +++ b/.github/workflows/native-playground.yml @@ -73,9 +73,36 @@ jobs: - '.github/actions/setup-node/**' - '.github/workflows/np-web-fast.yml' web-build: - - 'packages/frontend/**' - - 'packages/common/**' - - 'blocksuite/**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,css,json}' + - 'packages/frontend/admin/**' + - 'packages/frontend/apps/**' + - 'packages/frontend/component/**' + - 'packages/frontend/core/**' + - 'packages/frontend/electron-api/**' + - 'packages/frontend/i18n/**' + - 'packages/frontend/mobile-native/**' + - 'packages/frontend/native/**' + - 'packages/frontend/routes/**' + - 'packages/frontend/templates/**' + - 'packages/frontend/track/**' + - 'packages/common/auth/**' + - 'packages/common/debug/**' + - 'packages/common/env/**' + - 'packages/common/error/**' + - 'packages/common/graphql/**' + - 'packages/common/infra/**' + - 'packages/common/native/**' + - 'packages/common/nbstore/**' + - 'packages/common/reader/**' + - 'packages/common/realtime/**' + - 'packages/common/s3-compat/**' + - 'packages/common/theme/**' + - 'blocksuite/affine/**' + - 'blocksuite/framework/**' + - 'blocksuite/playground/**' + - 'blocksuite/integration-test/**' + - 'blocksuite/docs/**' + - 'blocksuite/docs-site/**' + - 'blocksuite/tsconfig.json' - 'tools/cli/**' - '**/package.json' - '**/tsconfig*.json' @@ -176,6 +203,8 @@ jobs: --select server-mail --select server-blob --select server-sync \ --select server-http --select server-worker --select affine-server "${timings[@]}" cat ../../.artifacts/server-harness/run.json + test -s ../../.artifacts/server-harness/run.json + test -s ../../.artifacts/csf-frame-audit/frames.json test "$status" = passed - name: Upload run report @@ -193,7 +222,7 @@ jobs: runs-on: ubuntu-24.04 defaults: run: - working-directory: blocksuite/native-playground + working-directory: packages/frontend steps: - name: Checkout repository uses: actions/checkout@v4 @@ -212,7 +241,7 @@ jobs: - name: Cache Cargo artifacts uses: Swatinem/rust-cache@v2 with: - workspaces: blocksuite/native-playground -> target + workspaces: packages/frontend -> target key: lint-wasm - name: Format check @@ -227,8 +256,8 @@ jobs: - name: Perf guardrail self-tests and generated token/icon unit tests run: | node --test perf/compare-n3.test.mjs - rustc --edition 2024 --test -D warnings tokens/tokens.rs -o /tmp/tokens_test && /tmp/tokens_test - rustc --edition 2024 --test -D warnings tokens/icons.rs -o /tmp/icons_test && /tmp/icons_test + rustc --edition 2024 --test -D warnings ../ui/tokens/tokens.rs -o /tmp/tokens_test && /tmp/tokens_test + rustc --edition 2024 --test -D warnings ../ui/tokens/icons.rs -o /tmp/icons_test && /tmp/icons_test rm -f /tmp/tokens_test /tmp/icons_test - name: Verify generated tokens, icons, and fonts.lock have zero drift @@ -241,7 +270,7 @@ jobs: | tar -xz --strip-components=1 -C /tmp/np-token-deps/node_modules/@toeverything/theme curl -fsSL "https://registry.npmjs.org/@blocksuite/icons/-/icons-${ICONS_VER}.tgz" \ | tar -xz --strip-components=1 -C /tmp/np-token-deps/node_modules/@blocksuite/icons - node tokens/extract-tokens.mjs --check --node-modules /tmp/np-token-deps/node_modules + node ../ui/tokens/extract-tokens.mjs --check --node-modules /tmp/np-token-deps/node_modules rm -rf /tmp/np-token-deps - name: Check WebAssembly target @@ -254,7 +283,7 @@ jobs: runs-on: ubuntu-24.04 defaults: run: - working-directory: blocksuite/native-playground + working-directory: packages/frontend steps: - name: Checkout repository uses: actions/checkout@v4 @@ -284,7 +313,7 @@ jobs: - name: Cache Cargo artifacts uses: Swatinem/rust-cache@v2 with: - workspaces: blocksuite/native-playground -> target + workspaces: packages/frontend -> target key: headless-linux - name: Run workspace unit tests (default and harness) @@ -294,16 +323,18 @@ jobs: - name: Build WebAssembly bundle and run headless Chromium smoke test run: | - mkdir -p artifacts web/pkg + mkdir -p artifacts ../../blocksuite/crates/playground/web/pkg cargo build --locked -p playground --target wasm32-unknown-unknown --release - wasm-bindgen --target web --out-dir web/pkg target/wasm32-unknown-unknown/release/playground.wasm - WASM_RAW=$(wc -c < web/pkg/playground_bg.wasm | tr -d ' ') - WASM_GZIP=$(gzip -9 -c web/pkg/playground_bg.wasm | wc -c | tr -d ' ') + wasm-bindgen --target web --out-dir ../../blocksuite/crates/playground/web/pkg target/wasm32-unknown-unknown/release/playground.wasm + WASM_RAW=$(wc -c < ../../blocksuite/crates/playground/web/pkg/playground_bg.wasm | tr -d ' ') + WASM_GZIP=$(gzip -9 -c ../../blocksuite/crates/playground/web/pkg/playground_bg.wasm | wc -c | tr -d ' ') echo "WASM_RAW=$WASM_RAW" >> "$GITHUB_ENV" echo "WASM_GZIP=$WASM_GZIP" >> "$GITHUB_ENV" node scripts/web-smoke.mjs \ --out artifacts/wasm-chromium.png \ --out-edgeless artifacts/wasm-chromium-edgeless.png + test -s artifacts/wasm-chromium.png + test -s artifacts/wasm-chromium-edgeless.png - name: Deterministic headless render, audit, 4-fps check, and 30-frame bench run: | @@ -318,6 +349,8 @@ jobs: --snapshot artifacts/linux-run2.json \ --width 1280 \ --height 800 + test -s artifacts/linux-run1.png + test -s artifacts/linux-run1.json sha1=$(sha256sum artifacts/linux-run1.png | awk '{print $1}') sha2=$(sha256sum artifacts/linux-run2.png | awk '{print $1}') echo "Run 1 SHA256: $sha1" @@ -331,24 +364,55 @@ jobs: --commit "${{ github.sha }}" \ --web-wasm-raw "$WASM_RAW" \ --web-wasm-gzip "$WASM_GZIP" + test -s artifacts/perf-metrics.json - name: Compare against rolling N-3 baseline env: GH_TOKEN: ${{ github.token }} run: | - if [ -f perf/compare-n3.mjs ]; then - node perf/compare-n3.mjs \ - --fetch-github \ - --repo "${{ github.repository }}" \ - --branch darksky/native-playground \ - --workflow native-playground.yml \ - --run-id "${{ github.run_id }}" \ - --current artifacts/perf-metrics.json \ - --json-out artifacts/perf-verdict.json \ - --fail-on-regression >> "$GITHUB_STEP_SUMMARY" - else - echo "No perf/compare-n3.mjs present; skipping N-3 comparison." >> "$GITHUB_STEP_SUMMARY" + test -f perf/compare-n3.mjs + STRICT_PERF_FLAG="--require-n3" + if [ "${NP_ALLOW_PERF_BOOTSTRAP:-0}" = "1" ]; then + STRICT_PERF_FLAG="" fi + node perf/compare-n3.mjs \ + --fetch-github \ + --repo "${{ github.repository }}" \ + --branch darksky/native-playground \ + --workflow native-playground.yml \ + --run-id "${{ github.run_id }}" \ + --current artifacts/perf-metrics.json \ + --json-out artifacts/perf-verdict.json \ + $STRICT_PERF_FLAG \ + --fail-on-regression >> "$GITHUB_STEP_SUMMARY" + test -s artifacts/perf-verdict.json + node -e ' + const fs = require("node:fs"); + const v = JSON.parse(fs.readFileSync("artifacts/perf-verdict.json", "utf8")); + const allowBootstrap = process.env.NP_ALLOW_PERF_BOOTSTRAP === "1"; + const shaRe = /^[0-9a-f]{40}$/; + if ( + (!allowBootstrap && (v.baseline_depth !== "N-3" || !shaRe.test(v.baseline_commit || ""))) || + (allowBootstrap && v.baseline_depth !== "bootstrap" && !shaRe.test(v.baseline_commit || "")) || + !Array.isArray(v.metrics) || + v.metrics.length === 0 + ) { + throw new Error(`Invalid perf-verdict.json: baseline_depth=${v.baseline_depth}, baseline_commit=${v.baseline_commit}, metrics=${v.metrics?.length}`); + } + const dropped = v.metrics.filter(m => m.status === "DROPPED"); + if (dropped.length > 0) { + throw new Error(`Unacknowledged dropped baseline metrics: ${dropped.map(m => m.key).join(", ")}`); + } + const unacceptedBootstrap = v.metrics.filter(m => m.status === "BOOTSTRAP"); + if (!allowBootstrap && unacceptedBootstrap.length > 0) { + throw new Error(`Unacknowledged BOOTSTRAP metrics against N-3 baseline: ${unacceptedBootstrap.map(m => m.key).join(", ")}`); + } + const compared = v.metrics.filter(m => m.baseline != null && m.current != null); + if (!allowBootstrap && compared.length === 0) { + throw new Error("No metrics were compared against prior N-3 baseline history"); + } + console.log(`perf-verdict.json verified: ${v.baseline_depth} (${(v.baseline_commit || "none").slice(0, 10)}), ${v.metrics.length} metrics, ${unacceptedBootstrap.length} unacknowledged bootstrap, 0 dropped`); + ' - name: Upload perf metrics artifact if: always() @@ -356,8 +420,8 @@ jobs: with: name: perf-metrics path: | - blocksuite/native-playground/artifacts/perf-metrics.json - blocksuite/native-playground/artifacts/perf-verdict.json + packages/frontend/artifacts/perf-metrics.json + packages/frontend/artifacts/perf-verdict.json if-no-files-found: ignore - name: Upload Linux headless and Web smoke artifacts @@ -366,10 +430,10 @@ jobs: with: name: headless-linux-artifacts path: | - blocksuite/native-playground/artifacts/linux-run1.png - blocksuite/native-playground/artifacts/linux-run1.json - blocksuite/native-playground/artifacts/wasm-chromium.png - blocksuite/native-playground/artifacts/wasm-chromium-edgeless.png + packages/frontend/artifacts/linux-run1.png + packages/frontend/artifacts/linux-run1.json + packages/frontend/artifacts/wasm-chromium.png + packages/frontend/artifacts/wasm-chromium-edgeless.png if-no-files-found: ignore macos-headless: @@ -377,7 +441,7 @@ jobs: runs-on: macos-15 defaults: run: - working-directory: blocksuite/native-playground + working-directory: packages/frontend steps: - name: Checkout repository uses: actions/checkout@v4 @@ -388,7 +452,7 @@ jobs: - name: Cache Cargo artifacts uses: Swatinem/rust-cache@v2 with: - workspaces: blocksuite/native-playground -> target + workspaces: packages/frontend -> target key: macos-headless - name: Check workspace all targets @@ -412,6 +476,8 @@ jobs: --snapshot artifacts/macos-run2.json \ --width 1280 \ --height 800 + test -s artifacts/macos-run1.png + test -s artifacts/macos-run1.json sha1=$(shasum -a 256 artifacts/macos-run1.png | awk '{print $1}') sha2=$(shasum -a 256 artifacts/macos-run2.png | awk '{print $1}') echo "Run 1 SHA256: $sha1" @@ -424,8 +490,9 @@ jobs: with: name: headless-macos-artifacts path: | - blocksuite/native-playground/artifacts/macos-run1.png - blocksuite/native-playground/artifacts/macos-run1.json + packages/frontend/artifacts/macos-run1.png + packages/frontend/artifacts/macos-run1.json + if-no-files-found: error js-room-coop: name: JS Room Coop & Rust-JS E2E @@ -461,15 +528,15 @@ jobs: - name: Cache Cargo artifacts uses: Swatinem/rust-cache@v2 with: - workspaces: blocksuite/native-playground -> target + workspaces: packages/frontend -> target key: js-room-coop - name: Build bs-relay and bs_doc_driver - working-directory: blocksuite/native-playground + working-directory: packages/frontend run: cargo build --locked -p blocksuite-playground-doc --bin bs-relay --example bs_doc_driver - name: Verify JS-authored surface snapshots without writeback - working-directory: blocksuite/native-playground + working-directory: packages/frontend run: cargo test --locked -p blocksuite-playground-doc --example bs_doc_driver js_authored_surface - name: Lint, format, and typecheck JS room sync @@ -500,8 +567,8 @@ jobs: - name: Verify surface geometry oracle and live Rust-JS room sync env: - BS_RELAY_BIN: ${{ github.workspace }}/blocksuite/native-playground/target/debug/bs-relay - BS_DOC_DRIVER_BIN: ${{ github.workspace }}/blocksuite/native-playground/target/debug/examples/bs_doc_driver + BS_RELAY_BIN: ${{ github.workspace }}/packages/frontend/target/debug/bs-relay + BS_DOC_DRIVER_BIN: ${{ github.workspace }}/packages/frontend/target/debug/examples/bs_doc_driver run: | (cd blocksuite/framework/sync && ../../../node_modules/.bin/vitest run) (cd blocksuite/playground && ../../node_modules/.bin/vitest run) diff --git a/.gitignore b/.gitignore index e1234d867d..8fc6e66fc4 100644 --- a/.gitignore +++ b/.gitignore @@ -104,3 +104,6 @@ storageState.json /.playwright-browsers/ **/.vitest-attachments/ /blocksuite/framework/std/src/__tests__/gfx/__screenshots__/ +/packages/frontend/target/ +/packages/frontend/artifacts/ +/blocksuite/crates/playground/web/pkg/ diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 0fd2b803b7..fd36a88d85 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -6,5 +6,9 @@ "tabWidth": 2, "arrowParens": "avoid", "sortPackageJson": false, - "ignorePatterns": ["**/*.toml"] + "ignorePatterns": [ + "**/*.toml", + "packages/frontend/artifacts/**", + "blocksuite/crates/playground/web/pkg/**" + ] } diff --git a/.oxlintrc.json b/.oxlintrc.json index d16d19a263..bcaddc2ab5 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -43,6 +43,7 @@ ".vscode", ".context", ".codex", + ".agents", ".yarnrc.yml", ".docker", "**/.storybook", @@ -73,7 +74,11 @@ "tests/oracle-contracts/**", "packages/backend/server-types/assets/*.license.json", "packages/backend/native/src/*.license.json", - "blocksuite/native-playground/**", + "packages/ui/**", + "packages/frontend/perf/**", + "packages/frontend/scripts/**", + "packages/frontend/artifacts/**", + "blocksuite/crates/**", "blocksuite/docs/api/**", "blocksuite/docs-site/.vitepress/.temp/**", "blocksuite/docs-site/api/**", diff --git a/.prettierignore b/.prettierignore index 484bc31262..5d8b7db3ed 100644 --- a/.prettierignore +++ b/.prettierignore @@ -43,7 +43,11 @@ tests/blocksuite/snapshots tests/oracle-contracts/** packages/backend/server-types/assets/*.license.json packages/backend/native/src/*.license.json -blocksuite/native-playground/** +packages/ui/** +packages/frontend/perf/** +packages/frontend/scripts/** +packages/frontend/artifacts/** +blocksuite/crates/** blocksuite/docs/api/** blocksuite/docs-site/.vitepress/.temp/** blocksuite/docs-site/api/** diff --git a/AGENTS.md b/AGENTS.md index faf0ed7039..3a7dbed4c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # Working on AFFiNE Native Playground (for agents) -These rules apply at the repository root on the `darksky/native-playground` branch and on topic branches under `darksky/np/**`. Subdirectory `AGENTS.md` files (for example `blocksuite/native-playground/AGENTS.md`) give narrower rules beside the code they govern. +These rules apply at the repository root on the `darksky/native-playground` branch and on topic branches under `darksky/np/**`. Subdirectory `AGENTS.md` files (for example `packages/frontend/AGENTS.md`, `packages/ui/AGENTS.md`, and `blocksuite/crates/AGENTS.md`) give narrower rules beside the code they govern. ## Branch and CI workflow @@ -12,7 +12,7 @@ These rules apply at the repository root on the `darksky/native-playground` bran - **Performance regression gate:** A CI benchmark metric can regress by **more than 10%** against the rolling `N-3` baseline. In that case, the performance guardian reviews the change before it lands. -- **Cargo rustflags isolation:** Root `.cargo/config.toml` adds NAPI linker flags (`-all_load`, `-undefined dynamic_lookup`, `-z nodelete`). Cargo joins these flags into nested workspaces. Always set `CARGO_ENCODED_RUSTFLAGS=""` when you build and test `blocksuite/native-playground` and the standalone `packages/backend/` workspace. +- **Cargo rustflags isolation:** Root `.cargo/config.toml` adds NAPI linker flags (`-all_load`, `-undefined dynamic_lookup`, `-z nodelete`). Cargo joins these flags into nested workspaces. Always set `CARGO_ENCODED_RUSTFLAGS=""` when you build and test `packages/frontend/` and the standalone `packages/backend/` workspace. - **Static gates:** `node scripts/ci/check-l0-tier-a.mjs` has no dependencies and runs in under a second. It guards the `packages/backend/` layering and hygiene. It also guards workflow references and the `waitForTimeout` / `.skip` ratchet in `scripts/ci/l0-ratchet.json`. The ratchet counts can only go down. To lower the ceiling, run the script with `--update-baseline`. diff --git a/blocksuite/native-playground/AGENTS.md b/blocksuite/crates/AGENTS.md similarity index 64% rename from blocksuite/native-playground/AGENTS.md rename to blocksuite/crates/AGENTS.md index 462a95dc30..e5ccc5a7ac 100644 --- a/blocksuite/native-playground/AGENTS.md +++ b/blocksuite/crates/AGENTS.md @@ -1,33 +1,19 @@ -# Working in `blocksuite/native-playground` (for agents) +# Working in `blocksuite/crates/` (for agents) -This document records the active engineering invariants enforced in CI today alongside the planned contracts for upcoming crates and editor features. +`blocksuite/crates/` holds the pure BlockSuite CRDT document engine (`doc/`), the standalone playground application (`playground/`), and browser geometry/style oracle fixtures (`oracle/`). +These crates belong to the client Cargo workspace rooted at `packages/frontend/Cargo.toml`. ## Active Invariants (enforced now) ### Workspace boundaries -- `crates/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 (`scripts/check-invariants.sh` rejects `blocksuite` and `affine` inside `crates/ui`) and embeds zero fonts (fonts are registered by the application via `cx.text_system().add_fonts(...)`). -- `crates/doc` (`blocksuite-playground-doc`) & `bs-relay`: Pure CRDT document engine and binary room sync relay (`#![forbid(unsafe_code)]`, zero GUI/platform dependencies, `scripts/check-invariants.sh` rejects `ui`, `wgpu`, `objc2`, and `web-sys` in `crates/doc/Cargo.toml`) built on `y-octo 0.4.0`. Preserves 53-bit `clientId` (`1..=2^53 - 1`), complete flavour schema defaults (`schema/`, 0 JS writeback updates on initial load), top-level Awareness `color` alongside `user` and `selectionV2`, deterministic `now_ms`-driven undo/awareness clocks (`session/`), WebSocket-only `seed-claim` / `seed-claim-result` single-winner arbitration (keyed by `seed:`), awareness refcounting across connections that forwards a removal (including the equal-clock live-to-`null` form `y-protocols` uses to expire a peer) once the last owner releases a client, `?ws=` relay origin forwarding with permissive blob CORS headers, and `wasm32-unknown-unknown` compatibility under `--no-default-features`. `read/` (`PageDocSession::read_page_snapshot`) is the typed read side: an ordered `PageSnapshot` tree of `BlockNode`s whose `BlockContent` covers every supported block flavour, keeps the normalized JSON of every `prop:*`, numbers `numbered` list runs, reads `prop:textAlign` and the note display modes by their BlockSuite wire values (`both` / `doc` / `edgeless`), reports blocks outside the root tree as `detached`, and reads any other flavour as `Unknown` instead of dropping it. -- `crates/playground`: Application layer owning the shipping `PlaygroundView` (`lib.rs`, `chrome.rs`, `view_room.rs`), the tracked repository font registration (`Inter` and the four `IBM Plex Mono` faces), the native macOS desktop entry (`native-playground`), the WebAssembly canvas entry (`wasm_main`), and the deterministic headless verification CLI (`src/bin/bs_harness/`). `theme.rs` resolves colors, typography and icons from the generated `tokens/tokens.rs` / `tokens/icons.rs` (pulled in with `include!`, never copied and never reformatted) for `PlaygroundTheme::{Light, Dark}`; `block_flow/` is the Page-mode renderer; `rich_text/` is the rich paragraph engine; `editor_session/` and `clipboard/` are the page editor; `overlays/` holds the popovers and the interactive block controls; `room_client/` is live room sync; `showcase.rs` seeds the deterministic `seed_showcase_doc` workspace shown without a room (every Page-mode block, one image blob, one remote collaborator). +- `blocksuite/crates/doc` (`blocksuite-playground-doc`) & `bs-relay`: Pure CRDT document engine and binary room sync relay (`#![forbid(unsafe_code)]`, zero GUI/platform dependencies, `packages/frontend/scripts/check-invariants.sh` rejects `ui`, `wgpu`, `objc2`, and `web-sys` in `blocksuite/blocksuite/crates/doc/Cargo.toml`) built on `y-octo 0.4.0`. Preserves 53-bit `clientId` (`1..=2^53 - 1`), complete flavour schema defaults (`schema/`, 0 JS writeback updates on initial load), top-level Awareness `color` alongside `user` and `selectionV2`, deterministic `now_ms`-driven undo/awareness clocks (`session/`), WebSocket-only `seed-claim` / `seed-claim-result` single-winner arbitration (keyed by `seed:`), awareness refcounting across connections that forwards a removal (including the equal-clock live-to-`null` form `y-protocols` uses to expire a peer) once the last owner releases a client, `?ws=` relay origin forwarding with permissive blob CORS headers, and `wasm32-unknown-unknown` compatibility under `--no-default-features`. `read/` (`PageDocSession::read_page_snapshot`) is the typed read side: an ordered `PageSnapshot` tree of `BlockNode`s whose `BlockContent` covers every supported block flavour, keeps the normalized JSON of every `prop:*`, numbers `numbered` list runs, reads `prop:textAlign` and the note display modes by their BlockSuite wire values (`both` / `doc` / `edgeless`), reports blocks outside the root tree as `detached`, and reads any other flavour as `Unknown` instead of dropping it. +- `blocksuite/crates/playground`: Application layer owning the shipping `PlaygroundView` (`lib.rs`, `chrome.rs`, `view_room.rs`), the tracked repository font registration (`Inter` and the four `IBM Plex Mono` faces), the native macOS desktop entry (`native-playground`), the WebAssembly canvas entry (`wasm_main`), and the deterministic headless verification CLI (`src/bin/bs_harness/`). `theme.rs` resolves colors, typography and icons from the generated `packages/ui/tokens/tokens.rs` / `packages/ui/tokens/icons.rs` (pulled in with `include!`, never copied and never reformatted) for `PlaygroundTheme::{Light, Dark}`; `block_flow/` is the Page-mode renderer; `rich_text/` is the rich paragraph engine; `editor_session/` and `clipboard/` are the page editor; `overlays/` holds the popovers and the interactive block controls; `room_client/` is live room sync; `showcase.rs` seeds the deterministic `seed_showcase_doc` workspace shown without a room (every Page-mode block, one image blob, one remote collaborator). - `unexpected_cfgs = "deny"` is enforced workspace-wide in `Cargo.toml`; dead upstream feature gates are forbidden. - -### Platform matrix -`crates/ui` compiles cleanly across three targets from one crate: -- **macOS (`target_os = "macos"`)**: AppKit + Metal + CoreText, including windowless `MetalHeadlessRenderer` readback, full mip-0 `MetalAtlas` zero-init, and offscreen `MacWindow` frame/scale fallbacks. -- **Linux Headless (`target_os = "linux"`)**: `wgpu` + `cosmic-text` via `WgpuHeadlessRenderer` on Mesa `lavapipe` for deterministic software rasterization in CI. -- **Web (`target_family = "wasm"`)**: Single-threaded `wasm32-unknown-unknown` + WebGPU/WebGL2 + `CanvasFontFallback` + block-scoped `ImeMirror` (no `wasm_thread`, no `http_client`), verified in headless Chromium via `scripts/web-smoke.mjs` (`--query` loads the page with a query string such as a live room, `--min-title-ink` waits for that much page ink before capturing; without a query it also drives composition across blocks and composition and paste in the toolbar's link field through the hidden textarea). - -### Determinism, single clock, and zero tester branches -- **Single UI execution path**: Headless shell rendering (`bs-harness render`), desktop (`main.rs`), and Web (`wasm_main`) all instantiate and render the exact same shipping `PlaygroundView` through `Application::with_platform(...)` and `Window::draw()`. -- **No wall clock outside `crates/ui/src/platform/`**: `Instant::now()` and `SystemTime::now()` are forbidden anywhere outside `crates/ui/src/platform/` (`scripts/check-invariants.sh`). Host thread-park deadlines read monotonic time in `crates/ui/src/platform/clock.rs`; animations and transitions read the scheduler clock (`cx.background_executor().now()`, backed by `TestScheduler` in headless/test runs and the platform scheduler in desktop/web). -- **Motion is pure data**: Transitions are declared once as `(from, to, curve, start_ms, duration_ms)` and evaluated as a pure function of scheduler time. Never write frame-by-frame recurrence loops or `sleep` waits. -- **Zero tester branches**: Application and layout logic never inspect `is_headless` or inline `#[cfg(any(test, feature = "harness"))]` to alter behavior (`scripts/check-invariants.sh`). -- **Four-rate replay invariance**: Stepped `PlaygroundView` transitions (the mode switch, the slash menu and the formatting toolbar opening and closing) must progress monotonically with in-flight frames and produce byte-identical terminal `FrameSnapshot` JSON at `60`, `120`, `24`, and `7` fps (`bs-harness fps-check`). -- **Callsite tracing**: Under the `harness` feature, `InteractiveElement::snapshot(...)` records post-layout bounds, `content_mask`, interactivity, focus, and `#[track_caller]` `file:line` origins into `Window::frame_snapshot()` for `sources_at(x, y)` and `bs-harness audit`. The snapshot schema and the audit rules are the repository's `tools/frame-audit` (a `serde`-only path dependency of `crates/ui`, re-exported from `ui::harness`). Change them there and keep both workspaces' tests green. Non-harness release builds compile to no-op stubs. -- **Locked builds & rustflags isolation**: `Cargo.lock` is committed and CI runs with `--locked` and `CARGO_ENCODED_RUSTFLAGS=""` (`scripts/check-invariants.sh` verifies fresh `cargo rustc --print link-args` contains zero leaked root NAPI flags). +- `blocksuite/crates/oracle/`: Browser-captured style and surface geometry fixtures (`style-oracle.json`, `surface-oracle.json`, `surface-baselines.json`, `surface-metrics-test.ttf`), `surface-baselines.mjs`, `surface-oracle.spec.mjs`, `extract-style-oracle.spec.ts`, and browser-mode `vitest.config.ts` (`browser.enabled: true` so `scripts/ci/vitest-node-projects.mjs` skips it). ### Page rendering and room sync - **World space vs screen space**: `BlockFlow` lays a `PageSnapshot` out in document coordinates (origin at the page column's top-left, independent of window and scroll) and reuses the body of every block whose content, width and theme are unchanged. `PageViewport` maps world space onto the screen (`viewport origin + world - scroll`); only blocks intersecting the viewport become elements. Top bar, mode switcher, theme toggle and presence badges are screen-space chrome. -- **Style oracle parity**: Block metrics (`paragraph_spec` with baselines and heading letter spacing, quote/code/divider/bookmark constants, margin collapsing, 24px child indent, the 944px container with 96px / 24px side padding) mirror BlockSuite's page CSS and are asserted against `tokens/style-oracle.json` in both themes by `crates/playground` tests, on the constants (L1) and on rendered frames (L2). Change a metric only together with the oracle. +- **Style oracle parity**: Block metrics (`paragraph_spec` with baselines and heading letter spacing, quote/code/divider/bookmark constants, margin collapsing, 24px child indent, the 944px container with 96px / 24px side padding) mirror BlockSuite's page CSS and are asserted against `blocksuite/crates/oracle/style-oracle.json` in both themes by `blocksuite/crates/playground` tests, on the constants (L1) and on rendered frames (L2). Change a metric only together with the oracle. - **Block semantics**: `prop:textAlign` (`left` / `center` / `right`) aligns paragraph and list text and is inherited by nested children that set none; a list prefix stays at the left edge. A collapsed heading hides its own children and the siblings under it up to the next heading of its level; a collapsed toggle hides its children. - **First-line prefixes**: List bullets, numbers, checkboxes and toggles are placed against the first line of the item's text, and a numbered prefix sits on that line's baseline. Single-style labels (title, code, captions, cards) use the plain `InlineLayout`. - **Snapshot ids**: `page.title_block`, `page.local_caret`, `page.selection`, `page.block.`, `page.presence..caret|label`, `chrome.theme_toggle`, `chrome.presence.`; block controls and overlays are listed under *Overlays and block controls*. A block, a control or a marker records its element snapshot only while it lies completely inside the page viewport; one cut by the fold is clipped on purpose. @@ -56,21 +42,14 @@ This document records the active engineering invariants enforced in CI today alo - **Sizes and radii**: Interactive targets are at least 24 × 24 px (toolbar buttons 28 × 28, edge to edge). Rows and buttons round concentrically with their container: 8 px menu with 4 px padding and 4 px rows (BlockSuite pads its menu `8px 4px 8px 8px`; 4 px all around keeps the radii concentric), 8 px toolbar with 4 px padding and 4 px buttons (`gap = 2px, pad = 4px`, intentionally compact relative to JS `8px / 0 6px` so the toolbar fits a 320 px window between its 8 px margins). The toolbar is 297 px wide, with 8 px on either side of the line between the mark and the alignment buttons. - **Verification**: `bs-harness render --state ` renders one overlay state of the showcase, `bs-harness audit-states` audits every state in both themes at `1280` and `320` px, and `bs-harness record-demo ` writes the frames of a 60 fps walk through typing, composition, the slash menu, the toolbar and the block controls; all drive the view through input events, the input handler and `dispatch_overlay` only. -### Performance guardrail and theme/style oracle -- **`perf/` (`schema.json`, `accepted.json`, `compare-n3.mjs`, `compare-n3.test.mjs`)**: Zero-dependency rolling `N-3` CI comparator with strict schema validation and rerun history anchoring (`--run-id` `created_at` cutoff + pagination). Deterministic byte sizes (`artifacts_bytes.*`) and work counters (non-`_ms` `benchmarks.*`) are hard-gated at strictly `> 10%` (`--fail-on-regression` exits `1`); shared-runner wall-clock timings (`benchmarks.*_ms` at `> 10%`, `ci_wall_ms.*` at `> 10%` and `> 15_000 ms`) are report-only `ADVISORY_SLOWDOWN`. Intentional increases are acknowledged via `{ metric, accepted_value, reason }` ceiling entries in `perf/accepted.json` (with report-only `stale_acceptances` once the rolling baseline catches up). Unmeasured sub-keys are omitted or `null` (never padded with synthetic `0`s) so newly introduced metrics transition through `BOOTSTRAP`. -- **`tokens/` (`extract-tokens.mjs`, `tokens.rs`, `icons.rs`, `fonts.lock`, `extract-style-oracle.spec.ts`, `style-oracle.json`)**: `extract-tokens.mjs` deterministically generates Rust-`Ord`-sorted `tokens.rs`, `icons.rs` (preserving inherited `` and stroke attributes), and `fonts.lock` (SHA-256 font asset manifest + `CommunityCanvasTextFonts` descriptors), with `--check` and `rustc --edition 2024 --test` enforced on every push in CI. `style-oracle.json` is regenerated via Vitest Browser (`extract-style-oracle.spec.ts`, `isolate: false` reusable iframe) whenever BlockSuite styles or themes change (until its browser CI job lands). - ### Rich paragraph layout - **Variable-font slant axis**: CoreText and Swash specialize an upright variable face at its minimum OpenType `slnt` coordinate for italic and oblique requests, alongside `wght`. A native static italic face retains its own outlines. Pixel letter spacing shifts shaped clusters and their total advance together. - **`RichParagraph`**: The single rich-text engine: `BlockFlow` lays out and paints paragraph and list text with it (`LaidOutRichParagraph::paint_at`, the same path `RichParagraphElement` uses), and reads remote carets and selections from its geometry. Cursor and selection geometry uses source UTF-16 positions and extended-grapheme boundaries. Each inline reference occupies one document unit regardless of its resolved label width, wraps as one inline object (the words before it stay on their line), and its prefix is the generated `LinkedPageIcon` SVG painted at the `DecorationKind::PageGlyph` bounds. `color` and `background` marks resolve through the theme (`DecorationKind::Highlight` behind the glyphs), and bold follows CSS `bolder`. Shaped lines supply wrapping, painting, hit targets, and both caret affinities at a soft wrap. -- **Inline style parity**: Code boxes and links follow the light/dark theme tokens and browser measurements in `tokens/style-oracle.json`; the code box metrics are constants that a test keeps equal to the oracle, so the oracle JSON is never embedded in the shipped binary. Plain and rich renders of one document can be reproduced with `bs-harness render-rich-sample --out-plain plain.png --out-rich rich.png`. +- **Inline style parity**: Code boxes and links follow the light/dark theme tokens and browser measurements in `blocksuite/crates/oracle/style-oracle.json`; the code box metrics are constants that a test keeps equal to the oracle, so the oracle JSON is never embedded in the shipped binary. Plain and rich renders of one document can be reproduced with `bs-harness render-rich-sample --out-plain plain.png --out-rich rich.png`. -### Edgeless rendering and GPU transforms -- **End-to-end GPU transforms and local clip masks**: `Window::with_paint_transformation` composes 2D affine transforms (`TransformationMatrix`) on a stack and `Window::with_local_paint_mask` intersects pre-transform local clip rects (`ContentMask`). All GPU primitives (`Quad`, `Shadow`, `Underline`, `MonochromeSprite`, `SubpixelSprite`, `PolychromeSprite`, and `PathRasterizationVertex`) are 16-byte aligned (`size_of % 16 == 0`, verified by compile-time assertions) for WebGL2 `RGBA32U` instance-texture decoding. Both Metal (`shaders.metal`) and wgpu/WebGL2 (`shaders.wgsl`, `shaders_webgl.wgsl`, `shaders_subpixel.wgsl`) transform vertices on the GPU, reserve bit 31 of `quad_id` (`0x80000000u`) in `vs_quad` / `quad_vertex` for the solid-quad fast path, evaluate SDFs in local space scaled by `transform_scale` for 1-device-pixel anti-aliasing across zooms and rotations, and clip against both screen-space `content_mask` and pre-transform `local_content_mask`. -- **Quarter-octave glyph zoom bucketing**: Under non-unit paint scales, `Window::paint_glyph` and `Window::paint_glyph_in_run` quantize rasterization scale to quarter-octave buckets (`2^(round(4*log2(s))/4)` clamped to `[0.25, 8.0]`), rasterizing atlas tiles at `font_size * bucket` while scaling local quad bounds by `1 / bucket` so cached `1.0x` `RichParagraph` / `BlockFlow` layouts render crisply at `0.1x..6.0x` without re-shaping or relayouting during pan/zoom. -- **Procedural dot-grid (`BackgroundTag::DotGrid = 4`)**: Renders the Edgeless background grid in a single fullscreen `Quad` draw call with 1-device-pixel anti-aliased dots centered in each tile with screen offset `(0.5 * gap - pan * zoom).rem_euclid(gap)` per axis and spacing matching BlockSuite's `getBgGridGap(zoom)`. +### Edgeless spatial canvas and interactive authoring - **Spatial camera & canvas (`edgeless/`)**: `edgeless/camera.rs` (`EdgelessCamera`) manages pan/zoom (`[0.1, 6.0]`), cursor-anchored wheel zoom, and fit-to-bounds (initialized before building `chrome.edgeless_zoom` so Frame 1 displays the fitted zoom percentage). `edgeless/scene.rs` and `edgeless/canvas_paint.rs` prepare and render Surface-parented Frames and EdgelessText and root-parented Notes in a single snapshot pass. Note dimensions are world units. Layout uses the logical width divided by scale. Collapsed notes clip to the stored world height, which already includes scale. The canvas merges the block and vector paint streams by fractional index and Frame/Group ancestry (`prop:childElementIds` treats every present key as a frame member, and equal indices preserve source enumeration order within each stream — live incremental sync and independent multi-author merged updates follow `(Reverse(client), clock)` integration order, whereas a late-join single V1 snapshot with cross-client causal edits among equal-index overlapping elements can invert their tie-break paint/pick order until `y-octo` exposes per-map integration order). Equal indices continue the active stream, with blocks first at the start. Notes reuse their cached `BlockFlow::layout_nodes` during pan/zoom. All items paint under `edgeless.viewport`, with bottom-centered creation toolbar (`chrome.edgeless_toolbar`) and bottom-right screen-space zoom controls (`chrome.edgeless_zoom`, stacked cleanly above `chrome.edgeless_toolbar` on narrow viewports `< 660 px`). `bs-harness render --mode edgeless [--zoom ] [--pan ,]` renders spatial states, `bs-harness audit-states` audits Edgeless default + `0.5x` + `2.0x` + authoring states (`edgeless_selected`, `edgeless_marquee`, `edgeless_inline_edit`, `edgeless_authoring`) in Light/Dark at `1280` and `320` px, and `bs-harness bench` measures `edgeless_1k_pan_zoom_frame_ms` and asserts `edgeless_1k_pan_zoom_blocks_relayout == 0`. -- **Edgeless interactive authoring & inline IME editing (`edgeless/{toolbar,hit_test,overlay,label_editor,inline_edit,gestures,commit,commands}.rs`)**: `chrome.edgeless_toolbar` provides Select (`V`/`Escape`), Hand (`H` or holding `Space`), Note (`N`), Shape (`S` with rect/ellipse/diamond/triangle picker), Connector (`C` with cardinal port snapping and live orthogonal connector preview), Brush (`P`), Highlighter, Text (`T`), and Frame (`F`, populating `prop:childElementIds`). World-space hit-testing walks exact reverse paint order (inverse-rotated OBBs for shapes/texts, routed polyline distance from `SurfaceLayout` for connectors/strokes, exact `layout_inline` title pill and border for frames). Selection renders a screen-crisp `edgeless.selection_box`, 8 resize handles (`edgeless.handle.nw..w`), top rotation handle (`edgeless.handle.rotate`, `15°` snap with `Shift`), and `2×3` 6-dot `14px` Edgeless `gfx` drag handle (`edgeless.drag_handle`) on selected blocks; resize and rotation handles are suppressed while inline label editing is active, and the underlying static label is hidden until commit. Dragging, resizing, rotating, deleting (`Backspace`/`Delete`), and z-reordering (`[`/`]` via `fractional-indexing@3.2.0` keys in `crates/doc/src/fractional_index.rs`) commit single atomic undo steps on `PageDocSession` and broadcast over `RoomProtocol`. Double-clicking a Note or EdgelessText edits rich text inline via `EditorSession` + `EntityInputHandler` with camera-mapped `bounds_for_range`; double-clicking a Shape, Connector, SurfaceText, or Frame title edits its `Y.Text` inline (`edgeless.inline_edit`) with full UTF-16 + IME preedit support. +- **Edgeless interactive authoring & inline IME editing (`edgeless/{toolbar,hit_test,overlay,label_editor,inline_edit,gestures,commit,commands}.rs`)**: `chrome.edgeless_toolbar` provides Select (`V`/`Escape`), Hand (`H` or holding `Space`), Note (`N`), Shape (`S` with rect/ellipse/diamond/triangle picker), Connector (`C` with cardinal port snapping and live orthogonal connector preview), Brush (`P`), Highlighter, Text (`T`), and Frame (`F`, populating `prop:childElementIds`). World-space hit-testing walks exact reverse paint order (inverse-rotated OBBs for shapes/texts, routed polyline distance from `SurfaceLayout` for connectors/strokes, exact `layout_inline` title pill and border for frames). Selection renders a screen-crisp `edgeless.selection_box`, 8 resize handles (`edgeless.handle.nw..w`), top rotation handle (`edgeless.handle.rotate`, `15°` snap with `Shift`), and `2×3` 6-dot `14px` Edgeless `gfx` drag handle (`edgeless.drag_handle`) on selected blocks; resize and rotation handles are suppressed while inline label editing is active, and the underlying static label is hidden until commit. Dragging, resizing, rotating, deleting (`Backspace`/`Delete`), and z-reordering (`[`/`]` via `fractional-indexing@3.2.0` keys in `blocksuite/blocksuite/crates/doc/src/fractional_index.rs`) commit single atomic undo steps on `PageDocSession` and broadcast over `RoomProtocol`. Double-clicking a Note or EdgelessText edits rich text inline via `EditorSession` + `EntityInputHandler` with camera-mapped `bounds_for_range`; double-clicking a Shape, Connector, SurfaceText, or Frame title edits its `Y.Text` inline (`edgeless.inline_edit`) with full UTF-16 + IME preedit support. ### Surface reading and painting @@ -78,43 +57,15 @@ This document records the active engineering invariants enforced in CI today alo - `surface::layout_surface` accepts element snapshots and world bounds for external blocks. It finds ports on rotated shape outlines and routes orthogonal connectors using their two endpoint bounds. The router follows BlockSuite's `ConnectorPathGenerator`. A connector's `rough` flag enables jitter and `roughness` sets its amplitude. Scribbled shapes follow RoughJS hachure, `pointsOnPath` sampling and seeded operation order. Brush and highlighter share the perfect-freehand pressure outline and midpoint quadratic curves. EdgelessCanvas caches geometry by document revision, theme and environment revision. Fully visible elements emit `edgeless.surface.` in screen coordinates. The standalone harness uses the same painter. - The canvas clips its viewport in screen coordinates. Within the camera transform, each rotated shape or text pushes its own center rotation before its label mask. The GPU inverse-maps coverage into the label's local coordinates while retaining the screen-space viewport clip. -- The JS surface oracle runs the BlockSuite shape, connector and freehand implementations and compares their coordinates to `tokens/surface-oracle.json`. Rust tests consume the same geometry and font baselines. +- The JS surface oracle runs the BlockSuite shape, connector and freehand implementations and compares their coordinates to `blocksuite/crates/oracle/surface-oracle.json`. Rust tests consume the same geometry and font baselines. - With repository JavaScript dependencies installed, `cargo test --locked -p blocksuite-playground-doc --example bs_doc_driver js_authored_surface` verifies data and rich-text marks written by Yjs against the typed Rust snapshot and compares the encoded document before and after reading. ### Rust Module Organization & Fast Verification - **Proactive modularization**: Split files by responsibility (targeting ~500–800 production lines; promote `.rs` to `/mod.rs` when introducing submodules). Keep each `mod.rs` as the dependency and visibility hub (`pub(super) use ...`), import siblings via `use super::...`, and hoist cross-layer shared items to the narrowest common ancestor `mod.rs`. - **Global optimum & clean boundaries**: Prefer structural cleanup and bold deletion over band-aid patches. Delete obsolete code outright, fold single-caller one-way fragments back into their caller, and extract shared helpers only for stable domain concepts, genuine multi-site reuse, or key invariants — never for one-line expressions. - **Focused, table-driven tests**: Keep test-only imports and helpers inside `#[cfg(test)] mod tests`, placing unit tests in the file under test and cross-submodule tests in the lowest common `mod.rs`. Keep every test file and function name aligned with its actual assertion scope, and group similar scenarios into table-driven loops rather than proliferating near-identical `#[test]` functions. -- **Sub-60-second verification loop**: Validate uncertain paths with minimal focused spikes first and remove scaffolding before landing. Keep routine edit-verify turns under **60 seconds** using targeted `cargo check --locked -p ...` / `cargo test --locked -p ... --lib ` and `./scripts/check-invariants.sh` (which enforces `super::super` bans, `mod.rs` layout, orphan-file detection, and per-file LOC limits automatically alongside `rustfmt.toml`). +- **Sub-60-second verification loop**: Validate uncertain paths with minimal focused spikes first and remove scaffolding before landing. Keep routine edit-verify turns under **60 seconds** using targeted `cargo check --locked -p ...` / `cargo test --locked -p ... --lib ` and `./packages/frontend/scripts/check-invariants.sh` (which enforces `super::super` bans, `mod.rs` layout, orphan-file detection, and per-file LOC limits automatically alongside `rustfmt.toml`). ## Planned Contracts (upcoming crates & features) - **Whiteboard surface elements**: Mindmap tree layout and editing on the Edgeless spatial canvas. - -## Build & verification commands - -Always clear inherited root rustflags: - -```sh -CARGO_ENCODED_RUSTFLAGS="" cargo fmt --all -- --check -CARGO_ENCODED_RUSTFLAGS="" cargo clippy --locked --workspace --all-targets --features harness -- -D warnings -CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p ui -p playground --target wasm32-unknown-unknown -CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p blocksuite-playground-doc --no-default-features --target wasm32-unknown-unknown -CARGO_ENCODED_RUSTFLAGS="" cargo test --locked --workspace -CARGO_ENCODED_RUSTFLAGS="" cargo test --locked --workspace --features harness -CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render --theme dark --mode page --out frame.png --snapshot frame.json -CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- probes -CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- bench --json perf-metrics.json -CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render-surface-sample --theme light --out surface-light.png --snapshot surface-light.json -CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render-editor artifacts/editor -CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render --state slash_menu_open --out slash.png --snapshot slash.json -CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- audit-states -CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- fps-check -CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- record-demo artifacts/demo -./scripts/check-invariants.sh -node --test perf/compare-n3.test.mjs -node tokens/extract-tokens.mjs --check -rustc --edition 2024 --test -D warnings tokens/tokens.rs -o /tmp/tokens_test && /tmp/tokens_test -rustc --edition 2024 --test -D warnings tokens/icons.rs -o /tmp/icons_test && /tmp/icons_test -rm -f /tmp/tokens_test /tmp/icons_test -``` diff --git a/blocksuite/native-playground/CLAUDE.md b/blocksuite/crates/CLAUDE.md similarity index 100% rename from blocksuite/native-playground/CLAUDE.md rename to blocksuite/crates/CLAUDE.md diff --git a/blocksuite/native-playground/crates/doc/Cargo.toml b/blocksuite/crates/doc/Cargo.toml similarity index 97% rename from blocksuite/native-playground/crates/doc/Cargo.toml rename to blocksuite/crates/doc/Cargo.toml index 9ab6cd6ff5..755aa42202 100644 --- a/blocksuite/native-playground/crates/doc/Cargo.toml +++ b/blocksuite/crates/doc/Cargo.toml @@ -1,5 +1,6 @@ [package] name = "blocksuite-playground-doc" +workspace = "../../../packages/frontend" version.workspace = true edition.workspace = true publish.workspace = true diff --git a/blocksuite/native-playground/crates/doc/examples/bs_doc_driver.rs b/blocksuite/crates/doc/examples/bs_doc_driver.rs similarity index 99% rename from blocksuite/native-playground/crates/doc/examples/bs_doc_driver.rs rename to blocksuite/crates/doc/examples/bs_doc_driver.rs index da31fd7bd1..261836ee0e 100644 --- a/blocksuite/native-playground/crates/doc/examples/bs_doc_driver.rs +++ b/blocksuite/crates/doc/examples/bs_doc_driver.rs @@ -1396,7 +1396,7 @@ mod surface_roundtrip { }); process.stdout.write(JSON.stringify(Array.from(Y.encodeStateAsUpdate(doc)))); "#; - let project = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../.."); + let project = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.."); let mut child = Command::new("node") .current_dir(project) .args(["--input-type=module", "-e", script]) diff --git a/blocksuite/native-playground/crates/doc/src/awareness.rs b/blocksuite/crates/doc/src/awareness.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/awareness.rs rename to blocksuite/crates/doc/src/awareness.rs diff --git a/blocksuite/native-playground/crates/doc/src/bin/bs_relay.rs b/blocksuite/crates/doc/src/bin/bs_relay.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/bin/bs_relay.rs rename to blocksuite/crates/doc/src/bin/bs_relay.rs diff --git a/blocksuite/native-playground/crates/doc/src/fractional_index.rs b/blocksuite/crates/doc/src/fractional_index.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/fractional_index.rs rename to blocksuite/crates/doc/src/fractional_index.rs diff --git a/blocksuite/native-playground/crates/doc/src/lib.rs b/blocksuite/crates/doc/src/lib.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/lib.rs rename to blocksuite/crates/doc/src/lib.rs diff --git a/blocksuite/native-playground/crates/doc/src/read/mod.rs b/blocksuite/crates/doc/src/read/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/read/mod.rs rename to blocksuite/crates/doc/src/read/mod.rs diff --git a/blocksuite/native-playground/crates/doc/src/read/surface.rs b/blocksuite/crates/doc/src/read/surface.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/read/surface.rs rename to blocksuite/crates/doc/src/read/surface.rs diff --git a/blocksuite/native-playground/crates/doc/src/room.rs b/blocksuite/crates/doc/src/room.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/room.rs rename to blocksuite/crates/doc/src/room.rs diff --git a/blocksuite/native-playground/crates/doc/src/schema/blocks.rs b/blocksuite/crates/doc/src/schema/blocks.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/schema/blocks.rs rename to blocksuite/crates/doc/src/schema/blocks.rs diff --git a/blocksuite/native-playground/crates/doc/src/schema/mod.rs b/blocksuite/crates/doc/src/schema/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/schema/mod.rs rename to blocksuite/crates/doc/src/schema/mod.rs diff --git a/blocksuite/native-playground/crates/doc/src/schema/surface.rs b/blocksuite/crates/doc/src/schema/surface.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/schema/surface.rs rename to blocksuite/crates/doc/src/schema/surface.rs diff --git a/blocksuite/native-playground/crates/doc/src/session/export.rs b/blocksuite/crates/doc/src/session/export.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/session/export.rs rename to blocksuite/crates/doc/src/session/export.rs diff --git a/blocksuite/native-playground/crates/doc/src/session/mod.rs b/blocksuite/crates/doc/src/session/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/session/mod.rs rename to blocksuite/crates/doc/src/session/mod.rs diff --git a/blocksuite/native-playground/crates/doc/src/session/structure.rs b/blocksuite/crates/doc/src/session/structure.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/session/structure.rs rename to blocksuite/crates/doc/src/session/structure.rs diff --git a/blocksuite/native-playground/crates/doc/src/session/surface.rs b/blocksuite/crates/doc/src/session/surface.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/session/surface.rs rename to blocksuite/crates/doc/src/session/surface.rs diff --git a/blocksuite/native-playground/crates/doc/src/session/workspace.rs b/blocksuite/crates/doc/src/session/workspace.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/session/workspace.rs rename to blocksuite/crates/doc/src/session/workspace.rs diff --git a/blocksuite/native-playground/crates/doc/src/wire.rs b/blocksuite/crates/doc/src/wire.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/src/wire.rs rename to blocksuite/crates/doc/src/wire.rs diff --git a/blocksuite/native-playground/crates/doc/tests/doc_room_sync.rs b/blocksuite/crates/doc/tests/doc_room_sync.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/tests/doc_room_sync.rs rename to blocksuite/crates/doc/tests/doc_room_sync.rs diff --git a/blocksuite/native-playground/crates/doc/tests/page_snapshot.rs b/blocksuite/crates/doc/tests/page_snapshot.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/tests/page_snapshot.rs rename to blocksuite/crates/doc/tests/page_snapshot.rs diff --git a/blocksuite/native-playground/crates/doc/tests/structural_edits.rs b/blocksuite/crates/doc/tests/structural_edits.rs similarity index 100% rename from blocksuite/native-playground/crates/doc/tests/structural_edits.rs rename to blocksuite/crates/doc/tests/structural_edits.rs diff --git a/blocksuite/native-playground/tokens/extract-style-oracle.spec.ts b/blocksuite/crates/oracle/extract-style-oracle.spec.ts similarity index 100% rename from blocksuite/native-playground/tokens/extract-style-oracle.spec.ts rename to blocksuite/crates/oracle/extract-style-oracle.spec.ts diff --git a/blocksuite/native-playground/tokens/style-oracle.json b/blocksuite/crates/oracle/style-oracle.json similarity index 100% rename from blocksuite/native-playground/tokens/style-oracle.json rename to blocksuite/crates/oracle/style-oracle.json diff --git a/blocksuite/native-playground/tokens/surface-baselines.json b/blocksuite/crates/oracle/surface-baselines.json similarity index 100% rename from blocksuite/native-playground/tokens/surface-baselines.json rename to blocksuite/crates/oracle/surface-baselines.json diff --git a/blocksuite/native-playground/scripts/surface-baselines.mjs b/blocksuite/crates/oracle/surface-baselines.mjs similarity index 87% rename from blocksuite/native-playground/scripts/surface-baselines.mjs rename to blocksuite/crates/oracle/surface-baselines.mjs index 00b884499b..48563edd64 100644 --- a/blocksuite/native-playground/scripts/surface-baselines.mjs +++ b/blocksuite/crates/oracle/surface-baselines.mjs @@ -1,9 +1,9 @@ import fs from 'node:fs'; -const root = new URL('../', import.meta.url); +const root = new URL('./', import.meta.url); const fonts = [ - ['IBM Plex Mono', '../../packages/frontend/component/src/fonts/ibm-plex-mono/IBMPlexMono-Regular.ttf'], - ['Surface Metrics Test', 'tokens/surface-metrics-test.ttf'], + ['IBM Plex Mono', '../../../packages/frontend/component/src/fonts/ibm-plex-mono/IBMPlexMono-Regular.ttf'], + ['Surface Metrics Test', './surface-metrics-test.ttf'], ]; // Measure the same inline span and containing line box as the surface text renderer. diff --git a/blocksuite/native-playground/tokens/surface-metrics-test.ttf b/blocksuite/crates/oracle/surface-metrics-test.ttf similarity index 100% rename from blocksuite/native-playground/tokens/surface-metrics-test.ttf rename to blocksuite/crates/oracle/surface-metrics-test.ttf diff --git a/blocksuite/native-playground/tokens/surface-oracle.json b/blocksuite/crates/oracle/surface-oracle.json similarity index 100% rename from blocksuite/native-playground/tokens/surface-oracle.json rename to blocksuite/crates/oracle/surface-oracle.json diff --git a/blocksuite/native-playground/tokens/surface-oracle.spec.mjs b/blocksuite/crates/oracle/surface-oracle.spec.mjs similarity index 100% rename from blocksuite/native-playground/tokens/surface-oracle.spec.mjs rename to blocksuite/crates/oracle/surface-oracle.spec.mjs diff --git a/blocksuite/native-playground/tokens/vitest.config.ts b/blocksuite/crates/oracle/vitest.config.ts similarity index 97% rename from blocksuite/native-playground/tokens/vitest.config.ts rename to blocksuite/crates/oracle/vitest.config.ts index f7c5174bc7..2b13c5001c 100644 --- a/blocksuite/native-playground/tokens/vitest.config.ts +++ b/blocksuite/crates/oracle/vitest.config.ts @@ -79,7 +79,7 @@ export default defineConfig({ }, plugins: [tc39DecoratorsPlugin(), vanillaExtractPlugin()], test: { - include: ['../native-playground/tokens/extract-style-oracle.spec.ts'], + include: ['../crates/oracle/extract-style-oracle.spec.ts'], fileParallelism: false, testTimeout: 60_000, browser: { diff --git a/blocksuite/native-playground/crates/playground/Cargo.toml b/blocksuite/crates/playground/Cargo.toml similarity index 92% rename from blocksuite/native-playground/crates/playground/Cargo.toml rename to blocksuite/crates/playground/Cargo.toml index 2a1e164519..7f5b34170d 100644 --- a/blocksuite/native-playground/crates/playground/Cargo.toml +++ b/blocksuite/crates/playground/Cargo.toml @@ -1,5 +1,6 @@ [package] name = "playground" +workspace = "../../../packages/frontend" version.workspace = true edition.workspace = true publish.workspace = true @@ -31,7 +32,7 @@ blocksuite-playground-doc = { path = "../doc", default-features = false } image.workspace = true serde.workspace = true serde_json.workspace = true -ui = { path = "../ui" } +ui = { path = "../../../packages/ui/ui" } unicode-bidi.workspace = true unicode-linebreak = "0.1" unicode-segmentation.workspace = true @@ -39,7 +40,7 @@ y-octo = { version = "0.4.0", default-features = false, features = ["session"] } [dev-dependencies] tempfile = "3" -ui = { path = "../ui", features = ["harness"] } +ui = { path = "../../../packages/ui/ui", features = ["harness"] } [target.'cfg(not(target_family = "wasm"))'.dependencies] futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] } diff --git a/blocksuite/native-playground/crates/playground/src/bin/bs_harness/bench.rs b/blocksuite/crates/playground/src/bin/bs_harness/bench.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/bin/bs_harness/bench.rs rename to blocksuite/crates/playground/src/bin/bs_harness/bench.rs diff --git a/blocksuite/native-playground/crates/playground/src/bin/bs_harness/demo.rs b/blocksuite/crates/playground/src/bin/bs_harness/demo.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/bin/bs_harness/demo.rs rename to blocksuite/crates/playground/src/bin/bs_harness/demo.rs diff --git a/blocksuite/native-playground/crates/playground/src/bin/bs_harness/fps.rs b/blocksuite/crates/playground/src/bin/bs_harness/fps.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/bin/bs_harness/fps.rs rename to blocksuite/crates/playground/src/bin/bs_harness/fps.rs diff --git a/blocksuite/native-playground/crates/playground/src/bin/bs_harness/main.rs b/blocksuite/crates/playground/src/bin/bs_harness/main.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/bin/bs_harness/main.rs rename to blocksuite/crates/playground/src/bin/bs_harness/main.rs diff --git a/blocksuite/native-playground/crates/playground/src/bin/bs_harness/probes.rs b/blocksuite/crates/playground/src/bin/bs_harness/probes.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/bin/bs_harness/probes.rs rename to blocksuite/crates/playground/src/bin/bs_harness/probes.rs diff --git a/blocksuite/native-playground/crates/playground/src/bin/bs_harness/render.rs b/blocksuite/crates/playground/src/bin/bs_harness/render.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/bin/bs_harness/render.rs rename to blocksuite/crates/playground/src/bin/bs_harness/render.rs diff --git a/blocksuite/native-playground/crates/playground/src/bin/bs_harness/states.rs b/blocksuite/crates/playground/src/bin/bs_harness/states.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/bin/bs_harness/states.rs rename to blocksuite/crates/playground/src/bin/bs_harness/states.rs diff --git a/blocksuite/native-playground/crates/playground/src/block_flow/blocks.rs b/blocksuite/crates/playground/src/block_flow/blocks.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/block_flow/blocks.rs rename to blocksuite/crates/playground/src/block_flow/blocks.rs diff --git a/blocksuite/native-playground/crates/playground/src/block_flow/body.rs b/blocksuite/crates/playground/src/block_flow/body.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/block_flow/body.rs rename to blocksuite/crates/playground/src/block_flow/body.rs diff --git a/blocksuite/native-playground/crates/playground/src/block_flow/inline.rs b/blocksuite/crates/playground/src/block_flow/inline.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/block_flow/inline.rs rename to blocksuite/crates/playground/src/block_flow/inline.rs diff --git a/blocksuite/native-playground/crates/playground/src/block_flow/layout.rs b/blocksuite/crates/playground/src/block_flow/layout.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/block_flow/layout.rs rename to blocksuite/crates/playground/src/block_flow/layout.rs diff --git a/blocksuite/native-playground/crates/playground/src/block_flow/mod.rs b/blocksuite/crates/playground/src/block_flow/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/block_flow/mod.rs rename to blocksuite/crates/playground/src/block_flow/mod.rs diff --git a/blocksuite/native-playground/crates/playground/src/block_flow/viewport.rs b/blocksuite/crates/playground/src/block_flow/viewport.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/block_flow/viewport.rs rename to blocksuite/crates/playground/src/block_flow/viewport.rs diff --git a/blocksuite/native-playground/crates/playground/src/chrome.rs b/blocksuite/crates/playground/src/chrome.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/chrome.rs rename to blocksuite/crates/playground/src/chrome.rs diff --git a/blocksuite/native-playground/crates/playground/src/clipboard/html.rs b/blocksuite/crates/playground/src/clipboard/html.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/clipboard/html.rs rename to blocksuite/crates/playground/src/clipboard/html.rs diff --git a/blocksuite/native-playground/crates/playground/src/clipboard/mod.rs b/blocksuite/crates/playground/src/clipboard/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/clipboard/mod.rs rename to blocksuite/crates/playground/src/clipboard/mod.rs diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/camera.rs b/blocksuite/crates/playground/src/edgeless/camera.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/edgeless/camera.rs rename to blocksuite/crates/playground/src/edgeless/camera.rs diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/canvas.rs b/blocksuite/crates/playground/src/edgeless/canvas.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/edgeless/canvas.rs rename to blocksuite/crates/playground/src/edgeless/canvas.rs diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/canvas_paint.rs b/blocksuite/crates/playground/src/edgeless/canvas_paint.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/edgeless/canvas_paint.rs rename to blocksuite/crates/playground/src/edgeless/canvas_paint.rs diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/commands.rs b/blocksuite/crates/playground/src/edgeless/commands.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/edgeless/commands.rs rename to blocksuite/crates/playground/src/edgeless/commands.rs diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/commit.rs b/blocksuite/crates/playground/src/edgeless/commit.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/edgeless/commit.rs rename to blocksuite/crates/playground/src/edgeless/commit.rs diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/gestures.rs b/blocksuite/crates/playground/src/edgeless/gestures.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/edgeless/gestures.rs rename to blocksuite/crates/playground/src/edgeless/gestures.rs diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/hit_test.rs b/blocksuite/crates/playground/src/edgeless/hit_test.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/edgeless/hit_test.rs rename to blocksuite/crates/playground/src/edgeless/hit_test.rs diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/inline_edit.rs b/blocksuite/crates/playground/src/edgeless/inline_edit.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/edgeless/inline_edit.rs rename to blocksuite/crates/playground/src/edgeless/inline_edit.rs diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/label_editor.rs b/blocksuite/crates/playground/src/edgeless/label_editor.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/edgeless/label_editor.rs rename to blocksuite/crates/playground/src/edgeless/label_editor.rs diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/mod.rs b/blocksuite/crates/playground/src/edgeless/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/edgeless/mod.rs rename to blocksuite/crates/playground/src/edgeless/mod.rs diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/order.rs b/blocksuite/crates/playground/src/edgeless/order.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/edgeless/order.rs rename to blocksuite/crates/playground/src/edgeless/order.rs diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/overlay.rs b/blocksuite/crates/playground/src/edgeless/overlay.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/edgeless/overlay.rs rename to blocksuite/crates/playground/src/edgeless/overlay.rs diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/scene.rs b/blocksuite/crates/playground/src/edgeless/scene.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/edgeless/scene.rs rename to blocksuite/crates/playground/src/edgeless/scene.rs diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/toolbar.rs b/blocksuite/crates/playground/src/edgeless/toolbar.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/edgeless/toolbar.rs rename to blocksuite/crates/playground/src/edgeless/toolbar.rs diff --git a/blocksuite/native-playground/crates/playground/src/editor_session/clipboard_ops.rs b/blocksuite/crates/playground/src/editor_session/clipboard_ops.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/editor_session/clipboard_ops.rs rename to blocksuite/crates/playground/src/editor_session/clipboard_ops.rs diff --git a/blocksuite/native-playground/crates/playground/src/editor_session/commands.rs b/blocksuite/crates/playground/src/editor_session/commands.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/editor_session/commands.rs rename to blocksuite/crates/playground/src/editor_session/commands.rs diff --git a/blocksuite/native-playground/crates/playground/src/editor_session/composition.rs b/blocksuite/crates/playground/src/editor_session/composition.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/editor_session/composition.rs rename to blocksuite/crates/playground/src/editor_session/composition.rs diff --git a/blocksuite/native-playground/crates/playground/src/editor_session/input_handler.rs b/blocksuite/crates/playground/src/editor_session/input_handler.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/editor_session/input_handler.rs rename to blocksuite/crates/playground/src/editor_session/input_handler.rs diff --git a/blocksuite/native-playground/crates/playground/src/editor_session/mod.rs b/blocksuite/crates/playground/src/editor_session/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/editor_session/mod.rs rename to blocksuite/crates/playground/src/editor_session/mod.rs diff --git a/blocksuite/native-playground/crates/playground/src/lib.rs b/blocksuite/crates/playground/src/lib.rs similarity index 99% rename from blocksuite/native-playground/crates/playground/src/lib.rs rename to blocksuite/crates/playground/src/lib.rs index 3cbb1641d9..e99cd08e1c 100644 --- a/blocksuite/native-playground/crates/playground/src/lib.rs +++ b/blocksuite/crates/playground/src/lib.rs @@ -781,7 +781,7 @@ mod tests { } fn oracle() -> serde_json::Value { - serde_json::from_str(include_str!("../../../tokens/style-oracle.json")) + serde_json::from_str(include_str!("../../oracle/style-oracle.json")) .expect("style oracle is valid JSON") } @@ -3194,7 +3194,7 @@ mod tests { #[test] fn yjs_bring_to_front_repaints_the_shape_over_the_note() { let oracle: serde_json::Value = - serde_json::from_str(include_str!("../../../tokens/surface-oracle.json")).unwrap(); + serde_json::from_str(include_str!("../../oracle/surface-oracle.json")).unwrap(); let update = |name: &str| serde_json::from_value::>(oracle["layers"][name].clone()).unwrap(); let mut doc = DocState::new("order", 71).unwrap(); diff --git a/blocksuite/native-playground/crates/playground/src/main.rs b/blocksuite/crates/playground/src/main.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/main.rs rename to blocksuite/crates/playground/src/main.rs diff --git a/blocksuite/native-playground/crates/playground/src/overlays/mod.rs b/blocksuite/crates/playground/src/overlays/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/overlays/mod.rs rename to blocksuite/crates/playground/src/overlays/mod.rs diff --git a/blocksuite/native-playground/crates/playground/src/overlays/paint_page.rs b/blocksuite/crates/playground/src/overlays/paint_page.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/overlays/paint_page.rs rename to blocksuite/crates/playground/src/overlays/paint_page.rs diff --git a/blocksuite/native-playground/crates/playground/src/overlays/paint_popovers.rs b/blocksuite/crates/playground/src/overlays/paint_popovers.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/overlays/paint_popovers.rs rename to blocksuite/crates/playground/src/overlays/paint_popovers.rs diff --git a/blocksuite/native-playground/crates/playground/src/overlays/slash.rs b/blocksuite/crates/playground/src/overlays/slash.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/overlays/slash.rs rename to blocksuite/crates/playground/src/overlays/slash.rs diff --git a/blocksuite/native-playground/crates/playground/src/overlays/state.rs b/blocksuite/crates/playground/src/overlays/state.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/overlays/state.rs rename to blocksuite/crates/playground/src/overlays/state.rs diff --git a/blocksuite/native-playground/crates/playground/src/overlays/toolbar.rs b/blocksuite/crates/playground/src/overlays/toolbar.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/overlays/toolbar.rs rename to blocksuite/crates/playground/src/overlays/toolbar.rs diff --git a/blocksuite/native-playground/crates/playground/src/overlays/view.rs b/blocksuite/crates/playground/src/overlays/view.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/overlays/view.rs rename to blocksuite/crates/playground/src/overlays/view.rs diff --git a/blocksuite/native-playground/crates/playground/src/overlays/view_edits.rs b/blocksuite/crates/playground/src/overlays/view_edits.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/overlays/view_edits.rs rename to blocksuite/crates/playground/src/overlays/view_edits.rs diff --git a/blocksuite/native-playground/crates/playground/src/rich_text/bi_index.rs b/blocksuite/crates/playground/src/rich_text/bi_index.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/rich_text/bi_index.rs rename to blocksuite/crates/playground/src/rich_text/bi_index.rs diff --git a/blocksuite/native-playground/crates/playground/src/rich_text/layout.rs b/blocksuite/crates/playground/src/rich_text/layout.rs similarity index 99% rename from blocksuite/native-playground/crates/playground/src/rich_text/layout.rs rename to blocksuite/crates/playground/src/rich_text/layout.rs index 1a37d20d69..774bcf5b96 100644 --- a/blocksuite/native-playground/crates/playground/src/rich_text/layout.rs +++ b/blocksuite/crates/playground/src/rich_text/layout.rs @@ -704,7 +704,7 @@ mod tests { #[test] fn rich_paragraph_layout_geometry_marks_alignment_and_bidi_invariants() { let oracle: serde_json::Value = - serde_json::from_str(include_str!("../../../../tokens/style-oracle.json")).unwrap(); + serde_json::from_str(include_str!("../../../oracle/style-oracle.json")).unwrap(); let platform = HeadlessPlatform::new(128, 64, 1.); let app = Application::with_platform(platform) .run_embedded(|cx| crate::register_bundled_fonts(cx).unwrap()); diff --git a/blocksuite/native-playground/crates/playground/src/rich_text/mod.rs b/blocksuite/crates/playground/src/rich_text/mod.rs similarity index 99% rename from blocksuite/native-playground/crates/playground/src/rich_text/mod.rs rename to blocksuite/crates/playground/src/rich_text/mod.rs index 8aaa720505..3c8836de67 100644 --- a/blocksuite/native-playground/crates/playground/src/rich_text/mod.rs +++ b/blocksuite/crates/playground/src/rich_text/mod.rs @@ -481,7 +481,7 @@ mod tests { #[test] fn code_box_constants_match_the_browser_oracle() { let oracle: serde_json::Value = - serde_json::from_str(include_str!("../../../../tokens/style-oracle.json")).unwrap(); + serde_json::from_str(include_str!("../../../oracle/style-oracle.json")).unwrap(); for (mode, name) in [(ThemeMode::Light, "light"), (ThemeMode::Dark, "dark")] { let node = &oracle["themes"][name]["inline_formats"]["inline_code"]; let css = |property: &str| -> f32 { diff --git a/blocksuite/native-playground/crates/playground/src/rich_text/paint.rs b/blocksuite/crates/playground/src/rich_text/paint.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/rich_text/paint.rs rename to blocksuite/crates/playground/src/rich_text/paint.rs diff --git a/blocksuite/native-playground/crates/playground/src/room_client/mod.rs b/blocksuite/crates/playground/src/room_client/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/room_client/mod.rs rename to blocksuite/crates/playground/src/room_client/mod.rs diff --git a/blocksuite/native-playground/crates/playground/src/room_client/native.rs b/blocksuite/crates/playground/src/room_client/native.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/room_client/native.rs rename to blocksuite/crates/playground/src/room_client/native.rs diff --git a/blocksuite/native-playground/crates/playground/src/room_client/web.rs b/blocksuite/crates/playground/src/room_client/web.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/room_client/web.rs rename to blocksuite/crates/playground/src/room_client/web.rs diff --git a/blocksuite/native-playground/crates/playground/src/showcase.rs b/blocksuite/crates/playground/src/showcase.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/showcase.rs rename to blocksuite/crates/playground/src/showcase.rs diff --git a/blocksuite/native-playground/crates/playground/src/surface/connector.rs b/blocksuite/crates/playground/src/surface/connector.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/surface/connector.rs rename to blocksuite/crates/playground/src/surface/connector.rs diff --git a/blocksuite/native-playground/crates/playground/src/surface/mod.rs b/blocksuite/crates/playground/src/surface/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/surface/mod.rs rename to blocksuite/crates/playground/src/surface/mod.rs diff --git a/blocksuite/native-playground/crates/playground/src/surface/oracle.rs b/blocksuite/crates/playground/src/surface/oracle.rs similarity index 98% rename from blocksuite/native-playground/crates/playground/src/surface/oracle.rs rename to blocksuite/crates/playground/src/surface/oracle.rs index 3b6e81c1c8..e79b7d339d 100644 --- a/blocksuite/native-playground/crates/playground/src/surface/oracle.rs +++ b/blocksuite/crates/playground/src/surface/oracle.rs @@ -2,7 +2,7 @@ use super::*; use blocksuite_playground_doc::read::{RichText, SurfaceElement, SurfaceElementKind}; use serde_json::{Value, json}; fn oracle() -> Value { - serde_json::from_str(include_str!("../../../../tokens/surface-oracle.json")).unwrap() + serde_json::from_str(include_str!("../../../oracle/surface-oracle.json")).unwrap() } fn val(p: P) -> Value { json!([p.0, p.1]) diff --git a/blocksuite/native-playground/crates/playground/src/surface/orthogonal.rs b/blocksuite/crates/playground/src/surface/orthogonal.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/surface/orthogonal.rs rename to blocksuite/crates/playground/src/surface/orthogonal.rs diff --git a/blocksuite/native-playground/crates/playground/src/surface/paint.rs b/blocksuite/crates/playground/src/surface/paint.rs similarity index 99% rename from blocksuite/native-playground/crates/playground/src/surface/paint.rs rename to blocksuite/crates/playground/src/surface/paint.rs index a14911ff33..179b9f337f 100644 --- a/blocksuite/native-playground/crates/playground/src/surface/paint.rs +++ b/blocksuite/crates/playground/src/surface/paint.rs @@ -731,14 +731,13 @@ mod tests { #[test] fn centered_shape_baselines_match_chromium_in_tall_and_short_shapes() { let cases: Vec = - serde_json::from_str(include_str!("../../../../tokens/surface-baselines.json")) - .unwrap(); + serde_json::from_str(include_str!("../../../oracle/surface-baselines.json")).unwrap(); let platform = HeadlessPlatform::new(64, 64, 1.); let app = Application::with_platform(platform).run_embedded(|cx| { crate::register_bundled_fonts(cx).unwrap(); cx.text_system() .add_fonts(vec![std::borrow::Cow::Borrowed(include_bytes!( - "../../../../tokens/surface-metrics-test.ttf" + "../../../oracle/surface-metrics-test.ttf" ))]) .unwrap(); }); diff --git a/blocksuite/native-playground/crates/playground/src/surface/rough.rs b/blocksuite/crates/playground/src/surface/rough.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/surface/rough.rs rename to blocksuite/crates/playground/src/surface/rough.rs diff --git a/blocksuite/native-playground/crates/playground/src/surface/shapes.rs b/blocksuite/crates/playground/src/surface/shapes.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/surface/shapes.rs rename to blocksuite/crates/playground/src/surface/shapes.rs diff --git a/blocksuite/native-playground/crates/playground/src/surface/strokes.rs b/blocksuite/crates/playground/src/surface/strokes.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/surface/strokes.rs rename to blocksuite/crates/playground/src/surface/strokes.rs diff --git a/blocksuite/native-playground/crates/playground/src/theme.rs b/blocksuite/crates/playground/src/theme.rs similarity index 95% rename from blocksuite/native-playground/crates/playground/src/theme.rs rename to blocksuite/crates/playground/src/theme.rs index 408570129f..20d23172d4 100644 --- a/blocksuite/native-playground/crates/playground/src/theme.rs +++ b/blocksuite/crates/playground/src/theme.rs @@ -1,8 +1,8 @@ //! Theme tokens, icons and bundled fonts for the playground. //! -//! Colors, typography and icons come straight from the generated `tokens/tokens.rs` and -//! `tokens/icons.rs` files, so a regenerated token set reaches every render target without -//! touching this crate. They are pulled in with `include!` rather than `#[path]` modules +//! Colors, typography and icons come straight from the generated `packages/ui/tokens/tokens.rs` +//! and `packages/ui/tokens/icons.rs` files, so a regenerated token set reaches every render target +//! without touching this crate. They are pulled in with `include!` rather than `#[path]` modules //! so `rustfmt` never rewrites the generated sources. use std::{ @@ -17,12 +17,12 @@ use ui::{ #[allow(dead_code, clippy::all)] pub mod tokens { - include!("../../../tokens/tokens.rs"); + include!("../../../../packages/ui/tokens/tokens.rs"); } #[allow(dead_code, clippy::all)] pub mod icons { - include!("../../../tokens/icons.rs"); + include!("../../../../packages/ui/tokens/icons.rs"); } pub use icons::{IconDef, icon_by_name}; @@ -34,19 +34,19 @@ pub const FONT_SANS: &str = "Inter"; pub const FONT_CODE: &str = "IBM Plex Mono"; const INTER_VARIABLE_TTF: &[u8] = include_bytes!( - "../../../../../packages/frontend/component/src/fonts/inter/Inter-VariableFont_slnt,wght.ttf" + "../../../../packages/frontend/component/src/fonts/inter/Inter-VariableFont_slnt,wght.ttf" ); const IBM_PLEX_MONO_REGULAR_TTF: &[u8] = include_bytes!( - "../../../../../packages/frontend/component/src/fonts/ibm-plex-mono/IBMPlexMono-Regular.ttf" + "../../../../packages/frontend/component/src/fonts/ibm-plex-mono/IBMPlexMono-Regular.ttf" ); const IBM_PLEX_MONO_BOLD_TTF: &[u8] = include_bytes!( - "../../../../../packages/frontend/component/src/fonts/ibm-plex-mono/IBMPlexMono-Bold.ttf" + "../../../../packages/frontend/component/src/fonts/ibm-plex-mono/IBMPlexMono-Bold.ttf" ); const IBM_PLEX_MONO_ITALIC_TTF: &[u8] = include_bytes!( - "../../../../../packages/frontend/component/src/fonts/ibm-plex-mono/IBMPlexMono-Italic.ttf" + "../../../../packages/frontend/component/src/fonts/ibm-plex-mono/IBMPlexMono-Italic.ttf" ); const IBM_PLEX_MONO_BOLD_ITALIC_TTF: &[u8] = include_bytes!( - "../../../../../packages/frontend/component/src/fonts/ibm-plex-mono/IBMPlexMono-BoldItalic.ttf" + "../../../../packages/frontend/component/src/fonts/ibm-plex-mono/IBMPlexMono-BoldItalic.ttf" ); /// Registers the tracked repository fonts (`Inter` and `IBM Plex Mono`) into the active diff --git a/blocksuite/native-playground/crates/playground/src/view_room.rs b/blocksuite/crates/playground/src/view_room.rs similarity index 100% rename from blocksuite/native-playground/crates/playground/src/view_room.rs rename to blocksuite/crates/playground/src/view_room.rs diff --git a/blocksuite/native-playground/web/index.html b/blocksuite/crates/playground/web/index.html similarity index 100% rename from blocksuite/native-playground/web/index.html rename to blocksuite/crates/playground/web/index.html diff --git a/blocksuite/native-playground/rust-toolchain.toml b/blocksuite/crates/rust-toolchain.toml similarity index 100% rename from blocksuite/native-playground/rust-toolchain.toml rename to blocksuite/crates/rust-toolchain.toml diff --git a/blocksuite/native-playground/rustfmt.toml b/blocksuite/crates/rustfmt.toml similarity index 100% rename from blocksuite/native-playground/rustfmt.toml rename to blocksuite/crates/rustfmt.toml diff --git a/blocksuite/native-playground/.gitignore b/blocksuite/native-playground/.gitignore deleted file mode 100644 index a7a696e5ca..0000000000 --- a/blocksuite/native-playground/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/target/ -/artifacts/ -/web/pkg/ diff --git a/blocksuite/native-playground/perf/README.md b/blocksuite/native-playground/perf/README.md deleted file mode 100644 index 3f941d5399..0000000000 --- a/blocksuite/native-playground/perf/README.md +++ /dev/null @@ -1,72 +0,0 @@ -# Native Playground CI Performance Guardrail - -Zero-dependency `N-3` regression detector for `darksky/native-playground`. - -## Metrics Schema (`schema.json`) - -Every CI run emits `perf-metrics.json` containing: - -- `schema_version`: integer `1`. -- `commit`: full 40-character lowercase Git SHA. -- `timestamp_utc`: ISO-8601 UTC timestamp. -- `ci_wall_ms`: shared-runner wall-clock durations (`lint_and_wasm`, `headless_linux`, `total_critical_path`). -- `artifacts_bytes`: deterministic build output sizes (`web_wasm_raw`, `web_wasm_gzip`, `headless_bin`). -- `benchmarks`: deterministic engine timings (`{ median, p95 }`, with `p95 >= median`) and work counters: - - `doc_1k_edits_ms` - - `room_sync_1k_ops_ms` - - `layout_10k_blocks_cold_ms` - - `layout_single_keystroke_ms` - - `layout_single_keystroke_blocks_relayout` - - `edgeless_1k_pan_zoom_frame_ms` - - `headless_frame_render_ms` - -Individual sub-keys inside `ci_wall_ms`, `artifacts_bytes`, and `benchmarks` are optional (or `null`) when a benchmark or artifact is not yet produced by CI. Never emit synthetic `0` placeholders for unmeasured metrics: omitted or `null` baseline keys transition cleanly through `BOOTSTRAP` when first introduced instead of triggering false `0 -> positive` (`+inf%`) regressions. - -## Regression Gate vs Advisory Timings - -Current commit metrics are compared against the completed push run from **3 distinct prior commits (`N-3`)** strictly older than the commit under test (`--current-created-at` or the commit's earliest push run on the branch). If `N-3` has no valid `perf-metrics.json` artifact, the comparator walks back `N-3 -> N-2 -> N-1` and uses the oldest valid baseline; with 0 valid prior baselines it emits a clean `bootstrap` pass. - -1. **Deterministic hard gate (`artifacts_bytes.*` and non-`_ms` work counters under `benchmarks.*`)**: - - Flagged as `REGRESSED` (`regressed: true`, sets `has_hard_regression: true`) whenever `(current - baseline) / baseline * 100 > 10.0%` (strictly greater than `--threshold-pct`), or when `baseline === 0` and `current > 0`. - - `--fail-on-regression` exits `1` only when `has_hard_regression` is `true`. -2. **Shared-runner wall-clock advisories (`benchmarks.*_ms` and `ci_wall_ms.*`)**: - - `benchmarks.*_ms` exceeding `> 10.0%`, and `ci_wall_ms.*` exceeding both `> 10.0%` and `> 15000` ms (`--ci-wall-min-delta-ms`), are reported as `ADVISORY_SLOWDOWN` (`advisory: true`, `regressed: false`, sets `has_advisory_slowdown: true`). - - Advisory timings are surfaced in the Markdown summary and `advisory_metrics` in `perf-verdict.json` for investigation on pinned hardware without failing shared-runner CI. - -## Regression Acknowledgements (`accepted.json`) - -Intentional increases (for example, adding a new bundled feature that grows `web_wasm_gzip`) are recorded as value-ceiling entries in `perf/accepted.json` (loaded by default, or via `--accepted `): - -```json -[ - { - "metric": "artifacts_bytes.web_wasm_gzip", - "accepted_value": 800000, - "reason": "Bundled new rich-text feature" - } -] -``` - -- When a metric triggers against the rolling baseline and `current <= accepted_value`, the row is marked `ACCEPTED` (`regressed: false`) while still printing `baseline`, `current`, `delta`, and the accepted ceiling. -- If `current > accepted_value`, it is not accepted (`REGRESSED` for deterministic hard-gate metrics, `ADVISORY_SLOWDOWN` for timings). -- Once the rolling `N-3` baseline catches up (`baseline >= accepted_value`), the entry is reported in `stale_acceptances` (strictly report-only; never fails CI) so it can be pruned cleanly. - -## Usage - -```sh -node blocksuite/native-playground/perf/compare-n3.mjs \ - --fetch-github \ - --repo toeverything/AFFiNE \ - --branch darksky/native-playground \ - --workflow native-playground.yml \ - --run-id "$GITHUB_RUN_ID" \ - --current artifacts/perf-metrics.json \ - --json-out artifacts/perf-verdict.json \ - --fail-on-regression -``` - -## Self-Tests - -```sh -node --test blocksuite/native-playground/perf/compare-n3.test.mjs -``` diff --git a/blocksuite/native-playground/scripts/check-invariants.sh b/blocksuite/native-playground/scripts/check-invariants.sh deleted file mode 100755 index b3845abaaa..0000000000 --- a/blocksuite/native-playground/scripts/check-invariants.sh +++ /dev/null @@ -1,201 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" -REPO_ROOT="$(cd "$ROOT/../.." && pwd)" -cd "$ROOT" - -fail() { - echo "ERROR: $*" >&2 - exit 1 -} - -echo "==> Checking zero internal proc-macro crates" -if grep -rn 'proc-macro\s*=\s*true' crates/ Cargo.toml 2>/dev/null; then - fail "Internal proc-macro crates are forbidden in blocksuite/native-playground" -fi - -echo "==> Checking crates/ui domain isolation (no blocksuite/affine words)" -if grep -rniE '\b(blocksuite|affine)\b' crates/ui/src crates/ui/Cargo.toml 2>/dev/null; then - fail "crates/ui must not reference BlockSuite or AFFiNE domain terms" -fi - -echo "==> Checking crates/doc GUI isolation and forbid(unsafe_code)" -if grep -rnE '^\s*(ui|wgpu|objc2|web-sys)\b' crates/doc/Cargo.toml 2>/dev/null; then - fail "crates/doc must not depend on GUI/platform crates (ui, wgpu, objc2, web-sys)" -fi -if ! grep -q '#!\[forbid(unsafe_code)\]' crates/doc/src/lib.rs; then - fail "crates/doc/src/lib.rs must declare #![forbid(unsafe_code)]" -fi - -echo "==> Checking no Instant::now / SystemTime::now outside crates/ui/src/platform" -WALL_CLOCK_HITS=$( - grep -rnE '(Instant::now|SystemTime::now)\s*\(' crates/ \ - --include='*.rs' \ - | grep -v '^crates/ui/src/platform/' \ - || true -) -if [ -n "$WALL_CLOCK_HITS" ]; then - echo "$WALL_CLOCK_HITS" >&2 - fail "Instant::now() / SystemTime::now() is forbidden outside crates/ui/src/platform/" -fi - -echo "==> Checking zero tester branches inside crates/playground/src layout/view code" -if grep -rn 'is_headless' crates/playground/src 2>/dev/null; then - fail "is_headless branches are forbidden in crates/playground/src" -fi -TESTER_CFG_HITS=$( - grep -rnE '#\[cfg\((any\(test|feature\s*=\s*"harness")' crates/playground/src 2>/dev/null \ - | grep -Ev '^crates/playground/src/(bin/|rich_text/mod\.rs:)' \ - || true -) -if [ -n "$TESTER_CFG_HITS" ]; then - echo "$TESTER_CFG_HITS" >&2 - fail "Inline harness/test cfg branches are forbidden in shipping crates/playground/src modules" -fi - -echo "==> Checking Rust module structure, visibility, orphaned files, and per-file LOC" -python3 - <<'PY' -import re -import sys -from pathlib import Path - -errors = [] -roots = [Path("crates/doc/src"), Path("crates/playground/src")] - -def strip_cfg_test_mods(src: str) -> str: - """Remove `#[cfg(test)] mod { ... }` blocks while preserving line numbers.""" - lines = src.splitlines() - out = [] - i = 0 - n = len(lines) - while i < n: - s = lines[i].strip() - if s == "#[cfg(test)]" and i + 1 < n and re.match(r"^(pub(\([^)]*\))?\s+)?mod\s+\w+\s*\{", lines[i + 1].strip()): - depth = 0 - started = False - out.append("") - i += 1 - while i < n: - line = lines[i] - if "{" in line: - started = True - depth += line.count("{") - line.count("}") - out.append("") - i += 1 - if started and depth <= 0: - break - continue - out.append(lines[i]) - i += 1 - return "\n".join(out) - -for src_root in roots: - rs_files = sorted(src_root.rglob("*.rs")) - declared_modules = set() - # Root entry points are always live. - for entry in ("lib.rs", "main.rs"): - if (src_root / entry).exists(): - declared_modules.add((src_root / entry).resolve()) - for bin_file in (src_root / "bin").glob("*.rs") if (src_root / "bin").exists() else []: - declared_modules.add(bin_file.resolve()) - for bin_main in (src_root / "bin").glob("*/main.rs") if (src_root / "bin").exists() else []: - declared_modules.add(bin_main.resolve()) - - mod_decl_re = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*;") - for p in rs_files: - text = p.read_text(encoding="utf-8") - parent = p.parent - # Track declared child modules for orphan detection. - for line in text.splitlines(): - m = mod_decl_re.match(line) - if m: - mod_name = m.group(1) - base_dir = parent if p.name in ("lib.rs", "main.rs", "mod.rs") else parent / p.stem - cand_file = base_dir / f"{mod_name}.rs" - cand_mod = base_dir / mod_name / "mod.rs" - if cand_file.exists(): - declared_modules.add(cand_file.resolve()) - if cand_mod.exists(): - declared_modules.add(cand_mod.resolve()) - - # Rule (g): no `.rs` coexisting beside `/`. - if p.name not in ("lib.rs", "main.rs", "mod.rs") and (parent / p.stem).is_dir(): - errors.append(f"{p}: coexists beside directory {parent / p.stem}/; move into {parent / p.stem}/mod.rs") - - non_test = strip_cfg_test_mods(text) - non_test_lines = non_test.splitlines() - - # Rule (c): no `super::super::` outside `mod tests`. - for lineno, line in enumerate(non_test_lines, 1): - if "super::super::" in line: - errors.append(f"{p}:{lineno}: forbidden `super::super::` outside `mod tests`") - - # Rules (b, c): sibling `src//.rs` must not import via `crate::::`. - rel = p.relative_to(src_root) - if len(rel.parts) >= 2 and p.name != "mod.rs" and rel.parts[0] != "bin": - parent_mod = rel.parts[0] - pat = f"crate::{parent_mod}::" - for lineno, line in enumerate(non_test_lines, 1): - if pat in line: - errors.append(f"{p}:{lineno}: use `super::` instead of `{pat}` inside submodule") - - # Rule (g): <= 800 non-test lines on every `.rs` file in `crates/doc/src` and `crates/playground/src`. - actual_non_test = len([1 for orig, stripped in zip(text.splitlines(), non_test_lines) if orig == stripped]) - if actual_non_test > 800: - errors.append(f"{p}: {actual_non_test} non-test lines exceeds ceiling of 800") - - # Orphaned .rs file check. - for p in rs_files: - if p.resolve() not in declared_modules: - errors.append(f"{p}: orphaned .rs file not declared by any `mod ;`") - -if errors: - for e in errors: - print(f"ERROR: {e}", file=sys.stderr) - sys.exit(1) -print("Rust module structure & LOC checks passed.") -PY - -echo "==> Checking crates/ui LOC ceiling" -UI_LOC_CEILING=95000 -UI_LOC=$(find crates/ui/src -name '*.rs' -print0 | xargs -0 cat | wc -l | tr -d ' ') -echo "crates/ui/src total LOC: $UI_LOC (ceiling: $UI_LOC_CEILING)" -if [ "$UI_LOC" -gt "$UI_LOC_CEILING" ]; then - fail "crates/ui/src LOC ($UI_LOC) exceeds ceiling ($UI_LOC_CEILING)" -fi - -echo "==> Checking workflow YAML validity" -if [ -f "$REPO_ROOT/.github/workflows/native-playground.yml" ] && [ -f "$REPO_ROOT/.github/workflows/build-test.yml" ]; then - if python3 -c "import yaml" 2>/dev/null; then - python3 -c " -import yaml, sys -for p in sys.argv[1:]: - with open(p) as f: - yaml.safe_load(f) - print('YAML OK:', p) -" "$REPO_ROOT/.github/workflows/build-test.yml" "$REPO_ROOT/.github/workflows/native-playground.yml" - elif command -v ruby >/dev/null 2>&1; then - ruby -ryaml -e 'ARGV.each { |p| YAML.load_file(p); puts "YAML OK: #{p}" }' \ - "$REPO_ROOT/.github/workflows/build-test.yml" "$REPO_ROOT/.github/workflows/native-playground.yml" - else - echo "Skipping YAML parse check (neither python3-yaml nor ruby installed)" - fi -fi - -echo "==> Checking CARGO_ENCODED_RUSTFLAGS isolation (no leaked root NAPI linker flags)" -if ! LINK_LOG=$(CARGO_ENCODED_RUSTFLAGS="" cargo rustc -p playground --bin bs-harness --features harness -- -C metadata="linkcheck-$$" --print link-args 2>&1); then - echo "$LINK_LOG" >&2 - fail "cargo rustc link-args check failed" -fi -if ! echo "$LINK_LOG" | grep -qE '(cc|clang|gcc|ld|lld|"[^"]*bs_harness|bs_harness)'; then - echo "$LINK_LOG" >&2 - fail "cargo rustc did not emit a linker invocation (cache bypass failed)" -fi -if echo "$LINK_LOG" | grep -E '(-all_load|-undefined[ ,]+dynamic_lookup|-z[ ,]+nodelete)' >/dev/null 2>&1; then - echo "$LINK_LOG" >&2 - fail "Detected leaked root NAPI linker flags in rustc invocation" -fi - -echo "All static invariants passed." diff --git a/blocksuite/playground/apps/_common/sync/room/__tests__/room-sync.spec.ts b/blocksuite/playground/apps/_common/sync/room/__tests__/room-sync.spec.ts index 4914781ce9..ec42065d7d 100644 --- a/blocksuite/playground/apps/_common/sync/room/__tests__/room-sync.spec.ts +++ b/blocksuite/playground/apps/_common/sync/room/__tests__/room-sync.spec.ts @@ -22,7 +22,7 @@ import { RoomWebSocketClient, } from '../index.js'; -const NATIVE_DIR = resolve(__dirname, '../../../../../../native-playground'); +const NATIVE_DIR = resolve(__dirname, '../../../../../../../packages/frontend'); const RELAY_BIN = process.env.BS_RELAY_BIN ?? resolve(NATIVE_DIR, 'target/debug/bs-relay'); const DRIVER_BIN = diff --git a/blocksuite/playground/vitest.config.ts b/blocksuite/playground/vitest.config.ts index 5e8243355f..fa63853a5b 100644 --- a/blocksuite/playground/vitest.config.ts +++ b/blocksuite/playground/vitest.config.ts @@ -8,7 +8,7 @@ export default { test: { include: [ 'apps/_common/sync/room/__tests__/**/*.spec.ts', - '../native-playground/tokens/surface-oracle.spec.mjs', + '../crates/oracle/surface-oracle.spec.mjs', ], testTimeout: 60_000, hookTimeout: 30_000, diff --git a/packages/backend/AGENTS.md b/packages/backend/AGENTS.md index 1d894cff45..df21ac6e9f 100644 --- a/packages/backend/AGENTS.md +++ b/packages/backend/AGENTS.md @@ -8,7 +8,7 @@ It excludes `native/` and `server/` and does not join the root `Cargo.toml` work - `tools/frame-audit`: shared frame snapshot schema (`FrameSnapshot`, `DebugElementSnapshot`) and audit engine (`audit_frame_snapshot`, `rules::ALL`). It depends on `serde` only. - `blocksuite/native-playground/crates/ui` depends on it by path and re-exports it. + `packages/ui/ui` depends on it by path and re-exports it. Keep both workspaces' tests green when you change it. - `test-db-harness` (library `test_db_harness`, binary `affine-test-env`): PostgreSQL and Redis harness for server tests. @@ -106,4 +106,4 @@ cargo clippy --locked --workspace --all-targets -- -D warnings cargo test --locked --workspace ``` -After you change `tools/frame-audit`, also run `cargo test --locked -p ui --features harness` in `blocksuite/native-playground`. +After you change `tools/frame-audit`, also run `cargo test --locked -p ui --features harness` in `packages/frontend`. diff --git a/packages/common/store/AGENTS.md b/packages/common/store/AGENTS.md new file mode 100644 index 0000000000..511365b3a9 --- /dev/null +++ b/packages/common/store/AGENTS.md @@ -0,0 +1,17 @@ +# Working in `packages/common/store/` (for agents) + +`packages/common/store/` holds the client storage and sans-I/O sync domain crate. +This directory belongs to the client Cargo workspace rooted at `packages/frontend/Cargo.toml`. + +## Domain boundaries and invariants + +- `packages/common/store/` declares `#![forbid(unsafe_code)]` and has zero GUI or platform dependencies. + Never depend on `ui`, `wgpu`, `objc2`, or `web-sys` rendering types. + +- Keep `rust-toolchain.toml` (`1.98.1` with `wasm32-unknown-unknown`) and `rustfmt.toml` (`edition = "2024"`) byte-identical to `packages/frontend/`. + +- This crate is the sole writer for AFFiNE root workspace metadata (`meta.pages` and `spaces[pageId]`) and workspace SQLite/IndexedDB tables. + +- Keep SQLite schema migrations frozen at the `0.27.5` five-step contract and share `.db` in place with legacy clients. + +- Keep every `.rs` file at or below 800 non-test lines and follow the module rules in `blocksuite/crates/AGENTS.md`. diff --git a/packages/common/store/CLAUDE.md b/packages/common/store/CLAUDE.md new file mode 100644 index 0000000000..43c994c2d3 --- /dev/null +++ b/packages/common/store/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/packages/common/store/rust-toolchain.toml b/packages/common/store/rust-toolchain.toml new file mode 100644 index 0000000000..bfd155b5c2 --- /dev/null +++ b/packages/common/store/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "1.98.1" +components = ["rustfmt", "clippy"] +targets = ["wasm32-unknown-unknown"] diff --git a/packages/common/store/rustfmt.toml b/packages/common/store/rustfmt.toml new file mode 100644 index 0000000000..f216078d96 --- /dev/null +++ b/packages/common/store/rustfmt.toml @@ -0,0 +1 @@ +edition = "2024" diff --git a/packages/frontend/AGENTS.md b/packages/frontend/AGENTS.md new file mode 100644 index 0000000000..c7e40b4ce7 --- /dev/null +++ b/packages/frontend/AGENTS.md @@ -0,0 +1,48 @@ +# Working in `packages/frontend/` (for agents) + +`packages/frontend/` holds the client Rust Cargo workspace (`Cargo.toml` and `Cargo.lock`) alongside legacy TypeScript frontend packages. +It uses `resolver = "3"`, edition 2024, and its own `rust-toolchain.toml` (`1.98.1` with `wasm32-unknown-unknown`) and `rustfmt.toml`. + +## Workspace boundaries and four-domain guards + +- `packages/frontend/Cargo.toml` lists every client member crate explicitly (`../ui/ui`, `../../blocksuite/crates/doc`, and `../../blocksuite/crates/playground`). + Never use directory wildcards that can scan asset directories. +- `packages/frontend/Cargo.toml` excludes `native` and `mobile-native`. + Those legacy crates remain members of the root `Cargo.toml` workspace. +- Legacy directories (`native/`, `mobile-native/`, and `apps/`) carry a `1.97.1` `rust-toolchain.toml` file that matches the repository root byte-for-byte. + `native/` and `mobile-native/` also carry a `rustfmt.toml` file that matches the repository root byte-for-byte. +- Client trees (`packages/frontend/`, `packages/ui/`, `blocksuite/crates/`, and `packages/common/store/`) share byte-identical `1.98.1` `rust-toolchain.toml` and client `rustfmt.toml` files. +- `scripts/check-invariants.sh` discovers client workspace members from `cargo metadata --locked --no-deps`, enforces four-domain acyclic dependencies (zero reverse edges), checks domain isolation, wall-clock isolation, zero tester branches, module structure, LOC ceilings, toolchain/rustfmt alignment, `workspace_root` resolution, `rustup show active-toolchain` for legacy (`1.97.1`) and client (`1.98.1`) directories, workflow YAML validity, and `CARGO_ENCODED_RUSTFLAGS=""` link-flag isolation. +- See `packages/ui/AGENTS.md`, `blocksuite/crates/AGENTS.md`, and `packages/common/store/AGENTS.md` for domain-specific invariants. + +### Performance guardrail and theme/style oracle + +- **`perf/` (`schema.json`, `accepted.json`, `compare-n3.mjs`, `compare-n3.test.mjs`)**: Zero-dependency rolling `N-3` CI comparator with strict schema validation and rerun history anchoring (`--run-id` `created_at` cutoff + pagination). Deterministic byte sizes (`artifacts_bytes.*`) and work counters (non-`_ms` `benchmarks.*`) are hard-gated at strictly `> 10%` (`--fail-on-regression` exits `1`); shared-runner wall-clock timings (`benchmarks.*_ms` at `> 10%`, `ci_wall_ms.*` at `> 10%` and `> 15_000 ms`) are report-only `ADVISORY_SLOWDOWN`. Intentional increases are acknowledged via `{ metric, accepted_value, reason }` ceiling entries in `packages/frontend/perf/accepted.json` (with report-only `stale_acceptances` once the rolling baseline catches up). Unmeasured sub-keys are omitted or `null` (never padded with synthetic `0`s) so newly introduced metrics transition through `BOOTSTRAP`. + +## Build & verification commands + +Always clear inherited root rustflags: + +```sh +CARGO_ENCODED_RUSTFLAGS="" cargo fmt --all -- --check +CARGO_ENCODED_RUSTFLAGS="" cargo clippy --locked --workspace --all-targets --features harness -- -D warnings +CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p ui -p playground --target wasm32-unknown-unknown +CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p blocksuite-playground-doc --no-default-features --target wasm32-unknown-unknown +CARGO_ENCODED_RUSTFLAGS="" cargo test --locked --workspace +CARGO_ENCODED_RUSTFLAGS="" cargo test --locked --workspace --features harness +CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render --theme dark --mode page --out frame.png --snapshot frame.json +CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- probes +CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- bench --json perf-metrics.json +CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render-surface-sample --theme light --out surface-light.png --snapshot surface-light.json +CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render-editor artifacts/editor +CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render --state slash_menu_open --out slash.png --snapshot slash.json +CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- audit-states +CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- fps-check +CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- record-demo artifacts/demo +./scripts/check-invariants.sh +node --test perf/compare-n3.test.mjs +node ../ui/tokens/extract-tokens.mjs --check +rustc --edition 2024 --test -D warnings ../ui/tokens/tokens.rs -o /tmp/tokens_test && /tmp/tokens_test +rustc --edition 2024 --test -D warnings ../ui/tokens/icons.rs -o /tmp/icons_test && /tmp/icons_test +rm -f /tmp/tokens_test /tmp/icons_test +``` diff --git a/packages/frontend/CLAUDE.md b/packages/frontend/CLAUDE.md new file mode 100644 index 0000000000..43c994c2d3 --- /dev/null +++ b/packages/frontend/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/blocksuite/native-playground/Cargo.lock b/packages/frontend/Cargo.lock similarity index 100% rename from blocksuite/native-playground/Cargo.lock rename to packages/frontend/Cargo.lock diff --git a/blocksuite/native-playground/Cargo.toml b/packages/frontend/Cargo.toml similarity index 96% rename from blocksuite/native-playground/Cargo.toml rename to packages/frontend/Cargo.toml index c1406af4d6..d3e63c7649 100644 --- a/blocksuite/native-playground/Cargo.toml +++ b/packages/frontend/Cargo.toml @@ -1,11 +1,16 @@ [workspace] resolver = "3" members = [ - "crates/ui", - "crates/doc", - "crates/playground", + "../ui/ui", + "../../blocksuite/crates/doc", + "../../blocksuite/crates/playground", ] -default-members = ["crates/ui", "crates/doc", "crates/playground"] +default-members = [ + "../ui/ui", + "../../blocksuite/crates/doc", + "../../blocksuite/crates/playground", +] +exclude = ["native", "mobile-native"] [workspace.package] version = "0.1.0" diff --git a/packages/frontend/apps/android/App/app/build.gradle b/packages/frontend/apps/android/App/app/build.gradle index e9aa26defe..0ffee2c4c3 100644 --- a/packages/frontend/apps/android/App/app/build.gradle +++ b/packages/frontend/apps/android/App/app/build.gradle @@ -196,8 +196,9 @@ android.applicationVariants.configureEach { variant -> def variantName = "${variant.name.substring(0,1).toUpperCase()}${variant.name.substring(1)}" def t = tasks.register("generate${variantName}UniFFIBindings", Exec) { workingDir "${project.projectDir}" + def rootManifest = file("${project.projectDir}/../../../../../../Cargo.toml").canonicalPath // Runs the bindings generation, note that you must have uniffi-bindgen installed and in your PATH environment variable - commandLine "${cargoPath}", 'run', '--bin', 'uniffi-bindgen', 'generate', '--library', "${buildDir}/rustJniLibs/android/${nativeAbi}/libaffine_mobile_native.so", '--language', 'kotlin', '--out-dir', "${project.projectDir}/src/main/java" + commandLine "${cargoPath}", 'run', '--manifest-path', "${rootManifest}", '--bin', 'uniffi-bindgen', 'generate', '--library', "${buildDir}/rustJniLibs/android/${nativeAbi}/libaffine_mobile_native.so", '--language', 'kotlin', '--out-dir', "${project.projectDir}/src/main/java" dependsOn(nativeLibraries) } tasks.named("compile${variantName}Kotlin").configure { dependsOn(t) } diff --git a/packages/frontend/apps/ios/App/xc-universal-binary.sh b/packages/frontend/apps/ios/App/xc-universal-binary.sh index 045faae8f9..454283a732 100644 --- a/packages/frontend/apps/ios/App/xc-universal-binary.sh +++ b/packages/frontend/apps/ios/App/xc-universal-binary.sh @@ -43,7 +43,9 @@ FFI_TARGET=${1} SRC_ROOT=${2} # Keep Cargo artifacts in a stable repo-local location so Xcode does not inherit # a sandbox-specific CARGO_TARGET_DIR from the parent shell. -export CARGO_TARGET_DIR="$SRC_ROOT/../../../target" +REPO_ROOT="$(cd "$SRC_ROOT/../../.." && pwd)" +MANIFEST_PATH="$REPO_ROOT/Cargo.toml" +export CARGO_TARGET_DIR="$REPO_ROOT/target" # buildvariant from our xcconfigs BUILDVARIANT=$(echo "${3}" | tr '[:upper:]' '[:lower:]') @@ -76,18 +78,18 @@ for arch in $ARCHS; do # Intel iOS simulator export CFLAGS_x86_64_apple_ios="-target x86_64-apple-ios" - $CARGO rustc -p "${FFI_TARGET}" --lib --crate-type staticlib ${CARGO_PROFILE_FLAG:+$CARGO_PROFILE_FLAG} --target x86_64-apple-ios --features use-as-lib + $CARGO rustc --manifest-path "$MANIFEST_PATH" -p "${FFI_TARGET}" --lib --crate-type staticlib ${CARGO_PROFILE_FLAG:+$CARGO_PROFILE_FLAG} --target x86_64-apple-ios --features use-as-lib SIM_X86_64_LIB="$CARGO_TARGET_DIR/x86_64-apple-ios/${RELFLAG}/lib${FFI_TARGET}.a" ;; arm64) if [ $IS_SIMULATOR -eq 0 ]; then # Hardware iOS targets - $CARGO rustc -p "${FFI_TARGET}" --lib --crate-type staticlib ${CARGO_PROFILE_FLAG:+$CARGO_PROFILE_FLAG} --target aarch64-apple-ios --features use-as-lib + $CARGO rustc --manifest-path "$MANIFEST_PATH" -p "${FFI_TARGET}" --lib --crate-type staticlib ${CARGO_PROFILE_FLAG:+$CARGO_PROFILE_FLAG} --target aarch64-apple-ios --features use-as-lib DEVICE_ARM64_LIB="$CARGO_TARGET_DIR/aarch64-apple-ios/${RELFLAG}/lib${FFI_TARGET}.a" else # Apple Silicon iOS simulator - $CARGO rustc -p "${FFI_TARGET}" --lib --crate-type staticlib ${CARGO_PROFILE_FLAG:+$CARGO_PROFILE_FLAG} --target aarch64-apple-ios-sim --features use-as-lib + $CARGO rustc --manifest-path "$MANIFEST_PATH" -p "${FFI_TARGET}" --lib --crate-type staticlib ${CARGO_PROFILE_FLAG:+$CARGO_PROFILE_FLAG} --target aarch64-apple-ios-sim --features use-as-lib SIM_ARM64_LIB="$CARGO_TARGET_DIR/aarch64-apple-ios-sim/${RELFLAG}/lib${FFI_TARGET}.a" fi ;; @@ -106,7 +108,7 @@ else exit 1 fi -$CARGO run -p affine_mobile_native --features use-as-lib --bin uniffi-bindgen generate --no-format --library "$BINDGEN_LIB" --language swift --out-dir "$SRCROOT/../../ios/App/App/uniffi" +$CARGO run --manifest-path "$MANIFEST_PATH" -p affine_mobile_native --features use-as-lib --bin uniffi-bindgen generate --no-format --library "$BINDGEN_LIB" --language swift --out-dir "$SRCROOT/../../ios/App/App/uniffi" if [ $IS_SIMULATOR -eq 0 ]; then cp "$DEVICE_ARM64_LIB" "$OUTPUT_LIB" diff --git a/packages/frontend/apps/rust-toolchain.toml b/packages/frontend/apps/rust-toolchain.toml new file mode 100644 index 0000000000..30a41bc1f6 --- /dev/null +++ b/packages/frontend/apps/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.97.1" +profile = "default" diff --git a/packages/frontend/mobile-native/rust-toolchain.toml b/packages/frontend/mobile-native/rust-toolchain.toml new file mode 100644 index 0000000000..30a41bc1f6 --- /dev/null +++ b/packages/frontend/mobile-native/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.97.1" +profile = "default" diff --git a/packages/frontend/mobile-native/rustfmt.toml b/packages/frontend/mobile-native/rustfmt.toml new file mode 100644 index 0000000000..bf7df1cb63 --- /dev/null +++ b/packages/frontend/mobile-native/rustfmt.toml @@ -0,0 +1,13 @@ +edition = "2024" +max_width = 120 +style_edition = "2024" + +hard_tabs = false +tab_spaces = 2 + +format_strings = true +unstable_features = true +wrap_comments = true + +group_imports = "StdExternalCrate" +imports_granularity = "Crate" diff --git a/packages/frontend/native/rust-toolchain.toml b/packages/frontend/native/rust-toolchain.toml new file mode 100644 index 0000000000..30a41bc1f6 --- /dev/null +++ b/packages/frontend/native/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.97.1" +profile = "default" diff --git a/packages/frontend/native/rustfmt.toml b/packages/frontend/native/rustfmt.toml new file mode 100644 index 0000000000..bf7df1cb63 --- /dev/null +++ b/packages/frontend/native/rustfmt.toml @@ -0,0 +1,13 @@ +edition = "2024" +max_width = 120 +style_edition = "2024" + +hard_tabs = false +tab_spaces = 2 + +format_strings = true +unstable_features = true +wrap_comments = true + +group_imports = "StdExternalCrate" +imports_granularity = "Crate" diff --git a/packages/frontend/perf/README.md b/packages/frontend/perf/README.md new file mode 100644 index 0000000000..440ba52e4a --- /dev/null +++ b/packages/frontend/perf/README.md @@ -0,0 +1,85 @@ +# Native Playground CI Performance Guardrail + +Zero-dependency `N-3` regression detector for `darksky/native-playground`. + +## Metrics Schema (`schema.json`) + +Every CI run emits `perf-metrics.json` containing: + +- `schema_version`: integer `1`. +- `commit`: full 40-character lowercase Git SHA. +- `timestamp_utc`: ISO-8601 UTC timestamp. +- `ci_wall_ms`: shared-runner wall-clock durations (`lint_and_wasm`, `headless_linux`, `total_critical_path`). +- `artifacts_bytes`: deterministic build output sizes (`web_wasm_raw`, `web_wasm_gzip`, `headless_bin`). +- `benchmarks`: deterministic engine timings (`{ median, p95 }`, with `p95 >= median`) and work counters: + - `doc_1k_edits_ms` + - `room_sync_1k_ops_ms` + - `layout_10k_blocks_cold_ms` + - `layout_single_keystroke_ms` + - `layout_single_keystroke_blocks_relayout` + - `edgeless_1k_pan_zoom_frame_ms` + - `headless_frame_render_ms` + +Individual sub-keys inside `ci_wall_ms`, `artifacts_bytes`, and `benchmarks` are optional (or `null`) when a benchmark or artifact is not yet produced by CI. Never emit synthetic `0` placeholders for unmeasured metrics: omitted or `null` baseline keys transition cleanly through `BOOTSTRAP` when first introduced instead of triggering false `0 -> positive` (`+inf%`) regressions. + +## Regression Gate vs Advisory Timings + +Current commit metrics are compared against the completed push run from **3 distinct prior commits (`N-3`)** strictly older than the commit under test (`--current-created-at` or the commit's earliest push run on the branch). + +- **Library / seeding mode (default)**: If `N-3` has no valid `perf-metrics.json` artifact, the comparator walks `N-3 -> N-2 -> N-1`; with 0 valid prior baselines (such as the initial seeding runs of a new integration branch like `darksky/np/mobile` before 3 runs exist) it emits `baseline_depth: "bootstrap"`. `--require-baseline` requires at least `N-1` (`baseline !== null`). +- **Strict `N-3` CI mode (`--require-n3`)**: Used on established branches (`native-playground.yml`). Requires `baseline_depth === "N-3"`, a 40-char `baseline_commit`, zero unacknowledged `DROPPED` metrics (`baseline != null && current == null`), and zero unacknowledged `BOOTSTRAP` metrics (`baseline == null && current != null`). If all prior artifacts expire after retention, set `NP_ALLOW_PERF_BOOTSTRAP=1` for 3 seeding runs on the integration branch to re-establish `N-3`. + +1. **Deterministic hard gate (`artifacts_bytes.*`, non-`_ms` work counters under `benchmarks.*`, and unacknowledged `DROPPED` / `--require-n3` `BOOTSTRAP` metrics)**: + - Flagged as `REGRESSED` (`DROPPED` when missing in `current`, `BOOTSTRAP` when missing in `N-3` under `--require-n3`; sets `has_hard_regression: true`) whenever `(current - baseline) / baseline * 100 > 10.0%` (strictly greater than `--threshold-pct`), or when `baseline === 0` and `current > 0`. + - `--fail-on-regression` exits `1` when `has_hard_regression` is `true`. +2. **Shared-runner wall-clock advisories (`benchmarks.*_ms` and `ci_wall_ms.*`)**: + - `benchmarks.*_ms` exceeding `> 10.0%`, and `ci_wall_ms.*` exceeding both `> 10.0%` and `> 15000` ms (`--ci-wall-min-delta-ms`), are reported as `ADVISORY_SLOWDOWN` (`advisory: true`, `regressed: false`, sets `has_advisory_slowdown: true`). + - Advisory timings are surfaced in the Markdown summary and `advisory_metrics` in `perf-verdict.json` for investigation on pinned hardware without failing shared-runner CI. + +## Lifecycle & Regression Acknowledgements (`accepted.json`) + +Intentional increases, newly introduced metrics, and retired metrics are recorded in `perf/accepted.json` (loaded by default, or via `--accepted `): + +```json +[ + { + "metric": "artifacts_bytes.web_wasm_gzip", + "accepted_value": 800000, + "reason": "Bundled new rich-text feature" + }, + { + "metric": "artifacts_bytes.headless_bin", + "action": "bootstrap", + "reason": "Newly introduced metric rolling into N-3" + }, + { + "metric": "benchmarks.layout_single_keystroke_blocks_relayout", + "action": "drop", + "reason": "Retired obsolete counter" + } +] +``` + +- **Value ceiling (`action: "ceiling"`, default)**: When a metric triggers against the rolling baseline and `current <= accepted_value`, the row is marked `ACCEPTED` (`regressed: false`). Once `baseline >= accepted_value`, it is reported in `stale_acceptances`. +- **Intentional new metric (`action: "bootstrap"`)**: Marks `baseline == null && current != null` as `ACCEPTED_BOOTSTRAP` (`regressed: false`) under `--require-n3` for the 3-commit rolling window; once `N-3` includes the metric, it is reported in `stale_acceptances` for pruning. +- **Intentional metric removal (`action: "drop"`)**: Marks `baseline != null && current == null` as `ACCEPTED_DROP` (`regressed: false`); once `N-3` no longer contains the metric, it is reported in `stale_acceptances` for pruning. + +## Usage + +```sh +node packages/frontend/perf/compare-n3.mjs \ + --fetch-github \ + --repo toeverything/AFFiNE \ + --branch darksky/native-playground \ + --workflow native-playground.yml \ + --run-id "$GITHUB_RUN_ID" \ + --current artifacts/perf-metrics.json \ + --json-out artifacts/perf-verdict.json \ + --fail-on-regression +``` + +## Self-Tests + +```sh +node --test packages/frontend/perf/compare-n3.test.mjs +``` diff --git a/blocksuite/native-playground/perf/accepted.json b/packages/frontend/perf/accepted.json similarity index 100% rename from blocksuite/native-playground/perf/accepted.json rename to packages/frontend/perf/accepted.json diff --git a/blocksuite/native-playground/perf/compare-n3.mjs b/packages/frontend/perf/compare-n3.mjs similarity index 83% rename from blocksuite/native-playground/perf/compare-n3.mjs rename to packages/frontend/perf/compare-n3.mjs index 142c04ca18..e2faeb6509 100644 --- a/blocksuite/native-playground/perf/compare-n3.mjs +++ b/packages/frontend/perf/compare-n3.mjs @@ -73,7 +73,13 @@ const INTEGER_METRIC_KEYS = new Set([ ...Array.from(BENCHMARK_COUNTER_KEYS, k => `benchmarks.${k}`), ]); -const ALLOWED_ACCEPTED_KEYS = new Set(['metric', 'accepted_value', 'reason']); +const ALLOWED_ACCEPTED_KEYS = new Set([ + 'metric', + 'action', + 'accepted_value', + 'reason', +]); +const ALLOWED_ACCEPTED_ACTIONS = new Set(['ceiling', 'bootstrap', 'drop']); function isPlainObject(v) { return v !== null && typeof v === 'object' && !Array.isArray(v); @@ -227,21 +233,42 @@ export function validateAcceptedEntries(entries, label = 'accepted.json') { } seenMetrics.add(metric); + const action = entry.action === undefined ? 'ceiling' : entry.action; if ( - typeof entry.accepted_value !== 'number' || - !Number.isFinite(entry.accepted_value) || - entry.accepted_value < 0 + typeof action !== 'string' || + !ALLOWED_ACCEPTED_ACTIONS.has(action) ) { throw new Error( - `${label}[${idx}].accepted_value must be a finite number >= 0` + `${label}[${idx}].action must be one of ceiling, bootstrap, drop` ); } - if ( - INTEGER_METRIC_KEYS.has(metric) && - !Number.isInteger(entry.accepted_value) + + let acceptedValue = null; + if (action === 'ceiling') { + if ( + typeof entry.accepted_value !== 'number' || + !Number.isFinite(entry.accepted_value) || + entry.accepted_value < 0 + ) { + throw new Error( + `${label}[${idx}].accepted_value must be a finite number >= 0` + ); + } + if ( + INTEGER_METRIC_KEYS.has(metric) && + !Number.isInteger(entry.accepted_value) + ) { + throw new Error( + `${label}[${idx}].accepted_value must be an integer for ${metric}` + ); + } + acceptedValue = entry.accepted_value; + } else if ( + entry.accepted_value !== undefined && + entry.accepted_value !== null ) { throw new Error( - `${label}[${idx}].accepted_value must be an integer for ${metric}` + `${label}[${idx}].accepted_value is only valid for ceiling entries (got action="${action}")` ); } @@ -250,7 +277,8 @@ export function validateAcceptedEntries(entries, label = 'accepted.json') { } return { metric, - accepted_value: entry.accepted_value, + action, + accepted_value: acceptedValue, reason: entry.reason.trim(), }; }); @@ -432,15 +460,52 @@ function evaluateSingleMetric({ accepted, thresholdPct, ciWallMinDeltaMs, + requireN3 = false, }) { const cur = lookupMetricEntry(current, category, field); const base = lookupMetricEntry(baseline, category, field); const n1Val = lookupMetricEntry(n1, category, field); const n2Val = lookupMetricEntry(n2, category, field); + const match = accepted.find(a => a.metric === key) ?? null; - if (!cur) return null; + if (!cur && !base) return null; + + if (!cur) { + const isAcceptedDrop = match?.action === 'drop'; + return { + key, + category, + unit, + deterministic_hard_gate: true, + current: null, + current_p95: null, + baseline: base.value, + baseline_p95: base.p95, + n1: n1Val?.value ?? null, + n2: n2Val?.value ?? null, + delta: null, + delta_pct: null, + delta_pct_infinite: false, + regressed: !isAcceptedDrop, + advisory: false, + accepted: isAcceptedDrop + ? { + accepted: true, + action: 'drop', + accepted_value: null, + reason: match.reason, + } + : null, + stale_acceptance: null, + status: isAcceptedDrop ? 'ACCEPTED_DROP' : 'DROPPED', + }; + } if (!base) { + const isAcceptedBootstrap = match?.action === 'bootstrap'; + const unacknowledgedUnderStrictN3 = Boolean( + requireN3 && !isAcceptedBootstrap + ); return { key, category, @@ -455,11 +520,18 @@ function evaluateSingleMetric({ delta: null, delta_pct: null, delta_pct_infinite: false, - regressed: false, + regressed: unacknowledgedUnderStrictN3, advisory: false, - accepted: null, + accepted: isAcceptedBootstrap + ? { + accepted: true, + action: 'bootstrap', + accepted_value: null, + reason: match.reason, + } + : null, stale_acceptance: null, - status: 'BOOTSTRAP', + status: isAcceptedBootstrap ? 'ACCEPTED_BOOTSTRAP' : 'BOOTSTRAP', }; } @@ -471,18 +543,28 @@ function evaluateSingleMetric({ ciWallMinDeltaMs, }); - const match = accepted.find(a => a.metric === key) ?? null; const staleAcceptance = - match && base.value >= match.accepted_value - EPS + match?.action === 'ceiling' && base.value >= match.accepted_value - EPS ? { key, unit, + action: 'ceiling', baseline: base.value, current: cur.value, accepted_value: match.accepted_value, reason: match.reason, } - : null; + : match?.action === 'bootstrap' + ? { + key, + unit, + action: 'bootstrap', + baseline: base.value, + current: cur.value, + accepted_value: null, + reason: match.reason, + } + : null; let regressed = false; let advisory = false; @@ -490,10 +572,14 @@ function evaluateSingleMetric({ let acceptanceInfo = null; if (check.triggered) { - if (match && cur.value <= match.accepted_value + EPS) { + if ( + match?.action === 'ceiling' && + cur.value <= match.accepted_value + EPS + ) { status = 'ACCEPTED'; acceptanceInfo = { accepted: true, + action: 'ceiling', accepted_value: match.accepted_value, reason: match.reason, }; @@ -549,6 +635,8 @@ export function comparePerfMetrics({ baselineDepth = baseline ? 'N-3' : 'bootstrap', thresholdPct = DEFAULT_THRESHOLD_PCT, ciWallMinDeltaMs = DEFAULT_CI_WALL_MIN_DELTA_MS, + requireBaseline = false, + requireN3 = false, }) { validatePerfMetrics(current, 'current'); if (baseline !== null) validatePerfMetrics(baseline, 'baseline'); @@ -573,6 +661,7 @@ export function comparePerfMetrics({ accepted: validatedAccepted, thresholdPct, ciWallMinDeltaMs, + requireN3, }); if (row) metrics.push(row); } @@ -591,6 +680,7 @@ export function comparePerfMetrics({ accepted: validatedAccepted, thresholdPct, ciWallMinDeltaMs, + requireN3, }); if (row) metrics.push(row); } @@ -609,6 +699,7 @@ export function comparePerfMetrics({ accepted: validatedAccepted, thresholdPct, ciWallMinDeltaMs, + requireN3, }); if (row) metrics.push(row); } @@ -626,23 +717,50 @@ export function comparePerfMetrics({ const regressedMetrics = metrics.filter(m => m.regressed).map(mapSummary); const advisoryMetrics = metrics.filter(m => m.advisory).map(mapSummary); const acceptedMetrics = metrics - .filter(m => m.status === 'ACCEPTED') + .filter( + m => + m.status === 'ACCEPTED' || + m.status === 'ACCEPTED_BOOTSTRAP' || + m.status === 'ACCEPTED_DROP' + ) .map(m => ({ ...mapSummary(m), unit: m.unit, + action: m.accepted?.action ?? 'ceiling', accepted_value: m.accepted?.accepted_value ?? null, reason: m.accepted?.reason ?? null, })); const staleAcceptances = metrics .filter(m => m.stale_acceptance !== null) .map(m => m.stale_acceptance); + if (baseline !== null) { + for (const acc of validatedAccepted) { + if (acc.action === 'drop' && !metrics.some(m => m.key === acc.metric)) { + staleAcceptances.push({ + key: acc.metric, + unit: '', + action: 'drop', + baseline: null, + current: null, + accepted_value: null, + reason: acc.reason, + }); + } + } + } - const hasHardRegression = regressedMetrics.length > 0; + const resolvedDepth = baseline ? baselineDepth : 'bootstrap'; + const missingRequiredBaseline = Boolean( + (requireBaseline || requireN3) && baseline === null + ); + const invalidN3Depth = Boolean(requireN3 && resolvedDepth !== 'N-3'); + const hasHardRegression = + regressedMetrics.length > 0 || missingRequiredBaseline || invalidN3Depth; const hasAdvisorySlowdown = advisoryMetrics.length > 0; return { schema_version: 1, - baseline_depth: baseline ? baselineDepth : 'bootstrap', + baseline_depth: resolvedDepth, current_commit: current.commit ?? null, baseline_commit: baseline?.commit ?? null, n1_commit: n1?.commit ?? null, @@ -672,7 +790,15 @@ function formatValue(value, unit) { } function formatDeltaPct(metric) { - if (metric.status === 'BOOTSTRAP') return '—'; + if ( + metric.status === 'BOOTSTRAP' || + metric.status === 'ACCEPTED_BOOTSTRAP' + ) { + return '—'; + } + if (metric.status === 'DROPPED' || metric.status === 'ACCEPTED_DROP') { + return 'DROPPED'; + } if (metric.delta_pct_infinite) return '+inf%'; if (metric.delta_pct === null) return '—'; const sign = metric.delta_pct > 0 ? '+' : ''; @@ -706,10 +832,31 @@ export function renderMarkdownSummary(verdict) { ); lines.push(''); + if (verdict.has_hard_regression && verdict.baseline_depth !== 'N-3') { + lines.push('### Missing or Incomplete Required Baseline'); + lines.push(''); + lines.push( + `- Prior baseline history check failed (resolved \`baseline_depth: ${verdict.baseline_depth}\`).` + ); + lines.push(''); + } + if (verdict.regressed_metrics.length > 0) { lines.push('### Hard Regressions'); lines.push(''); for (const item of verdict.regressed_metrics) { + if (item.current === null) { + lines.push( + `- \`${item.key}\`: ${item.baseline} -> missing (DROPPED vs ${label})` + ); + continue; + } + if (item.baseline === null) { + lines.push( + `- \`${item.key}\`: missing -> ${item.current} (UNACKNOWLEDGED BOOTSTRAP vs ${label})` + ); + continue; + } const pct = item.delta_pct_infinite ? '+inf%' : `+${Number(item.delta_pct).toFixed(2)}%`; @@ -738,6 +885,18 @@ export function renderMarkdownSummary(verdict) { lines.push('### Accepted Changes (`perf/accepted.json`)'); lines.push(''); for (const item of verdict.accepted_metrics) { + if (item.action === 'bootstrap') { + lines.push( + `- \`${item.key}\`: missing -> ${item.current} (acknowledged bootstrap: ${item.reason})` + ); + continue; + } + if (item.action === 'drop') { + lines.push( + `- \`${item.key}\`: ${item.baseline} -> missing (acknowledged drop: ${item.reason})` + ); + continue; + } const pct = item.delta_pct_infinite ? '+inf%' : `+${Number(item.delta_pct).toFixed(2)}%`; @@ -752,9 +911,19 @@ export function renderMarkdownSummary(verdict) { lines.push('### Stale Acceptances (`perf/accepted.json`)'); lines.push(''); for (const item of verdict.stale_acceptances) { - lines.push( - `- \`${item.key}\`: baseline ${formatValue(item.baseline, item.unit)} has reached accepted ceiling ${formatValue(item.accepted_value, item.unit)} (safe to prune: ${item.reason})` - ); + if (item.action === 'bootstrap') { + lines.push( + `- \`${item.key}\`: baseline ${formatValue(item.baseline, item.unit)} is now present in ${label} (safe to prune bootstrap entry: ${item.reason})` + ); + } else if (item.action === 'drop') { + lines.push( + `- \`${item.key}\`: metric is no longer present in ${label} (safe to prune drop entry: ${item.reason})` + ); + } else { + lines.push( + `- \`${item.key}\`: baseline ${formatValue(item.baseline, item.unit)} has reached accepted ceiling ${formatValue(item.accepted_value, item.unit)} (safe to prune: ${item.reason})` + ); + } } lines.push(''); } @@ -1030,6 +1199,8 @@ export function parseArgs(argv) { markdownOut: null, jsonOut: null, failOnRegression: false, + requireBaseline: false, + requireN3: false, }; for (let i = 0; i < argv.length; i += 1) { @@ -1094,6 +1265,12 @@ export function parseArgs(argv) { case '--fail-on-regression': opts.failOnRegression = true; break; + case '--require-baseline': + opts.requireBaseline = true; + break; + case '--require-n3': + opts.requireN3 = true; + break; case '--help': case '-h': opts.help = true; @@ -1114,7 +1291,7 @@ export function main(argv = process.argv.slice(2)) { const opts = parseArgs(argv); if (opts.help) { console.log( - 'Usage: compare-n3.mjs --current [--current-created-at ] [--baseline | --fetch-github --repo --branch --workflow ] [--n1 ] [--n2 ] [--accepted ] [--threshold-pct 10] [--ci-wall-min-delta-ms 15000] [--markdown-out ] [--json-out ] [--fail-on-regression]' + 'Usage: compare-n3.mjs --current [--current-created-at ] [--baseline | --fetch-github --repo --branch --workflow ] [--n1 ] [--n2 ] [--accepted ] [--threshold-pct 10] [--ci-wall-min-delta-ms 15000] [--markdown-out ] [--json-out ] [--require-baseline] [--require-n3] [--fail-on-regression]' ); return 0; } @@ -1180,6 +1357,8 @@ export function main(argv = process.argv.slice(2)) { baselineDepth, thresholdPct: opts.thresholdPct, ciWallMinDeltaMs: opts.ciWallMinDeltaMs, + requireBaseline: opts.requireBaseline, + requireN3: opts.requireN3, }); const markdown = renderMarkdownSummary(verdict); @@ -1206,7 +1385,11 @@ export function main(argv = process.argv.slice(2)) { process.stdout.write(markdown); } - if (opts.failOnRegression && verdict.has_hard_regression) { + if ( + (opts.failOnRegression && verdict.has_hard_regression) || + (opts.requireBaseline && baseline === null) || + (opts.requireN3 && (baseline === null || verdict.baseline_depth !== 'N-3')) + ) { return 1; } return 0; diff --git a/blocksuite/native-playground/perf/compare-n3.test.mjs b/packages/frontend/perf/compare-n3.test.mjs similarity index 84% rename from blocksuite/native-playground/perf/compare-n3.test.mjs rename to packages/frontend/perf/compare-n3.test.mjs index c339e4b408..d9130ffeae 100644 --- a/blocksuite/native-playground/perf/compare-n3.test.mjs +++ b/packages/frontend/perf/compare-n3.test.mjs @@ -800,3 +800,165 @@ test('edgeless_1k_pan_zoom_blocks_relayout: 0->0 passes and 0->1 flags determini fs.rmSync(dir, { recursive: true, force: true }); } }); + +test('missing baseline metric in current flags DROPPED hard regression and --require-baseline rejects missing history', () => { + const baseline = makeMetrics('a'.repeat(40)); + const droppedCurrent = makeMetrics('b'.repeat(40)); + delete droppedCurrent.artifacts_bytes.headless_bin; + + const droppedVerdict = comparePerfMetrics({ + current: droppedCurrent, + baseline, + }); + assert.equal(droppedVerdict.has_hard_regression, true); + assert.equal(droppedVerdict.regressed_metrics.length, 1); + assert.equal( + droppedVerdict.regressed_metrics[0].key, + 'artifacts_bytes.headless_bin' + ); + const droppedRow = droppedVerdict.metrics.find( + m => m.key === 'artifacts_bytes.headless_bin' + ); + assert.equal(droppedRow?.status, 'DROPPED'); + assert.equal(droppedRow?.regressed, true); + assert.equal(droppedRow?.current, null); + assert.equal(droppedRow?.baseline, 15_000_000); + assert.match(renderMarkdownSummary(droppedVerdict), /DROPPED/); + + const missingHistoryVerdict = comparePerfMetrics({ + current: makeMetrics('c'.repeat(40)), + baseline: null, + requireBaseline: true, + }); + assert.equal(missingHistoryVerdict.baseline_depth, 'bootstrap'); + assert.equal(missingHistoryVerdict.has_hard_regression, true); + assert.match( + renderMarkdownSummary(missingHistoryVerdict), + /Missing or Incomplete Required Baseline/ + ); + + // Strict --require-n3 rejects N-2 / N-1 fallback and unacknowledged BOOTSTRAP, + // while perf/accepted.json action="bootstrap" and action="drop" allow intentional + // metric additions and removals cleanly until N-3 catches up. + const n2FallbackVerdict = comparePerfMetrics({ + current: makeMetrics('d'.repeat(40)), + baseline: makeMetrics('1'.repeat(40)), + baselineDepth: 'N-2', + requireN3: true, + }); + assert.equal(n2FallbackVerdict.baseline_depth, 'N-2'); + assert.equal(n2FallbackVerdict.has_hard_regression, true); + + const missingInN3Baseline = makeMetrics('1'.repeat(40)); + delete missingInN3Baseline.artifacts_bytes.headless_bin; + const unackBootstrapVerdict = comparePerfMetrics({ + current: makeMetrics('d'.repeat(40)), + baseline: missingInN3Baseline, + baselineDepth: 'N-3', + requireN3: true, + }); + assert.equal(unackBootstrapVerdict.has_hard_regression, true); + assert.equal( + unackBootstrapVerdict.metrics.find( + m => m.key === 'artifacts_bytes.headless_bin' + )?.status, + 'BOOTSTRAP' + ); + + const ackBootstrapVerdict = comparePerfMetrics({ + current: makeMetrics('d'.repeat(40)), + baseline: missingInN3Baseline, + baselineDepth: 'N-3', + requireN3: true, + accepted: [ + { + metric: 'artifacts_bytes.headless_bin', + action: 'bootstrap', + reason: 'Newly introduced binary size metric', + }, + ], + }); + assert.equal(ackBootstrapVerdict.has_hard_regression, false); + assert.equal( + ackBootstrapVerdict.metrics.find( + m => m.key === 'artifacts_bytes.headless_bin' + )?.status, + 'ACCEPTED_BOOTSTRAP' + ); + + const ackDropVerdict = comparePerfMetrics({ + current: droppedCurrent, + baseline, + baselineDepth: 'N-3', + requireN3: true, + accepted: [ + { + metric: 'artifacts_bytes.headless_bin', + action: 'drop', + reason: 'Retired legacy binary target', + }, + ], + }); + assert.equal(ackDropVerdict.has_hard_regression, false); + assert.equal( + ackDropVerdict.metrics.find( + m => m.key === 'artifacts_bytes.headless_bin' + )?.status, + 'ACCEPTED_DROP' + ); + + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'compare-n3-dropped-')); + try { + const basePath = path.join(dir, 'baseline.json'); + const droppedPath = path.join(dir, 'dropped.json'); + const fullPath = path.join(dir, 'full.json'); + const noAcceptedPath = path.join(dir, 'accepted.json'); + fs.writeFileSync(basePath, JSON.stringify(baseline)); + fs.writeFileSync(droppedPath, JSON.stringify(droppedCurrent)); + fs.writeFileSync(fullPath, JSON.stringify(makeMetrics('c'.repeat(40)))); + fs.writeFileSync(noAcceptedPath, '[]'); + + let droppedExit = 0; + try { + execFileSync( + process.execPath, + [ + CLI_PATH, + '--current', + droppedPath, + '--baseline', + basePath, + '--accepted', + noAcceptedPath, + '--fail-on-regression', + ], + { encoding: 'utf8' } + ); + } catch (err) { + droppedExit = err.status ?? 0; + } + assert.equal(droppedExit, 1); + + let noHistoryExit = 0; + try { + execFileSync( + process.execPath, + [ + CLI_PATH, + '--current', + fullPath, + '--accepted', + noAcceptedPath, + '--require-baseline', + '--fail-on-regression', + ], + { encoding: 'utf8' } + ); + } catch (err) { + noHistoryExit = err.status ?? 0; + } + assert.equal(noHistoryExit, 1); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/blocksuite/native-playground/perf/schema.json b/packages/frontend/perf/schema.json similarity index 100% rename from blocksuite/native-playground/perf/schema.json rename to packages/frontend/perf/schema.json diff --git a/packages/frontend/rust-toolchain.toml b/packages/frontend/rust-toolchain.toml new file mode 100644 index 0000000000..bfd155b5c2 --- /dev/null +++ b/packages/frontend/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "1.98.1" +components = ["rustfmt", "clippy"] +targets = ["wasm32-unknown-unknown"] diff --git a/packages/frontend/rustfmt.toml b/packages/frontend/rustfmt.toml new file mode 100644 index 0000000000..f216078d96 --- /dev/null +++ b/packages/frontend/rustfmt.toml @@ -0,0 +1 @@ +edition = "2024" diff --git a/packages/frontend/scripts/check-invariants.sh b/packages/frontend/scripts/check-invariants.sh new file mode 100755 index 0000000000..d959fa93a0 --- /dev/null +++ b/packages/frontend/scripts/check-invariants.sh @@ -0,0 +1,482 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +REPO_ROOT="$(cd "$ROOT/../.." && pwd)" +cd "$ROOT" + +fail() { + echo "ERROR: $*" >&2 + exit 1 +} + +echo "==> Enumerating client Cargo workspace members via cargo metadata" +WORKSPACE_JSON=$(CARGO_ENCODED_RUSTFLAGS="" cargo metadata --manifest-path "$ROOT/Cargo.toml" --locked --no-deps --format-version 1) + +MEMBER_LINES=$( + WORKSPACE_JSON="$WORKSPACE_JSON" REPO_ROOT="$REPO_ROOT" python3 - <<'PY' +import json +import os +from pathlib import Path + +meta = json.loads(os.environ["WORKSPACE_JSON"]) +repo_root = Path(os.environ["REPO_ROOT"]).resolve() +ws_ids = set(meta["workspace_members"]) +members = {} +for pkg in meta["packages"]: + if pkg["id"] in ws_ids: + manifest = Path(pkg["manifest_path"]).resolve() + members[pkg["name"]] = manifest.parent + +if len(members) < 3: + raise SystemExit(f"Expected at least 3 client workspace members, found {len(members)}: {members}") + +expected_core = { + "ui": (repo_root / "packages/ui/ui").resolve(), + "blocksuite-playground-doc": (repo_root / "blocksuite/crates/doc").resolve(), + "playground": (repo_root / "blocksuite/crates/playground").resolve(), +} +for name, expected_dir in expected_core.items(): + actual_dir = members.get(name) + if actual_dir != expected_dir: + raise SystemExit( + f"Expected core client member {name} at {expected_dir}, found {actual_dir}" + ) + +for name in sorted(members): + print(f"{name}\t{members[name]}") +PY +) + +echo "Client workspace members:" +echo "$MEMBER_LINES" + +echo "==> Checking four-domain toolchain, rustfmt, and AGENTS.md alignment and legacy guards" +CLIENT_TREES=( + "$REPO_ROOT/packages/frontend" + "$REPO_ROOT/packages/ui" + "$REPO_ROOT/blocksuite/crates" + "$REPO_ROOT/packages/common/store" +) + +for tree in "${CLIENT_TREES[@]}"; do + [ -d "$tree" ] || fail "Missing client domain directory $tree" + [ -f "$tree/rust-toolchain.toml" ] || fail "Missing $tree/rust-toolchain.toml" + [ -f "$tree/rustfmt.toml" ] || fail "Missing $tree/rustfmt.toml" + [ -f "$tree/AGENTS.md" ] || fail "Missing $tree/AGENTS.md" + [ -f "$tree/CLAUDE.md" ] || fail "Missing $tree/CLAUDE.md" + cmp -s "$ROOT/rust-toolchain.toml" "$tree/rust-toolchain.toml" \ + || fail "$tree/rust-toolchain.toml differs from packages/frontend/rust-toolchain.toml" + cmp -s "$ROOT/rustfmt.toml" "$tree/rustfmt.toml" \ + || fail "$tree/rustfmt.toml differs from packages/frontend/rustfmt.toml" +done + +for legacy_dir in \ + "$REPO_ROOT/packages/frontend/native" \ + "$REPO_ROOT/packages/frontend/mobile-native" \ + "$REPO_ROOT/packages/frontend/apps"; do + [ -f "$legacy_dir/rust-toolchain.toml" ] || fail "Missing legacy guard $legacy_dir/rust-toolchain.toml" + cmp -s "$REPO_ROOT/rust-toolchain.toml" "$legacy_dir/rust-toolchain.toml" \ + || fail "$legacy_dir/rust-toolchain.toml must match root rust-toolchain.toml" +done + +for legacy_fmt_dir in \ + "$REPO_ROOT/packages/frontend/native" \ + "$REPO_ROOT/packages/frontend/mobile-native"; do + [ -f "$legacy_fmt_dir/rustfmt.toml" ] || fail "Missing legacy guard $legacy_fmt_dir/rustfmt.toml" + cmp -s "$REPO_ROOT/rustfmt.toml" "$legacy_fmt_dir/rustfmt.toml" \ + || fail "$legacy_fmt_dir/rustfmt.toml must match root rustfmt.toml" +done + +echo "==> Checking Cargo workspace_root resolution for client and legacy crates" +EXPECTED_CLIENT_ROOT="$(cd "$ROOT" && pwd -P)" +EXPECTED_REPO_ROOT="$(cd "$REPO_ROOT" && pwd -P)" + +while IFS=$'\t' read -r pkg_name member_dir; do + resolved_root=$( + cd "$member_dir" && CARGO_ENCODED_RUSTFLAGS="" cargo metadata --locked --no-deps --format-version 1 \ + | python3 -c "import json, os, sys; print(os.path.realpath(json.load(sys.stdin)['workspace_root']))" + ) + if [ "$resolved_root" != "$EXPECTED_CLIENT_ROOT" ]; then + fail "Client crate $pkg_name ($member_dir) resolved workspace_root=$resolved_root, expected $EXPECTED_CLIENT_ROOT" + fi +done <<< "$MEMBER_LINES" + +for legacy_crate in \ + "$REPO_ROOT" \ + "$REPO_ROOT/packages/frontend/native" \ + "$REPO_ROOT/packages/frontend/mobile-native" \ + "$REPO_ROOT/packages/frontend/native/nbstore" \ + "$REPO_ROOT/packages/frontend/native/schema" \ + "$REPO_ROOT/packages/frontend/native/sqlite_v1"; do + resolved_root=$( + cd "$legacy_crate" && CARGO_ENCODED_RUSTFLAGS="" cargo metadata --locked --no-deps --format-version 1 \ + | python3 -c "import json, os, sys; print(os.path.realpath(json.load(sys.stdin)['workspace_root']))" + ) + if [ "$resolved_root" != "$EXPECTED_REPO_ROOT" ]; then + fail "Legacy crate ($legacy_crate) resolved workspace_root=$resolved_root, expected $EXPECTED_REPO_ROOT" + fi +done + +echo "==> Checking four-domain acyclic dependency rules (default-deny DAG)" +WORKSPACE_JSON="$WORKSPACE_JSON" REPO_ROOT="$REPO_ROOT" python3 - <<'PY' +import json +import os +from pathlib import Path + +UI_ALL = {"packages/ui/tokens", "packages/ui/ui", "packages/ui/kit"} +BS_LOWER = {"blocksuite/crates/doc", "blocksuite/crates/preview", "blocksuite/crates/editor"} + +ALLOWED_DEPS = { + "packages/ui/tokens": set(), + "packages/ui/ui": {"packages/ui/tokens"}, + "packages/ui/kit": {"packages/ui/tokens", "packages/ui/ui"}, + "blocksuite/crates/doc": set(), + "blocksuite/crates/preview": {"packages/ui/tokens", "packages/ui/ui", "blocksuite/crates/doc"}, + "blocksuite/crates/editor": UI_ALL | {"blocksuite/crates/doc", "blocksuite/crates/preview"}, + "blocksuite/crates/playground": UI_ALL | BS_LOWER, + "blocksuite/crates/oracle": UI_ALL | BS_LOWER, + "packages/common/store": {"blocksuite/crates/doc"}, + "packages/frontend/legacy-import": {"blocksuite/crates/doc", "packages/common/store"}, + "packages/frontend/client": UI_ALL | BS_LOWER | { + "packages/common/store", + "packages/frontend/legacy-import", + }, + "packages/frontend/mobile": UI_ALL | BS_LOWER | { + "packages/common/store", + "packages/frontend/legacy-import", + "packages/frontend/client", + }, + "packages/frontend/desktop": UI_ALL | BS_LOWER | { + "packages/common/store", + "packages/frontend/legacy-import", + "packages/frontend/client", + }, +} + +HOST_ALLOWED = UI_ALL | BS_LOWER | { + "packages/common/store", + "packages/frontend/legacy-import", + "packages/frontend/client", + "packages/frontend/mobile", + "packages/frontend/desktop", +} + + +def is_allowed_edge(src_rel: str, dep_rel: str) -> bool: + if src_rel == dep_rel: + return True + if src_rel.startswith("packages/frontend/hosts/"): + parts = src_rel.split("/") + if len(parts) == 4 and parts[3]: + return dep_rel in HOST_ALLOWED + return False + allowed = ALLOWED_DEPS.get(src_rel) + if allowed is None: + return False + return dep_rel in allowed + + +POSITIVE_FIXTURES = [ + ("packages/ui/kit", "packages/ui/ui"), + ("blocksuite/crates/editor", "blocksuite/crates/preview"), + ("blocksuite/crates/playground", "blocksuite/crates/doc"), + ("packages/common/store", "blocksuite/crates/doc"), + ("packages/frontend/mobile", "packages/frontend/client"), + ("packages/frontend/hosts/ios", "packages/frontend/mobile"), +] +NEGATIVE_FIXTURES = [ + ("packages/ui/ui", "packages/ui/kit"), + ("packages/ui/kit", "blocksuite/crates/doc"), + ("blocksuite/crates/doc", "blocksuite/crates/preview"), + ("blocksuite/crates/preview", "blocksuite/crates/editor"), + ("packages/common/store", "blocksuite/crates/editor"), + ("packages/common/store", "packages/ui/ui"), + ("packages/frontend/client", "packages/frontend/mobile"), + ("packages/frontend/mobile", "packages/frontend/hosts/ios"), + ("packages/frontend/mobile", "packages/frontend/desktop"), + ("packages/frontend/hosts/ios", "packages/frontend/hosts/android"), + ("packages/frontend/unregistered", "packages/ui/ui"), +] + +for s_rel, d_rel in POSITIVE_FIXTURES: + if not is_allowed_edge(s_rel, d_rel): + raise SystemExit(f"DAG self-test failed: expected {s_rel} -> {d_rel} to be allowed") +for s_rel, d_rel in NEGATIVE_FIXTURES: + if is_allowed_edge(s_rel, d_rel): + raise SystemExit(f"DAG self-test failed: expected {s_rel} -> {d_rel} to be rejected") + +meta = json.loads(os.environ["WORKSPACE_JSON"]) +repo_root = Path(os.environ["REPO_ROOT"]).resolve() +ws_ids = set(meta["workspace_members"]) + +pkg_rel = {} +for pkg in meta["packages"]: + if pkg["id"] in ws_ids: + rel_dir = Path(pkg["manifest_path"]).resolve().parent.relative_to(repo_root).as_posix() + pkg_rel[pkg["name"]] = rel_dir + +errors = [] +for pkg in meta["packages"]: + if pkg["id"] not in ws_ids: + continue + src_name = pkg["name"] + src_rel = pkg_rel[src_name] + if src_rel not in ALLOWED_DEPS and not ( + src_rel.startswith("packages/frontend/hosts/") and len(src_rel.split("/")) == 4 + ): + errors.append( + f"{src_name} ({src_rel}) is not registered in check-invariants.sh ALLOWED_DEPS" + ) + continue + for dep in pkg.get("dependencies", []): + dep_name = dep["name"] + if dep_name not in pkg_rel: + continue + dep_rel = pkg_rel[dep_name] + if not is_allowed_edge(src_rel, dep_rel): + errors.append(f"{src_name} ({src_rel}) must not depend on {dep_name} ({dep_rel})") + +if errors: + for e in errors: + print(f"ERROR: {e}") + raise SystemExit(1) +print("Four-domain default-deny dependency DAG check (with self-tests) passed.") +PY + +echo "==> Checking active rustup toolchain for legacy (1.97.1) and client (1.98.1) directories" +command -v rustup >/dev/null 2>&1 || fail "rustup is required to verify active toolchains" +ROOT_CHANNEL=$(awk -F'"' '/^channel[[:space:]]*=/{print $2; exit}' "$REPO_ROOT/rust-toolchain.toml") +CLIENT_CHANNEL=$(awk -F'"' '/^channel[[:space:]]*=/{print $2; exit}' "$ROOT/rust-toolchain.toml") +for legacy_tc_dir in \ + "$REPO_ROOT/packages/frontend/native" \ + "$REPO_ROOT/packages/frontend/mobile-native" \ + "$REPO_ROOT/packages/frontend/apps/ios/App" \ + "$REPO_ROOT/packages/frontend/apps/android/App"; do + active_tc=$(cd "$legacy_tc_dir" && env -u RUSTUP_TOOLCHAIN rustup show active-toolchain) \ + || fail "rustup show active-toolchain failed in $legacy_tc_dir" + if [[ "$active_tc" != *"$ROOT_CHANNEL"* ]]; then + fail "Expected active rustup toolchain in $legacy_tc_dir to match $ROOT_CHANNEL, got: $active_tc" + fi +done +for client_tc_dir in "${CLIENT_TREES[@]}"; do + active_tc=$(cd "$client_tc_dir" && env -u RUSTUP_TOOLCHAIN rustup show active-toolchain) \ + || fail "rustup show active-toolchain failed in $client_tc_dir" + if [[ "$active_tc" != *"$CLIENT_CHANNEL"* ]]; then + fail "Expected active rustup toolchain in $client_tc_dir to match $CLIENT_CHANNEL, got: $active_tc" + fi +done + +echo "==> Checking zero internal proc-macro crates" +if grep -rn 'proc-macro\s*=\s*true' "$ROOT/Cargo.toml" 2>/dev/null; then + fail "Internal proc-macro crates are forbidden in the client workspace" +fi +while IFS=$'\t' read -r pkg_name member_dir; do + if grep -rn 'proc-macro\s*=\s*true' "$member_dir/Cargo.toml" 2>/dev/null; then + fail "Internal proc-macro crates are forbidden ($pkg_name)" + fi +done <<< "$MEMBER_LINES" + +UI_DIR="$REPO_ROOT/packages/ui/ui" +DOC_DIR="$REPO_ROOT/blocksuite/crates/doc" +PLAYGROUND_DIR="$REPO_ROOT/blocksuite/crates/playground" + +echo "==> Checking packages/ui/ui domain isolation (no blocksuite/affine words)" +if grep -rniE '\b(blocksuite|affine)\b' "$UI_DIR/src" "$UI_DIR/Cargo.toml" 2>/dev/null; then + fail "packages/ui/ui must not reference BlockSuite or AFFiNE domain terms" +fi + +echo "==> Checking blocksuite/crates/doc GUI isolation and forbid(unsafe_code)" +if grep -rnE '^\s*(ui|wgpu|objc2|web-sys)\b' "$DOC_DIR/Cargo.toml" 2>/dev/null; then + fail "blocksuite/crates/doc must not depend on GUI/platform crates (ui, wgpu, objc2, web-sys)" +fi +if ! grep -q '#!\[forbid(unsafe_code)\]' "$DOC_DIR/src/lib.rs"; then + fail "blocksuite/crates/doc/src/lib.rs must declare #![forbid(unsafe_code)]" +fi + +echo "==> Checking no wall-clock calls outside packages/ui/ui/src/platform" +WALL_CLOCK_HITS="" +while IFS=$'\t' read -r _pkg_name member_dir; do + if [ -d "$member_dir/src" ]; then + hits=$( + grep -rnE '(Instant::now|SystemTime::now|Zoned::now|Timestamp::now)\s*\(' "$member_dir/src" \ + --include='*.rs' \ + | grep -v "^$UI_DIR/src/platform/" \ + || true + ) + if [ -n "$hits" ]; then + WALL_CLOCK_HITS="${WALL_CLOCK_HITS}${hits}"$'\n' + fi + fi +done <<< "$MEMBER_LINES" +if [ -n "$WALL_CLOCK_HITS" ]; then + echo "$WALL_CLOCK_HITS" >&2 + fail "Instant::now() / SystemTime::now() / Zoned::now() / Timestamp::now() is forbidden outside packages/ui/ui/src/platform/" +fi + +echo "==> Checking zero tester branches inside shipping playground view modules" +if grep -rn 'is_headless' "$PLAYGROUND_DIR/src" 2>/dev/null; then + fail "is_headless branches are forbidden in blocksuite/crates/playground/src" +fi +TESTER_CFG_HITS=$( + grep -rnE '#\[cfg\((any\(test|feature\s*=\s*"harness")' "$PLAYGROUND_DIR/src" 2>/dev/null \ + | grep -Ev "^$PLAYGROUND_DIR/src/(bin/|rich_text/mod\.rs:)" \ + || true +) +if [ -n "$TESTER_CFG_HITS" ]; then + echo "$TESTER_CFG_HITS" >&2 + fail "Inline harness/test cfg branches are forbidden in shipping blocksuite/crates/playground/src modules" +fi + +echo "==> Checking Rust module structure, visibility, orphaned files, and per-file LOC" +MEMBER_LINES="$MEMBER_LINES" python3 - <<'PY' +import os +import re +import sys +from pathlib import Path + +errors = [] +roots = [] +for line in os.environ["MEMBER_LINES"].splitlines(): + if not line.strip(): + continue + name, dir_path = line.split("\t", 1) + if name == "ui": + continue + src_dir = Path(dir_path) / "src" + if src_dir.is_dir(): + roots.append(src_dir) + +if len(roots) < 2: + print(f"ERROR: Expected at least 2 non-vendored client crate src roots, found {roots}", file=sys.stderr) + sys.exit(1) + +def strip_cfg_test_mods(src: str) -> str: + """Remove `#[cfg(test)] mod { ... }` blocks while preserving line numbers.""" + lines = src.splitlines() + out = [] + i = 0 + n = len(lines) + while i < n: + s = lines[i].strip() + if s == "#[cfg(test)]" and i + 1 < n and re.match(r"^(pub(\([^)]*\))?\s+)?mod\s+\w+\s*\{", lines[i + 1].strip()): + depth = 0 + started = False + out.append("") + i += 1 + while i < n: + line = lines[i] + if "{" in line: + started = True + depth += line.count("{") - line.count("}") + out.append("") + i += 1 + if started and depth <= 0: + break + continue + out.append(lines[i]) + i += 1 + return "\n".join(out) + +for src_root in roots: + rs_files = sorted(src_root.rglob("*.rs")) + declared_modules = set() + for entry in ("lib.rs", "main.rs"): + if (src_root / entry).exists(): + declared_modules.add((src_root / entry).resolve()) + for bin_file in (src_root / "bin").glob("*.rs") if (src_root / "bin").exists() else []: + declared_modules.add(bin_file.resolve()) + for bin_main in (src_root / "bin").glob("*/main.rs") if (src_root / "bin").exists() else []: + declared_modules.add(bin_main.resolve()) + + mod_decl_re = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*;") + for p in rs_files: + text = p.read_text(encoding="utf-8") + parent = p.parent + for line in text.splitlines(): + m = mod_decl_re.match(line) + if m: + mod_name = m.group(1) + base_dir = parent if p.name in ("lib.rs", "main.rs", "mod.rs") else parent / p.stem + cand_file = base_dir / f"{mod_name}.rs" + cand_mod = base_dir / mod_name / "mod.rs" + if cand_file.exists(): + declared_modules.add(cand_file.resolve()) + if cand_mod.exists(): + declared_modules.add(cand_mod.resolve()) + + if p.name not in ("lib.rs", "main.rs", "mod.rs") and (parent / p.stem).is_dir(): + errors.append(f"{p}: coexists beside directory {parent / p.stem}/; move into {parent / p.stem}/mod.rs") + + non_test = strip_cfg_test_mods(text) + non_test_lines = non_test.splitlines() + + for lineno, line in enumerate(non_test_lines, 1): + if "super::super::" in line: + errors.append(f"{p}:{lineno}: forbidden `super::super::` outside `mod tests`") + + rel = p.relative_to(src_root) + if len(rel.parts) >= 2 and p.name != "mod.rs" and rel.parts[0] != "bin": + parent_mod = rel.parts[0] + pat = f"crate::{parent_mod}::" + for lineno, line in enumerate(non_test_lines, 1): + if pat in line: + errors.append(f"{p}:{lineno}: use `super::` instead of `{pat}` inside submodule") + + actual_non_test = len([1 for orig, stripped in zip(text.splitlines(), non_test_lines) if orig == stripped]) + if actual_non_test > 800: + errors.append(f"{p}: {actual_non_test} non-test lines exceeds ceiling of 800") + + for p in rs_files: + if p.resolve() not in declared_modules: + errors.append(f"{p}: orphaned .rs file not declared by any `mod ;`") + +if errors: + for e in errors: + print(f"ERROR: {e}", file=sys.stderr) + sys.exit(1) +print("Rust module structure & LOC checks passed.") +PY + +echo "==> Checking packages/ui/ui LOC ceiling" +UI_LOC_CEILING=95000 +UI_LOC=$(find "$UI_DIR/src" -name '*.rs' -print0 | xargs -0 cat | wc -l | tr -d ' ') +echo "packages/ui/ui/src total LOC: $UI_LOC (ceiling: $UI_LOC_CEILING)" +if [ "$UI_LOC" -gt "$UI_LOC_CEILING" ]; then + fail "packages/ui/ui/src LOC ($UI_LOC) exceeds ceiling ($UI_LOC_CEILING)" +fi + +echo "==> Checking workflow YAML validity" +if [ -f "$REPO_ROOT/.github/workflows/native-playground.yml" ] && [ -f "$REPO_ROOT/.github/workflows/build-test.yml" ]; then + if python3 -c "import yaml" 2>/dev/null; then + python3 -c " +import yaml, sys +for p in sys.argv[1:]: + with open(p) as f: + yaml.safe_load(f) + print('YAML OK:', p) +" "$REPO_ROOT/.github/workflows/build-test.yml" "$REPO_ROOT/.github/workflows/native-playground.yml" + elif command -v ruby >/dev/null 2>&1; then + ruby -ryaml -e 'ARGV.each { |p| YAML.load_file(p); puts "YAML OK: #{p}" }' \ + "$REPO_ROOT/.github/workflows/build-test.yml" "$REPO_ROOT/.github/workflows/native-playground.yml" + else + fail "Neither python3-yaml nor ruby is available to validate workflow YAML files" + fi +fi + +echo "==> Checking CARGO_ENCODED_RUSTFLAGS isolation (no leaked root NAPI linker flags)" +if ! LINK_LOG=$(CARGO_ENCODED_RUSTFLAGS="" cargo rustc -p playground --bin bs-harness --features harness -- -C metadata="linkcheck-$$" --print link-args 2>&1); then + echo "$LINK_LOG" >&2 + fail "cargo rustc link-args check failed" +fi +if ! echo "$LINK_LOG" | grep -qE '(cc|clang|gcc|ld|lld|"[^"]*bs_harness|bs_harness)'; then + echo "$LINK_LOG" >&2 + fail "cargo rustc did not emit a linker invocation (cache bypass failed)" +fi +if echo "$LINK_LOG" | grep -E '(-all_load|-undefined[ ,]+dynamic_lookup|-z[ ,]+nodelete)' >/dev/null 2>&1; then + echo "$LINK_LOG" >&2 + fail "Detected leaked root NAPI linker flags in rustc invocation" +fi + +echo "All static invariants passed." diff --git a/blocksuite/native-playground/scripts/web-smoke.mjs b/packages/frontend/scripts/web-smoke.mjs similarity index 98% rename from blocksuite/native-playground/scripts/web-smoke.mjs rename to packages/frontend/scripts/web-smoke.mjs index e1f1123197..268bab48bf 100755 --- a/blocksuite/native-playground/scripts/web-smoke.mjs +++ b/packages/frontend/scripts/web-smoke.mjs @@ -16,7 +16,7 @@ * over the network is captured after it rendered. */ -import { measureSurfaceBaselines } from './surface-baselines.mjs'; +import { measureSurfaceBaselines } from '../../../blocksuite/crates/oracle/surface-baselines.mjs'; import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import fs from 'node:fs'; @@ -27,7 +27,9 @@ import zlib from 'node:zlib'; const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url)); const ROOT = path.resolve(SCRIPT_DIR, '..'); -const WEB_DIR = path.join(ROOT, 'web'); +const REPO_ROOT = path.resolve(ROOT, '../..'); +const WEB_DIR = path.join(REPO_ROOT, 'blocksuite/crates/playground/web'); +const ORACLE_DIR = path.join(REPO_ROOT, 'blocksuite/crates/oracle'); function parseArgs(argv) { const args = { @@ -605,7 +607,7 @@ async function main() { await checkComposition(cdp); await checkLinkField(cdp); const baselines = await measureSurfaceBaselines(inputProbe(cdp).evaluate); - assert.deepEqual(baselines, JSON.parse(fs.readFileSync(path.join(ROOT, 'tokens/surface-baselines.json'), 'utf8'))); + assert.deepEqual(baselines, JSON.parse(fs.readFileSync(path.join(ORACLE_DIR, 'surface-baselines.json'), 'utf8'))); console.log('Chromium DOM and Canvas surface label baselines passed'); } diff --git a/packages/ui/AGENTS.md b/packages/ui/AGENTS.md new file mode 100644 index 0000000000..c34bf3638d --- /dev/null +++ b/packages/ui/AGENTS.md @@ -0,0 +1,32 @@ +# Working in `packages/ui/` (for agents) + +`packages/ui/` holds the domain-neutral GPU UI library (`packages/ui/ui`) and generated design tokens (`packages/ui/tokens`). +This directory belongs to the client Cargo workspace rooted at `packages/frontend/Cargo.toml`. + +## Active Invariants (enforced now) + +### Workspace boundaries +- `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(...)`). + +### Platform matrix +`packages/ui/ui` compiles cleanly across three targets from one crate: +- **macOS (`target_os = "macos"`)**: AppKit + Metal + CoreText, including windowless `MetalHeadlessRenderer` readback, full mip-0 `MetalAtlas` zero-init, and offscreen `MacWindow` frame/scale fallbacks. +- **Linux Headless (`target_os = "linux"`)**: `wgpu` + `cosmic-text` via `WgpuHeadlessRenderer` on Mesa `lavapipe` for deterministic software rasterization in CI. +- **Web (`target_family = "wasm"`)**: Single-threaded `wasm32-unknown-unknown` + WebGPU/WebGL2 + `CanvasFontFallback` + block-scoped `ImeMirror` (no `wasm_thread`, no `http_client`), verified in headless Chromium via `packages/frontend/scripts/web-smoke.mjs` (`--query` loads the page with a query string such as a live room, `--min-title-ink` waits for that much page ink before capturing; without a query it also drives composition across blocks and composition and paste in the toolbar's link field through the hidden textarea). + +### Determinism, single clock, and zero tester branches +- **Single UI execution path**: Headless shell rendering (`bs-harness render`), desktop (`main.rs`), and Web (`wasm_main`) all instantiate and render the exact same shipping `PlaygroundView` through `Application::with_platform(...)` and `Window::draw()`. +- **No wall clock outside `packages/ui/ui/src/platform/`**: `Instant::now()` and `SystemTime::now()` are forbidden anywhere outside `packages/ui/ui/src/platform/` (`packages/frontend/scripts/check-invariants.sh`). Host thread-park deadlines read monotonic time in `packages/ui/ui/src/platform/clock.rs`; animations and transitions read the scheduler clock (`cx.background_executor().now()`, backed by `TestScheduler` in headless/test runs and the platform scheduler in desktop/web). +- **Motion is pure data**: Transitions are declared once as `(from, to, curve, start_ms, duration_ms)` and evaluated as a pure function of scheduler time. Never write frame-by-frame recurrence loops or `sleep` waits. +- **Zero tester branches**: Application and layout logic never inspect `is_headless` or inline `#[cfg(any(test, feature = "harness"))]` to alter behavior (`packages/frontend/scripts/check-invariants.sh`). +- **Four-rate replay invariance**: Stepped `PlaygroundView` transitions (the mode switch, the slash menu and the formatting toolbar opening and closing) must progress monotonically with in-flight frames and produce byte-identical terminal `FrameSnapshot` JSON at `60`, `120`, `24`, and `7` fps (`bs-harness fps-check`). +- **Callsite tracing**: Under the `harness` feature, `InteractiveElement::snapshot(...)` records post-layout bounds, `content_mask`, interactivity, focus, and `#[track_caller]` `file:line` origins into `Window::frame_snapshot()` for `sources_at(x, y)` and `bs-harness audit`. The snapshot schema and the audit rules are the repository's `tools/frame-audit` (a `serde`-only path dependency of `packages/ui/ui`, re-exported from `ui::harness`). Change them there and keep both workspaces' tests green. Non-harness release builds compile to no-op stubs. `packages/ui/ui/src/harness.rs` (`normalize_callsite_path`) maps `packages/ui/ui/` to `crates/ui/` and out-of-tree `crates/` paths to `crates/` so `FrameSnapshot` JSON stays byte-identical across hosts and checkout roots. +- **Locked builds & rustflags isolation**: `Cargo.lock` is committed and CI runs with `--locked` and `CARGO_ENCODED_RUSTFLAGS=""` (`packages/frontend/scripts/check-invariants.sh` verifies fresh `cargo rustc --print link-args` contains zero leaked root NAPI flags). + +### Edgeless rendering and GPU transforms +- **End-to-end GPU transforms and local clip masks**: `Window::with_paint_transformation` composes 2D affine transforms (`TransformationMatrix`) on a stack and `Window::with_local_paint_mask` intersects pre-transform local clip rects (`ContentMask`). All GPU primitives (`Quad`, `Shadow`, `Underline`, `MonochromeSprite`, `SubpixelSprite`, `PolychromeSprite`, and `PathRasterizationVertex`) are 16-byte aligned (`size_of % 16 == 0`, verified by compile-time assertions) for WebGL2 `RGBA32U` instance-texture decoding. Both Metal (`shaders.metal`) and wgpu/WebGL2 (`shaders.wgsl`, `shaders_webgl.wgsl`, `shaders_subpixel.wgsl`) transform vertices on the GPU, reserve bit 31 of `quad_id` (`0x80000000u`) in `vs_quad` / `quad_vertex` for the solid-quad fast path, evaluate SDFs in local space scaled by `transform_scale` for 1-device-pixel anti-aliasing across zooms and rotations, and clip against both screen-space `content_mask` and pre-transform `local_content_mask`. +- **Quarter-octave glyph zoom bucketing**: Under non-unit paint scales, `Window::paint_glyph` and `Window::paint_glyph_in_run` quantize rasterization scale to quarter-octave buckets (`2^(round(4*log2(s))/4)` clamped to `[0.25, 8.0]`), rasterizing atlas tiles at `font_size * bucket` while scaling local quad bounds by `1 / bucket` so cached `1.0x` `RichParagraph` / `BlockFlow` layouts render crisply at `0.1x..6.0x` without re-shaping or relayouting during pan/zoom. +- **Procedural dot-grid (`BackgroundTag::DotGrid = 4`)**: Renders the Edgeless background grid in a single fullscreen `Quad` draw call with 1-device-pixel anti-aliased dots centered in each tile with screen offset `(0.5 * gap - pan * zoom).rem_euclid(gap)` per axis and spacing matching BlockSuite's `getBgGridGap(zoom)`. + +### Design tokens and style oracle +- **`packages/ui/tokens/` (`extract-tokens.mjs`, `tokens.rs`, `icons.rs`, `fonts.lock`) & `blocksuite/crates/oracle/` (`extract-style-oracle.spec.ts`, `style-oracle.json`)**: `extract-tokens.mjs` deterministically generates Rust-`Ord`-sorted `tokens.rs`, `icons.rs` (preserving inherited `` and stroke attributes), and `fonts.lock` (SHA-256 font asset manifest + `CommunityCanvasTextFonts` descriptors), with `--check` and `rustc --edition 2024 --test` enforced on every push in CI. `style-oracle.json` is regenerated via Vitest Browser (`extract-style-oracle.spec.ts`, `isolate: false` reusable iframe) whenever BlockSuite styles or themes change (until its browser CI job lands). diff --git a/packages/ui/CLAUDE.md b/packages/ui/CLAUDE.md new file mode 100644 index 0000000000..43c994c2d3 --- /dev/null +++ b/packages/ui/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/packages/ui/rust-toolchain.toml b/packages/ui/rust-toolchain.toml new file mode 100644 index 0000000000..bfd155b5c2 --- /dev/null +++ b/packages/ui/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "1.98.1" +components = ["rustfmt", "clippy"] +targets = ["wasm32-unknown-unknown"] diff --git a/packages/ui/rustfmt.toml b/packages/ui/rustfmt.toml new file mode 100644 index 0000000000..f216078d96 --- /dev/null +++ b/packages/ui/rustfmt.toml @@ -0,0 +1 @@ +edition = "2024" diff --git a/blocksuite/native-playground/tokens/extract-tokens.mjs b/packages/ui/tokens/extract-tokens.mjs similarity index 98% rename from blocksuite/native-playground/tokens/extract-tokens.mjs rename to packages/ui/tokens/extract-tokens.mjs index 07c6c4c0d1..2cae272981 100644 --- a/blocksuite/native-playground/tokens/extract-tokens.mjs +++ b/packages/ui/tokens/extract-tokens.mjs @@ -433,7 +433,7 @@ ${renderColorSlice(data.connectorPalette)} ? basePx + Number(lineHeightCalcMatch[1]) : parsePxStrict(lineHeightRaw, '--affine-line-height'); - return `// @generated by blocksuite/native-playground/tokens/extract-tokens.mjs + return `// @generated by packages/ui/tokens/extract-tokens.mjs // Source: @toeverything/theme@${themePkg.version} (dist/style.css) // Do not edit manually; regenerate with extract-tokens.mjs. @@ -768,7 +768,7 @@ ${pathLines} .map(item => ` ${item.rustConstName},`) .join('\n'); - return `// @generated by blocksuite/native-playground/tokens/extract-tokens.mjs + return `// @generated by packages/ui/tokens/extract-tokens.mjs // Source: @blocksuite/icons@${iconsPkg.version} (dist/lit.mjs) // Do not edit manually; regenerate with extract-tokens.mjs. @@ -948,6 +948,18 @@ function generateFontsLock(nodeModulesDir) { const repoRoot = path.resolve(__dirname, '../../..'); const communityCanvasTextFonts = parseCommunityCanvasTextFonts(repoRoot); + if (bundledFiles.length === 0) { + throw new Error('Generated fonts.lock bundled_files must not be empty'); + } + if (fontFaces.length === 0) { + throw new Error('Generated fonts.lock font_faces must not be empty'); + } + if (communityCanvasTextFonts.length === 0) { + throw new Error( + `Generated fonts.lock community_canvas_text_fonts must not be empty (repoRoot=${repoRoot})` + ); + } + const manifest = { schema_version: 1, source_package: `@toeverything/theme@${themePkg.version}`, diff --git a/blocksuite/native-playground/tokens/fonts.lock b/packages/ui/tokens/fonts.lock similarity index 100% rename from blocksuite/native-playground/tokens/fonts.lock rename to packages/ui/tokens/fonts.lock diff --git a/blocksuite/native-playground/tokens/icons.rs b/packages/ui/tokens/icons.rs similarity index 99% rename from blocksuite/native-playground/tokens/icons.rs rename to packages/ui/tokens/icons.rs index 0d9cfea630..de05122d38 100644 --- a/blocksuite/native-playground/tokens/icons.rs +++ b/packages/ui/tokens/icons.rs @@ -1,4 +1,4 @@ -// @generated by blocksuite/native-playground/tokens/extract-tokens.mjs +// @generated by packages/ui/tokens/extract-tokens.mjs // Source: @blocksuite/icons@2.2.17 (dist/lit.mjs) // Do not edit manually; regenerate with extract-tokens.mjs. diff --git a/blocksuite/native-playground/tokens/tokens.rs b/packages/ui/tokens/tokens.rs similarity index 99% rename from blocksuite/native-playground/tokens/tokens.rs rename to packages/ui/tokens/tokens.rs index e719f95527..fb308da93e 100644 --- a/blocksuite/native-playground/tokens/tokens.rs +++ b/packages/ui/tokens/tokens.rs @@ -1,4 +1,4 @@ -// @generated by blocksuite/native-playground/tokens/extract-tokens.mjs +// @generated by packages/ui/tokens/extract-tokens.mjs // Source: @toeverything/theme@1.1.23 (dist/style.css) // Do not edit manually; regenerate with extract-tokens.mjs. diff --git a/blocksuite/native-playground/crates/ui/Cargo.toml b/packages/ui/ui/Cargo.toml similarity index 99% rename from blocksuite/native-playground/crates/ui/Cargo.toml rename to packages/ui/ui/Cargo.toml index c4087f3662..87d74a712d 100644 --- a/blocksuite/native-playground/crates/ui/Cargo.toml +++ b/packages/ui/ui/Cargo.toml @@ -1,5 +1,6 @@ [package] name = "ui" +workspace = "../../frontend" version.workspace = true edition.workspace = true publish.workspace = true diff --git a/blocksuite/native-playground/VENDOR.md b/packages/ui/ui/VENDOR.md similarity index 100% rename from blocksuite/native-playground/VENDOR.md rename to packages/ui/ui/VENDOR.md diff --git a/blocksuite/native-playground/crates/ui/build.rs b/packages/ui/ui/build.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/build.rs rename to packages/ui/ui/build.rs diff --git a/blocksuite/native-playground/crates/ui/src/action.rs b/packages/ui/ui/src/action.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/action.rs rename to packages/ui/ui/src/action.rs diff --git a/blocksuite/native-playground/crates/ui/src/app.rs b/packages/ui/ui/src/app.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/app.rs rename to packages/ui/ui/src/app.rs diff --git a/blocksuite/native-playground/crates/ui/src/app/async_context.rs b/packages/ui/ui/src/app/async_context.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/app/async_context.rs rename to packages/ui/ui/src/app/async_context.rs diff --git a/blocksuite/native-playground/crates/ui/src/app/context.rs b/packages/ui/ui/src/app/context.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/app/context.rs rename to packages/ui/ui/src/app/context.rs diff --git a/blocksuite/native-playground/crates/ui/src/app/entity_map.rs b/packages/ui/ui/src/app/entity_map.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/app/entity_map.rs rename to packages/ui/ui/src/app/entity_map.rs diff --git a/blocksuite/native-playground/crates/ui/src/arena.rs b/packages/ui/ui/src/arena.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/arena.rs rename to packages/ui/ui/src/arena.rs diff --git a/blocksuite/native-playground/crates/ui/src/asset_cache.rs b/packages/ui/ui/src/asset_cache.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/asset_cache.rs rename to packages/ui/ui/src/asset_cache.rs diff --git a/blocksuite/native-playground/crates/ui/src/assets.rs b/packages/ui/ui/src/assets.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/assets.rs rename to packages/ui/ui/src/assets.rs diff --git a/blocksuite/native-playground/crates/ui/src/collections/mod.rs b/packages/ui/ui/src/collections/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/collections/mod.rs rename to packages/ui/ui/src/collections/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/collections/vecmap.rs b/packages/ui/ui/src/collections/vecmap.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/collections/vecmap.rs rename to packages/ui/ui/src/collections/vecmap.rs diff --git a/blocksuite/native-playground/crates/ui/src/color.rs b/packages/ui/ui/src/color.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/color.rs rename to packages/ui/ui/src/color.rs diff --git a/blocksuite/native-playground/crates/ui/src/element.rs b/packages/ui/ui/src/element.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/element.rs rename to packages/ui/ui/src/element.rs diff --git a/blocksuite/native-playground/crates/ui/src/elements/anchored.rs b/packages/ui/ui/src/elements/anchored.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/elements/anchored.rs rename to packages/ui/ui/src/elements/anchored.rs diff --git a/blocksuite/native-playground/crates/ui/src/elements/canvas.rs b/packages/ui/ui/src/elements/canvas.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/elements/canvas.rs rename to packages/ui/ui/src/elements/canvas.rs diff --git a/blocksuite/native-playground/crates/ui/src/elements/deferred.rs b/packages/ui/ui/src/elements/deferred.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/elements/deferred.rs rename to packages/ui/ui/src/elements/deferred.rs diff --git a/blocksuite/native-playground/crates/ui/src/elements/div.rs b/packages/ui/ui/src/elements/div.rs similarity index 99% rename from blocksuite/native-playground/crates/ui/src/elements/div.rs rename to packages/ui/ui/src/elements/div.rs index 20f7ee75b9..59e2944071 100644 --- a/blocksuite/native-playground/crates/ui/src/elements/div.rs +++ b/packages/ui/ui/src/elements/div.rs @@ -2139,6 +2139,11 @@ impl Interactivity { .with_focused(spec.focused) .with_corner_radius(corner_radius) .with_padding(padding); + snap.callsite = format!( + "{}:{}", + crate::harness::normalize_callsite_path(spec.callsite.file()), + spec.callsite.line() + ); if let Some(parent_id) = &spec.parent_id { snap = snap.with_parent(parent_id.as_ref()); } diff --git a/blocksuite/native-playground/crates/ui/src/elements/image_cache.rs b/packages/ui/ui/src/elements/image_cache.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/elements/image_cache.rs rename to packages/ui/ui/src/elements/image_cache.rs diff --git a/blocksuite/native-playground/crates/ui/src/elements/img.rs b/packages/ui/ui/src/elements/img.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/elements/img.rs rename to packages/ui/ui/src/elements/img.rs diff --git a/blocksuite/native-playground/crates/ui/src/elements/mod.rs b/packages/ui/ui/src/elements/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/elements/mod.rs rename to packages/ui/ui/src/elements/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/elements/svg.rs b/packages/ui/ui/src/elements/svg.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/elements/svg.rs rename to packages/ui/ui/src/elements/svg.rs diff --git a/blocksuite/native-playground/crates/ui/src/elements/text.rs b/packages/ui/ui/src/elements/text.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/elements/text.rs rename to packages/ui/ui/src/elements/text.rs diff --git a/blocksuite/native-playground/crates/ui/src/executor.rs b/packages/ui/ui/src/executor.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/executor.rs rename to packages/ui/ui/src/executor.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/app_borrow.rs b/packages/ui/ui/src/fast/app_borrow.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/app_borrow.rs rename to packages/ui/ui/src/fast/app_borrow.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/bounds_tree.rs b/packages/ui/ui/src/fast/bounds_tree.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/bounds_tree.rs rename to packages/ui/ui/src/fast/bounds_tree.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/clock.rs b/packages/ui/ui/src/fast/clock.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/clock.rs rename to packages/ui/ui/src/fast/clock.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/dependencies.rs b/packages/ui/ui/src/fast/dependencies.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/dependencies.rs rename to packages/ui/ui/src/fast/dependencies.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/dispatch.rs b/packages/ui/ui/src/fast/dispatch.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/dispatch.rs rename to packages/ui/ui/src/fast/dispatch.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/em_metrics.rs b/packages/ui/ui/src/fast/em_metrics.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/em_metrics.rs rename to packages/ui/ui/src/fast/em_metrics.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/global_id.rs b/packages/ui/ui/src/fast/global_id.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/global_id.rs rename to packages/ui/ui/src/fast/global_id.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/glyphs.rs b/packages/ui/ui/src/fast/glyphs.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/glyphs.rs rename to packages/ui/ui/src/fast/glyphs.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/interactive_text.rs b/packages/ui/ui/src/fast/interactive_text.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/interactive_text.rs rename to packages/ui/ui/src/fast/interactive_text.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/interactivity.rs b/packages/ui/ui/src/fast/interactivity.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/interactivity.rs rename to packages/ui/ui/src/fast/interactivity.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/layout.rs b/packages/ui/ui/src/fast/layout.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/layout.rs rename to packages/ui/ui/src/fast/layout.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/layout_bounds.rs b/packages/ui/ui/src/fast/layout_bounds.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/layout_bounds.rs rename to packages/ui/ui/src/fast/layout_bounds.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/layout_key.rs b/packages/ui/ui/src/fast/layout_key.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/layout_key.rs rename to packages/ui/ui/src/fast/layout_key.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/line_break.rs b/packages/ui/ui/src/fast/line_break.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/line_break.rs rename to packages/ui/ui/src/fast/line_break.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/misc/mod.rs b/packages/ui/ui/src/fast/misc/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/misc/mod.rs rename to packages/ui/ui/src/fast/misc/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/misc/reentrant_window.rs b/packages/ui/ui/src/fast/misc/reentrant_window.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/misc/reentrant_window.rs rename to packages/ui/ui/src/fast/misc/reentrant_window.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/mod.rs b/packages/ui/ui/src/fast/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/mod.rs rename to packages/ui/ui/src/fast/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/number_shaping.rs b/packages/ui/ui/src/fast/number_shaping.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/number_shaping.rs rename to packages/ui/ui/src/fast/number_shaping.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/observers.rs b/packages/ui/ui/src/fast/observers.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/observers.rs rename to packages/ui/ui/src/fast/observers.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/path_cache.rs b/packages/ui/ui/src/fast/path_cache.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/path_cache.rs rename to packages/ui/ui/src/fast/path_cache.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/pointer.rs b/packages/ui/ui/src/fast/pointer.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/pointer.rs rename to packages/ui/ui/src/fast/pointer.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/retained.rs b/packages/ui/ui/src/fast/retained.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/retained.rs rename to packages/ui/ui/src/fast/retained.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/rounded_clip.rs b/packages/ui/ui/src/fast/rounded_clip.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/rounded_clip.rs rename to packages/ui/ui/src/fast/rounded_clip.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/rounded_clip_scene.rs b/packages/ui/ui/src/fast/rounded_clip_scene.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/rounded_clip_scene.rs rename to packages/ui/ui/src/fast/rounded_clip_scene.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/scene.rs b/packages/ui/ui/src/fast/scene.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/scene.rs rename to packages/ui/ui/src/fast/scene.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/splice.rs b/packages/ui/ui/src/fast/splice.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/splice.rs rename to packages/ui/ui/src/fast/splice.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/stats.rs b/packages/ui/ui/src/fast/stats.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/stats.rs rename to packages/ui/ui/src/fast/stats.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/tab_stop.rs b/packages/ui/ui/src/fast/tab_stop.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/tab_stop.rs rename to packages/ui/ui/src/fast/tab_stop.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/text.rs b/packages/ui/ui/src/fast/text.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/text.rs rename to packages/ui/ui/src/fast/text.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/text_style.rs b/packages/ui/ui/src/fast/text_style.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/text_style.rs rename to packages/ui/ui/src/fast/text_style.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/tracked_entities.rs b/packages/ui/ui/src/fast/tracked_entities.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/tracked_entities.rs rename to packages/ui/ui/src/fast/tracked_entities.rs diff --git a/blocksuite/native-playground/crates/ui/src/fast/truncation.rs b/packages/ui/ui/src/fast/truncation.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/fast/truncation.rs rename to packages/ui/ui/src/fast/truncation.rs diff --git a/blocksuite/native-playground/crates/ui/src/geometry.rs b/packages/ui/ui/src/geometry.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/geometry.rs rename to packages/ui/ui/src/geometry.rs diff --git a/blocksuite/native-playground/crates/ui/src/global.rs b/packages/ui/ui/src/global.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/global.rs rename to packages/ui/ui/src/global.rs diff --git a/blocksuite/native-playground/crates/ui/src/gpui_util/arc_cow.rs b/packages/ui/ui/src/gpui_util/arc_cow.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/gpui_util/arc_cow.rs rename to packages/ui/ui/src/gpui_util/arc_cow.rs diff --git a/blocksuite/native-playground/crates/ui/src/gpui_util/mod.rs b/packages/ui/ui/src/gpui_util/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/gpui_util/mod.rs rename to packages/ui/ui/src/gpui_util/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/harness.rs b/packages/ui/ui/src/harness.rs similarity index 68% rename from blocksuite/native-playground/crates/ui/src/harness.rs rename to packages/ui/ui/src/harness.rs index 585827fb2c..ddea06b7a8 100644 --- a/blocksuite/native-playground/crates/ui/src/harness.rs +++ b/packages/ui/ui/src/harness.rs @@ -27,6 +27,41 @@ mod active { pub(crate) focused: bool, pub(crate) text: Option, } + + /// Normalizes a `#[track_caller]` file path into a workspace-relative crate + /// path so snapshots stay byte-identical across OSes and checkout roots. + pub(crate) fn normalize_callsite_path(raw: &str) -> String { + let normalized = raw.replace('\\', "/"); + if let Some((_, rest)) = find_rightmost_marker(&normalized, "packages/ui/ui/") { + return format!("crates/ui/{rest}"); + } + if let Some((_, rest)) = find_rightmost_marker(&normalized, "packages/ui/kit/") { + return format!("crates/kit/{rest}"); + } + match ( + find_rightmost_marker(&normalized, "packages/"), + find_rightmost_marker(&normalized, "crates/"), + ) { + (Some((pkg_idx, pkg_rest)), Some((crate_idx, crate_rest))) => { + if crate_idx > pkg_idx { + format!("crates/{crate_rest}") + } else { + format!("packages/{pkg_rest}") + } + } + (Some((_, pkg_rest)), None) => format!("packages/{pkg_rest}"), + (None, Some((_, crate_rest))) => format!("crates/{crate_rest}"), + (None, None) => normalized, + } + } + + fn find_rightmost_marker<'a>(path: &'a str, marker: &str) -> Option<(usize, &'a str)> { + let needle = format!("/{marker}"); + if let Some(idx) = path.rfind(&needle) { + return Some((idx + 1, &path[idx + needle.len()..])); + } + path.strip_prefix(marker).map(|rest| (0, rest)) + } } #[cfg(not(any(test, feature = "harness")))] @@ -115,9 +150,9 @@ mod active { } } -#[cfg(any(test, feature = "harness"))] -pub(crate) use active::SnapshotSpec; pub use active::{DebugElementSnapshot, FrameSnapshot, audit_frame_snapshot}; +#[cfg(any(test, feature = "harness"))] +pub(crate) use active::{SnapshotSpec, normalize_callsite_path}; #[cfg(test)] mod tests { @@ -184,4 +219,37 @@ mod tests { assert!(rules.contains(&"off-viewport-focus"), "{rules:?}"); assert!(rules.contains(&"pixel-alignment"), "{rules:?}"); } + + #[test] + fn normalize_callsite_path_strips_host_prefixes() { + let cases = [ + ( + "/home/runner/work/repo/repo/crates/playground/src/chrome.rs", + "crates/playground/src/chrome.rs", + ), + ( + "/Users/dev/packages/repo/crates/playground/src/chrome.rs", + "crates/playground/src/chrome.rs", + ), + ( + "/Users/runner/work/repo/repo/packages/ui/ui/src/lib.rs", + "crates/ui/src/lib.rs", + ), + ( + "/Users/runner/work/repo/repo/packages/ui/kit/src/button.rs", + "crates/kit/src/button.rs", + ), + ( + r"C:\work\repo\packages\frontend\mobile\src\lib.rs", + "packages/frontend/mobile/src/lib.rs", + ), + ( + "../../crates/playground/src/lib.rs", + "crates/playground/src/lib.rs", + ), + ]; + for (raw, expected) in cases { + assert_eq!(normalize_callsite_path(raw), expected, "raw={raw}"); + } + } } diff --git a/blocksuite/native-playground/crates/ui/src/input.rs b/packages/ui/ui/src/input.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/input.rs rename to packages/ui/ui/src/input.rs diff --git a/blocksuite/native-playground/crates/ui/src/interactive.rs b/packages/ui/ui/src/interactive.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/interactive.rs rename to packages/ui/ui/src/interactive.rs diff --git a/blocksuite/native-playground/crates/ui/src/key_dispatch.rs b/packages/ui/ui/src/key_dispatch.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/key_dispatch.rs rename to packages/ui/ui/src/key_dispatch.rs diff --git a/blocksuite/native-playground/crates/ui/src/keymap.rs b/packages/ui/ui/src/keymap.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/keymap.rs rename to packages/ui/ui/src/keymap.rs diff --git a/blocksuite/native-playground/crates/ui/src/keymap/binding.rs b/packages/ui/ui/src/keymap/binding.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/keymap/binding.rs rename to packages/ui/ui/src/keymap/binding.rs diff --git a/blocksuite/native-playground/crates/ui/src/keymap/context.rs b/packages/ui/ui/src/keymap/context.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/keymap/context.rs rename to packages/ui/ui/src/keymap/context.rs diff --git a/blocksuite/native-playground/crates/ui/src/lib.rs b/packages/ui/ui/src/lib.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/lib.rs rename to packages/ui/ui/src/lib.rs diff --git a/blocksuite/native-playground/crates/ui/src/motion.rs b/packages/ui/ui/src/motion.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/motion.rs rename to packages/ui/ui/src/motion.rs diff --git a/blocksuite/native-playground/crates/ui/src/path_builder.rs b/packages/ui/ui/src/path_builder.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/path_builder.rs rename to packages/ui/ui/src/path_builder.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform.rs b/packages/ui/ui/src/platform.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform.rs rename to packages/ui/ui/src/platform.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/app_menu.rs b/packages/ui/ui/src/platform/app_menu.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/app_menu.rs rename to packages/ui/ui/src/platform/app_menu.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/dispatcher.rs b/packages/ui/ui/src/platform/apple/dispatcher.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/dispatcher.rs rename to packages/ui/ui/src/platform/apple/dispatcher.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/display_link.rs b/packages/ui/ui/src/platform/apple/display_link.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/display_link.rs rename to packages/ui/ui/src/platform/apple/display_link.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/fast/color_bitmap_fonts.rs b/packages/ui/ui/src/platform/apple/fast/color_bitmap_fonts.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/fast/color_bitmap_fonts.rs rename to packages/ui/ui/src/platform/apple/fast/color_bitmap_fonts.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/fast/font_fallbacks.rs b/packages/ui/ui/src/platform/apple/fast/font_fallbacks.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/fast/font_fallbacks.rs rename to packages/ui/ui/src/platform/apple/fast/font_fallbacks.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/fast/mod.rs b/packages/ui/ui/src/platform/apple/fast/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/fast/mod.rs rename to packages/ui/ui/src/platform/apple/fast/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/fast/paths.rs b/packages/ui/ui/src/platform/apple/fast/paths.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/fast/paths.rs rename to packages/ui/ui/src/platform/apple/fast/paths.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/fast/rounded_clip.rs b/packages/ui/ui/src/platform/apple/fast/rounded_clip.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/fast/rounded_clip.rs rename to packages/ui/ui/src/platform/apple/fast/rounded_clip.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/fast/rounded_clip_shader.rs b/packages/ui/ui/src/platform/apple/fast/rounded_clip_shader.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/fast/rounded_clip_shader.rs rename to packages/ui/ui/src/platform/apple/fast/rounded_clip_shader.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/fast/text_system.rs b/packages/ui/ui/src/platform/apple/fast/text_system.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/fast/text_system.rs rename to packages/ui/ui/src/platform/apple/fast/text_system.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/metal_atlas.rs b/packages/ui/ui/src/platform/apple/metal_atlas.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/metal_atlas.rs rename to packages/ui/ui/src/platform/apple/metal_atlas.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/metal_renderer.rs b/packages/ui/ui/src/platform/apple/metal_renderer.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/metal_renderer.rs rename to packages/ui/ui/src/platform/apple/metal_renderer.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/mod.rs b/packages/ui/ui/src/platform/apple/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/mod.rs rename to packages/ui/ui/src/platform/apple/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/open_type.rs b/packages/ui/ui/src/platform/apple/open_type.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/open_type.rs rename to packages/ui/ui/src/platform/apple/open_type.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/shaders.metal b/packages/ui/ui/src/platform/apple/shaders.metal similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/shaders.metal rename to packages/ui/ui/src/platform/apple/shaders.metal diff --git a/blocksuite/native-playground/crates/ui/src/platform/apple/text_system.rs b/packages/ui/ui/src/platform/apple/text_system.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/apple/text_system.rs rename to packages/ui/ui/src/platform/apple/text_system.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/click_state.rs b/packages/ui/ui/src/platform/click_state.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/click_state.rs rename to packages/ui/ui/src/platform/click_state.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/clock.rs b/packages/ui/ui/src/platform/clock.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/clock.rs rename to packages/ui/ui/src/platform/clock.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/headless/mod.rs b/packages/ui/ui/src/platform/headless/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/headless/mod.rs rename to packages/ui/ui/src/platform/headless/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/keyboard.rs b/packages/ui/ui/src/platform/keyboard.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/keyboard.rs rename to packages/ui/ui/src/platform/keyboard.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/keystroke.rs b/packages/ui/ui/src/platform/keystroke.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/keystroke.rs rename to packages/ui/ui/src/platform/keystroke.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/macos/display.rs b/packages/ui/ui/src/platform/macos/display.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/macos/display.rs rename to packages/ui/ui/src/platform/macos/display.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/macos/display_link.rs b/packages/ui/ui/src/platform/macos/display_link.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/macos/display_link.rs rename to packages/ui/ui/src/platform/macos/display_link.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/macos/events.rs b/packages/ui/ui/src/platform/macos/events.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/macos/events.rs rename to packages/ui/ui/src/platform/macos/events.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/macos/fast/display_link_lifecycle.rs b/packages/ui/ui/src/platform/macos/fast/display_link_lifecycle.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/macos/fast/display_link_lifecycle.rs rename to packages/ui/ui/src/platform/macos/fast/display_link_lifecycle.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/macos/fast/menu.rs b/packages/ui/ui/src/platform/macos/fast/menu.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/macos/fast/menu.rs rename to packages/ui/ui/src/platform/macos/fast/menu.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/macos/fast/mod.rs b/packages/ui/ui/src/platform/macos/fast/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/macos/fast/mod.rs rename to packages/ui/ui/src/platform/macos/fast/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/macos/keyboard.rs b/packages/ui/ui/src/platform/macos/keyboard.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/macos/keyboard.rs rename to packages/ui/ui/src/platform/macos/keyboard.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/macos/mod.rs b/packages/ui/ui/src/platform/macos/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/macos/mod.rs rename to packages/ui/ui/src/platform/macos/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/macos/pasteboard.rs b/packages/ui/ui/src/platform/macos/pasteboard.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/macos/pasteboard.rs rename to packages/ui/ui/src/platform/macos/pasteboard.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/macos/platform.rs b/packages/ui/ui/src/platform/macos/platform.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/macos/platform.rs rename to packages/ui/ui/src/platform/macos/platform.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/macos/window.rs b/packages/ui/ui/src/platform/macos/window.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/macos/window.rs rename to packages/ui/ui/src/platform/macos/window.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/macos/window_appearance.rs b/packages/ui/ui/src/platform/macos/window_appearance.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/macos/window_appearance.rs rename to packages/ui/ui/src/platform/macos/window_appearance.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/platform_info.rs b/packages/ui/ui/src/platform/platform_info.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/platform_info.rs rename to packages/ui/ui/src/platform/platform_info.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/popup.rs b/packages/ui/ui/src/platform/popup.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/popup.rs rename to packages/ui/ui/src/platform/popup.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/threaded_dispatcher.rs b/packages/ui/ui/src/platform/threaded_dispatcher.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/threaded_dispatcher.rs rename to packages/ui/ui/src/platform/threaded_dispatcher.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/canvas_fallback.rs b/packages/ui/ui/src/platform/web/canvas_fallback.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/canvas_fallback.rs rename to packages/ui/ui/src/platform/web/canvas_fallback.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/canvas_text.rs b/packages/ui/ui/src/platform/web/canvas_text.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/canvas_text.rs rename to packages/ui/ui/src/platform/web/canvas_text.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/dispatcher.rs b/packages/ui/ui/src/platform/web/dispatcher.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/dispatcher.rs rename to packages/ui/ui/src/platform/web/dispatcher.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/display.rs b/packages/ui/ui/src/platform/web/display.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/display.rs rename to packages/ui/ui/src/platform/web/display.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/events.rs b/packages/ui/ui/src/platform/web/events.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/events.rs rename to packages/ui/ui/src/platform/web/events.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/fast/canvas_size.rs b/packages/ui/ui/src/platform/web/fast/canvas_size.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/fast/canvas_size.rs rename to packages/ui/ui/src/platform/web/fast/canvas_size.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/fast/ime_edit.rs b/packages/ui/ui/src/platform/web/fast/ime_edit.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/fast/ime_edit.rs rename to packages/ui/ui/src/platform/web/fast/ime_edit.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/fast/ime_keys.rs b/packages/ui/ui/src/platform/web/fast/ime_keys.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/fast/ime_keys.rs rename to packages/ui/ui/src/platform/web/fast/ime_keys.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/fast/ime_position.rs b/packages/ui/ui/src/platform/web/fast/ime_position.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/fast/ime_position.rs rename to packages/ui/ui/src/platform/web/fast/ime_position.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/fast/mod.rs b/packages/ui/ui/src/platform/web/fast/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/fast/mod.rs rename to packages/ui/ui/src/platform/web/fast/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/fast/wgpu_context.rs b/packages/ui/ui/src/platform/web/fast/wgpu_context.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/fast/wgpu_context.rs rename to packages/ui/ui/src/platform/web/fast/wgpu_context.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/glyph_cache.rs b/packages/ui/ui/src/platform/web/glyph_cache.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/glyph_cache.rs rename to packages/ui/ui/src/platform/web/glyph_cache.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/ime_mirror.rs b/packages/ui/ui/src/platform/web/ime_mirror.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/ime_mirror.rs rename to packages/ui/ui/src/platform/web/ime_mirror.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/keyboard.rs b/packages/ui/ui/src/platform/web/keyboard.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/keyboard.rs rename to packages/ui/ui/src/platform/web/keyboard.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/logging.rs b/packages/ui/ui/src/platform/web/logging.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/logging.rs rename to packages/ui/ui/src/platform/web/logging.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/mod.rs b/packages/ui/ui/src/platform/web/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/mod.rs rename to packages/ui/ui/src/platform/web/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/platform.rs b/packages/ui/ui/src/platform/web/platform.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/platform.rs rename to packages/ui/ui/src/platform/web/platform.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/run_replacements.rs b/packages/ui/ui/src/platform/web/run_replacements.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/run_replacements.rs rename to packages/ui/ui/src/platform/web/run_replacements.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/text_system.rs b/packages/ui/ui/src/platform/web/text_system.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/text_system.rs rename to packages/ui/ui/src/platform/web/text_system.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/viewport.rs b/packages/ui/ui/src/platform/web/viewport.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/viewport.rs rename to packages/ui/ui/src/platform/web/viewport.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/window.rs b/packages/ui/ui/src/platform/web/window.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/web/window.rs rename to packages/ui/ui/src/platform/web/window.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/cosmic_text_system.rs b/packages/ui/ui/src/platform/wgpu/cosmic_text_system.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/cosmic_text_system.rs rename to packages/ui/ui/src/platform/wgpu/cosmic_text_system.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/atlas.rs b/packages/ui/ui/src/platform/wgpu/fast/atlas.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/atlas.rs rename to packages/ui/ui/src/platform/wgpu/fast/atlas.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/bind_groups.rs b/packages/ui/ui/src/platform/wgpu/fast/bind_groups.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/bind_groups.rs rename to packages/ui/ui/src/platform/wgpu/fast/bind_groups.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/emoji_fonts.rs b/packages/ui/ui/src/platform/wgpu/fast/emoji_fonts.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/emoji_fonts.rs rename to packages/ui/ui/src/platform/wgpu/fast/emoji_fonts.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/frame.rs b/packages/ui/ui/src/platform/wgpu/fast/frame.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/frame.rs rename to packages/ui/ui/src/platform/wgpu/fast/frame.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/globals.rs b/packages/ui/ui/src/platform/wgpu/fast/globals.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/globals.rs rename to packages/ui/ui/src/platform/wgpu/fast/globals.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/mod.rs b/packages/ui/ui/src/platform/wgpu/fast/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/mod.rs rename to packages/ui/ui/src/platform/wgpu/fast/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/pass_state.rs b/packages/ui/ui/src/platform/wgpu/fast/pass_state.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/pass_state.rs rename to packages/ui/ui/src/platform/wgpu/fast/pass_state.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/rounded_clip.rs b/packages/ui/ui/src/platform/wgpu/fast/rounded_clip.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/rounded_clip.rs rename to packages/ui/ui/src/platform/wgpu/fast/rounded_clip.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/wgpu_context.rs b/packages/ui/ui/src/platform/wgpu/fast/wgpu_context.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/fast/wgpu_context.rs rename to packages/ui/ui/src/platform/wgpu/fast/wgpu_context.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/mod.rs b/packages/ui/ui/src/platform/wgpu/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/mod.rs rename to packages/ui/ui/src/platform/wgpu/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/shaders.wgsl b/packages/ui/ui/src/platform/wgpu/shaders.wgsl similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/shaders.wgsl rename to packages/ui/ui/src/platform/wgpu/shaders.wgsl diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/shaders_storage.wgsl b/packages/ui/ui/src/platform/wgpu/shaders_storage.wgsl similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/shaders_storage.wgsl rename to packages/ui/ui/src/platform/wgpu/shaders_storage.wgsl diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/shaders_subpixel.wgsl b/packages/ui/ui/src/platform/wgpu/shaders_subpixel.wgsl similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/shaders_subpixel.wgsl rename to packages/ui/ui/src/platform/wgpu/shaders_subpixel.wgsl diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/shaders_webgl.wgsl b/packages/ui/ui/src/platform/wgpu/shaders_webgl.wgsl similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/shaders_webgl.wgsl rename to packages/ui/ui/src/platform/wgpu/shaders_webgl.wgsl diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/wgpu_atlas.rs b/packages/ui/ui/src/platform/wgpu/wgpu_atlas.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/wgpu_atlas.rs rename to packages/ui/ui/src/platform/wgpu/wgpu_atlas.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/wgpu_context.rs b/packages/ui/ui/src/platform/wgpu/wgpu_context.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/wgpu_context.rs rename to packages/ui/ui/src/platform/wgpu/wgpu_context.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform/wgpu/wgpu_renderer.rs b/packages/ui/ui/src/platform/wgpu/wgpu_renderer.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform/wgpu/wgpu_renderer.rs rename to packages/ui/ui/src/platform/wgpu/wgpu_renderer.rs diff --git a/blocksuite/native-playground/crates/ui/src/platform_scheduler.rs b/packages/ui/ui/src/platform_scheduler.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/platform_scheduler.rs rename to packages/ui/ui/src/platform_scheduler.rs diff --git a/blocksuite/native-playground/crates/ui/src/prelude.rs b/packages/ui/ui/src/prelude.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/prelude.rs rename to packages/ui/ui/src/prelude.rs diff --git a/blocksuite/native-playground/crates/ui/src/queue.rs b/packages/ui/ui/src/queue.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/queue.rs rename to packages/ui/ui/src/queue.rs diff --git a/blocksuite/native-playground/crates/ui/src/refineable.rs b/packages/ui/ui/src/refineable.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/refineable.rs rename to packages/ui/ui/src/refineable.rs diff --git a/blocksuite/native-playground/crates/ui/src/scene.rs b/packages/ui/ui/src/scene.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/scene.rs rename to packages/ui/ui/src/scene.rs diff --git a/blocksuite/native-playground/crates/ui/src/scheduler/clock.rs b/packages/ui/ui/src/scheduler/clock.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/scheduler/clock.rs rename to packages/ui/ui/src/scheduler/clock.rs diff --git a/blocksuite/native-playground/crates/ui/src/scheduler/executor.rs b/packages/ui/ui/src/scheduler/executor.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/scheduler/executor.rs rename to packages/ui/ui/src/scheduler/executor.rs diff --git a/blocksuite/native-playground/crates/ui/src/scheduler/fast/clock.rs b/packages/ui/ui/src/scheduler/fast/clock.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/scheduler/fast/clock.rs rename to packages/ui/ui/src/scheduler/fast/clock.rs diff --git a/blocksuite/native-playground/crates/ui/src/scheduler/fast/mod.rs b/packages/ui/ui/src/scheduler/fast/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/scheduler/fast/mod.rs rename to packages/ui/ui/src/scheduler/fast/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/scheduler/mod.rs b/packages/ui/ui/src/scheduler/mod.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/scheduler/mod.rs rename to packages/ui/ui/src/scheduler/mod.rs diff --git a/blocksuite/native-playground/crates/ui/src/scheduler/test_scheduler.rs b/packages/ui/ui/src/scheduler/test_scheduler.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/scheduler/test_scheduler.rs rename to packages/ui/ui/src/scheduler/test_scheduler.rs diff --git a/blocksuite/native-playground/crates/ui/src/shared_string.rs b/packages/ui/ui/src/shared_string.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/shared_string.rs rename to packages/ui/ui/src/shared_string.rs diff --git a/blocksuite/native-playground/crates/ui/src/shared_uri.rs b/packages/ui/ui/src/shared_uri.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/shared_uri.rs rename to packages/ui/ui/src/shared_uri.rs diff --git a/blocksuite/native-playground/crates/ui/src/style.rs b/packages/ui/ui/src/style.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/style.rs rename to packages/ui/ui/src/style.rs diff --git a/blocksuite/native-playground/crates/ui/src/styled.rs b/packages/ui/ui/src/styled.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/styled.rs rename to packages/ui/ui/src/styled.rs diff --git a/blocksuite/native-playground/crates/ui/src/subscription.rs b/packages/ui/ui/src/subscription.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/subscription.rs rename to packages/ui/ui/src/subscription.rs diff --git a/blocksuite/native-playground/crates/ui/src/svg_renderer.rs b/packages/ui/ui/src/svg_renderer.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/svg_renderer.rs rename to packages/ui/ui/src/svg_renderer.rs diff --git a/blocksuite/native-playground/crates/ui/src/taffy.rs b/packages/ui/ui/src/taffy.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/taffy.rs rename to packages/ui/ui/src/taffy.rs diff --git a/blocksuite/native-playground/crates/ui/src/text_system.rs b/packages/ui/ui/src/text_system.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/text_system.rs rename to packages/ui/ui/src/text_system.rs diff --git a/blocksuite/native-playground/crates/ui/src/text_system/font_fallbacks.rs b/packages/ui/ui/src/text_system/font_fallbacks.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/text_system/font_fallbacks.rs rename to packages/ui/ui/src/text_system/font_fallbacks.rs diff --git a/blocksuite/native-playground/crates/ui/src/text_system/font_features.rs b/packages/ui/ui/src/text_system/font_features.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/text_system/font_features.rs rename to packages/ui/ui/src/text_system/font_features.rs diff --git a/blocksuite/native-playground/crates/ui/src/text_system/line.rs b/packages/ui/ui/src/text_system/line.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/text_system/line.rs rename to packages/ui/ui/src/text_system/line.rs diff --git a/blocksuite/native-playground/crates/ui/src/text_system/line_layout.rs b/packages/ui/ui/src/text_system/line_layout.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/text_system/line_layout.rs rename to packages/ui/ui/src/text_system/line_layout.rs diff --git a/blocksuite/native-playground/crates/ui/src/text_system/line_wrapper.rs b/packages/ui/ui/src/text_system/line_wrapper.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/text_system/line_wrapper.rs rename to packages/ui/ui/src/text_system/line_wrapper.rs diff --git a/blocksuite/native-playground/crates/ui/src/util.rs b/packages/ui/ui/src/util.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/util.rs rename to packages/ui/ui/src/util.rs diff --git a/blocksuite/native-playground/crates/ui/src/view.rs b/packages/ui/ui/src/view.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/view.rs rename to packages/ui/ui/src/view.rs diff --git a/blocksuite/native-playground/crates/ui/src/window.rs b/packages/ui/ui/src/window.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/window.rs rename to packages/ui/ui/src/window.rs diff --git a/blocksuite/native-playground/crates/ui/src/window/prompts.rs b/packages/ui/ui/src/window/prompts.rs similarity index 100% rename from blocksuite/native-playground/crates/ui/src/window/prompts.rs rename to packages/ui/ui/src/window/prompts.rs diff --git a/scripts/ci/check-l0-tier-a.mjs b/scripts/ci/check-l0-tier-a.mjs index 69299e77ad..e4a6ce2b7d 100644 --- a/scripts/ci/check-l0-tier-a.mjs +++ b/scripts/ci/check-l0-tier-a.mjs @@ -20,6 +20,10 @@ // 7. compat-backlog: every `// compat(): -- ` marker in // packages/backend/ production Rust has a `### ` entry in // docs/post-cutover-ablation-backlog.md, and every entry has a marker. +// 8. Directory classification: every first-level subdirectory under +// packages/frontend/, packages/common/, and blocksuite/ belongs to a known +// legacy Web set or a known Rust/client set, and native-playground.yml's +// web-build filter covers every legacy Web subdirectory. import { createHash } from 'node:crypto'; import { @@ -761,6 +765,184 @@ if (!existsSync(COMPAT_BACKLOG_PATH)) { } } +// 8. Top-level directory classification for web-build filter ---------------- + +const DOMAIN_CLASSIFICATION = { + 'packages/ui': { + legacyWeb: new Set([]), + newRust: new Set(['ui', 'kit', 'tokens']), + ignored: new Set(['node_modules']), + }, + 'packages/frontend': { + legacyWeb: new Set([ + 'admin', + 'apps', + 'component', + 'core', + 'electron-api', + 'i18n', + 'mobile-native', + 'native', + 'routes', + 'templates', + 'track', + ]), + newRust: new Set([ + 'client', + 'desktop', + 'hosts', + 'legacy-import', + 'mobile', + 'perf', + 'scripts', + ]), + ignored: new Set(['target', 'artifacts', 'node_modules']), + }, + 'packages/common': { + legacyWeb: new Set([ + 'auth', + 'debug', + 'env', + 'error', + 'graphql', + 'infra', + 'native', + 'nbstore', + 'reader', + 'realtime', + 's3-compat', + 'theme', + ]), + newRust: new Set(['store']), + ignored: new Set(['node_modules']), + }, + blocksuite: { + legacyWeb: new Set([ + 'affine', + 'docs', + 'docs-site', + 'framework', + 'integration-test', + 'playground', + ]), + newRust: new Set(['crates']), + ignored: new Set(['node_modules']), + }, +}; + +const WEB_BUILD_FIXED_ENTRIES = new Set([ + 'blocksuite/tsconfig.json', + 'tools/cli/**', + '**/package.json', + '**/tsconfig*.json', + 'yarn.lock', + '.yarnrc.yml', + '.yarn/**', + '.github/actions/setup-node/**', + '.github/workflows/np-web-build.yml', +]); + +const npWorkflowPath = join(WORKFLOWS, 'native-playground.yml'); +const npWorkflowText = existsSync(npWorkflowPath) ? read(npWorkflowPath) : ''; +const webBuildSectionMatch = /^\s*web-build:\n((?:\s+-\s+.*\n)+)/m.exec( + npWorkflowText +); +const webBuildEntries = new Set( + (webBuildSectionMatch?.[1] ?? '') + .split('\n') + .map(l => /^\s*-\s+['"]?([^'"]+?)['"]?\s*$/.exec(l)?.[1]) + .filter(Boolean) +); + +const expectedWebBuildEntries = new Set(WEB_BUILD_FIXED_ENTRIES); + +for (const [baseDir, sets] of Object.entries(DOMAIN_CLASSIFICATION)) { + const fullBase = join(ROOT, baseDir); + if (!existsSync(fullBase)) continue; + for (const entry of readdirSync(fullBase, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + const name = entry.name; + if (sets.ignored.has(name)) continue; + if (!sets.legacyWeb.has(name) && !sets.newRust.has(name)) { + fail( + 'dir-classification', + `${baseDir}/${name}: unclassified directory; add it to legacyWeb (and native-playground.yml web-build) or newRust in scripts/ci/check-l0-tier-a.mjs` + ); + } + } + for (const legacy of sets.legacyWeb) { + expectedWebBuildEntries.add(`${baseDir}/${legacy}/**`); + } +} + +for (const expected of expectedWebBuildEntries) { + if (!webBuildEntries.has(expected)) { + fail( + 'dir-classification', + `.github/workflows/native-playground.yml: web-build filter is missing ${expected}` + ); + } +} +for (const actual of webBuildEntries) { + if (!expectedWebBuildEntries.has(actual)) { + fail( + 'dir-classification', + `.github/workflows/native-playground.yml: web-build filter contains unexpected broad or unknown pattern ${actual}` + ); + } +} + +function globToRegExp(glob) { + let out = '^'; + for (let i = 0; i < glob.length; i += 1) { + if (glob.slice(i, i + 3) === '**/') { + out += '(?:.*/)?'; + i += 2; + } else if (glob.slice(i, i + 2) === '**') { + out += '.*'; + i += 1; + } else if (glob[i] === '*') { + out += '[^/]*'; + } else { + out += glob[i].replace(/[.+?^${}()|[\]\\]/g, '\\$&'); + } + } + return new RegExp(`${out}$`); +} + +const webBuildRegexes = [...webBuildEntries].map(globToRegExp); +const matchesWebBuild = paths => + paths.some(p => webBuildRegexes.some(re => re.test(p))); + +const WEB_BUILD_FILTER_CASES = [ + ['oracle-only', ['blocksuite/crates/oracle/style-oracle.json'], false], + [ + 'rust-only', + [ + 'packages/ui/ui/src/lib.rs', + 'packages/common/store/AGENTS.md', + 'blocksuite/crates/doc/src/lib.rs', + ], + false, + ], + ['legacy-ts', ['packages/frontend/core/src/index.ts'], true], + [ + 'mixed', + ['packages/ui/ui/src/lib.rs', 'packages/common/infra/src/index.ts'], + true, + ], +]; + +for (const [label, paths, expected] of WEB_BUILD_FILTER_CASES) { + const actual = matchesWebBuild(paths); + if (actual !== expected) { + fail( + 'dir-classification', + `web-build filter self-test "${label}" returned ${actual}, expected ${expected}` + ); + } +} + // --------------------------------------------------------------------------- const ms = Math.round(performance.now() - started);