Files
AFFiNE/packages/ui/AGENTS.md
T
DarkSky 22649e8852 perf(ui): keep path triangles on the GPU between frames
Keep the triangles of a path in an Arc with an identity. A change gives the triangles a new identity. The process never gives an identity twice.

Paint a path without a copy of its vertices. The scene path shares the triangles and keeps the scale factor and the paint transformation. The vertex shaders scale and transform the vertices in the order of operations of the CPU code. The Metal shader turns off fast-math contraction and reassociation for this.

A GPU can fuse a multiply and an add into one rounding. For a rotation or a skew, the renderer thus keeps screen positions that the CPU placed. The GPU still scales the vertices for the local clip.

Keep the triangles of each identity in a pool on the GPU. Append only the triangles that no earlier frame drew. Replace the pool when it is full or when the frame uses less than one eighth of it. Never write to a part of the pool that a frame can read. After a failed upload, forget the pool.

Draw each path with one 144-byte instance record. Use this design for storage buffers, the WebGL2 texture transport, and Metal. Write WebGL2 instance data and pool data in blocks of whole rows. Each array needs a maximum of four texture writes.

Remove the frame paths of wgpu and Metal that no caller can reach.
2026-12-04 01:21:03 +09:00

9.0 KiB

Working in packages/ui/ (for agents)

packages/ui/ holds the zero-dependency token crate (packages/ui/tokens), the domain-neutral GPU UI library (packages/ui/ui), and the cross-platform component kit (packages/ui/kit). This directory belongs to the client Cargo workspace rooted at packages/frontend/Cargo.toml.

Active Invariants (enforced now)

Workspace boundaries

  • packages/ui/tokens (ui-tokens): Zero-dependency crate (#![forbid(unsafe_code)]) exposing generated tokens (tokens.rs), icons (icons.rs), and the five tracked repository font slices via bundled_font_bytes(), while keeping extract-tokens.mjs --check and standalone rustc --edition 2024 --test gates intact.
  • packages/ui/ui: Single fused internal GPU UI library (vendored once without upstream sync hooks, zero internal proc-macro = true crates, zero external UI-kit dependencies). It knows nothing about BlockSuite or AFFiNE (packages/frontend/scripts/check-invariants.sh rejects blocksuite and affine inside packages/ui/ui) and embeds zero fonts (fonts are registered by the application via cx.text_system().add_fonts(...)).
  • packages/ui/kit (ui-kit): Domain-neutral cross-platform component library (#![forbid(unsafe_code)]) depending only on ui and ui-tokens. Provides LogicalEdges, LogicalStyled, SafeArea, VirtualList, and SwipeDialog (Sheet). packages/frontend/scripts/check-invariants.sh rejects BlockSuite/AFFiNE terms and physical left/right layout helpers inside packages/ui/kit/src.

Platform matrix

packages/ui/ui compiles cleanly across four targets from one crate:

  • macOS (target_os = "macos"): AppKit + Metal + CoreText, including windowless MetalHeadlessRenderer readback, full mip-0 MetalAtlas zero-init, and offscreen MacWindow frame/scale fallbacks.
  • iOS (target_os = "ios"): Metal, CoreText, and GCD shared from platform::apple, with platform::ios (IosPlatform, IosDisplay, IosWindow) checked on aarch64-apple-ios and aarch64-apple-ios-sim.
  • 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(). HeadlessPlatform::new_with_text_system is strictly for deterministic tests and harness custom PlatformTextSystem injection, never an application entry point.
  • 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<Pixels>). All GPU primitives (Quad, Shadow, Underline, MonochromeSprite, SubpixelSprite, PolychromeSprite, and PathInstance) 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.
  • Resident path triangles: A Path shares its triangles (PathVertices, behind an Arc) under a PathGeometryId that every change replaces and that is never given twice. Window::paint_path copies no vertex: the scene's ScenePath shares the triangles, and the GPU scales them by the scale factor and maps them through the paint transformation in the CPU's order of operations. A GPU can fuse a * x + b * y into one rounding, so for a rotation or skew the renderer keeps screen positions that the CPU placed (ScenePath::needs_cpu_placement), and the GPU only scales the vertices for the local clip. The Metal path vertex shader turns off fast-math contraction and reassociation (#pragma clang fp) so that it rounds as the CPU does. Each renderer (wgpu storage buffer, WebGL2 Rgba32Uint texture, Metal buffer) keeps them in a pool (fast/resident_paths.rs) that a frame appends to only for identities no earlier frame drew, and replaces, never overwrites, when it fills or is used under an eighth, and forgets after a failed upload. Each path is one draw with a 144-byte PathInstance. WebGL2 texture writes span whole rows (platform/wgpu/fast/texels.rs, at most four write_texture calls an array).
  • 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 <svg fill> 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).