From bdad4ecff57a5ab6d6ce4b98f0f7005a2e63dfdd Mon Sep 17 00:00:00 2001 From: DarkSky Date: Sun, 22 Nov 2026 09:35:39 +0900 Subject: [PATCH] feat(native-playground): add BlockFlow page renderer, light/dark themes, and live room sync Renders any page document in Page mode from the same y-octo CRDT state the JavaScript editor edits, in both themes, on macOS, Linux headless and the Web. - crates/doc: typed read snapshot (`read.rs`, `PageDocSession::read_page_snapshot`) returning an ordered `PageSnapshot` tree for every supported block flavour with the normalized JSON of each `prop:*`, numbered-list run indices, `prop:textAlign`, the note display modes by their wire values (`both` / `doc` / `edgeless`), detached blocks and lossless `Unknown` blocks; `add_raw_block` for flavours without a typed spec; the room hub now forwards the equal-clock live-to-`null` awareness removal once the last owning connection releases a client; `RoomAwareness::reannounce_local_payload` lands a reconnecting client above the tombstone the relay wrote for it. - crates/playground `theme.rs`: `PlaygroundTheme::{Light, Dark}` resolved from the generated `tokens.rs` / `icons.rs` (included, never copied), `IBM Plex Mono` registered next to `Inter`, and a top bar theme toggle. - crates/playground `block_flow.rs`: world-space `BlockFlow` layout mapped to the screen by `PageViewport`, with per-block reuse across passes. Title, paragraphs and headings, quotes, nested bulleted / numbered / to-do / toggle lists, dividers, code, images, bookmarks and unknown-block cards follow BlockSuite's page metrics (collapsing margins, first-line list prefixes, heading letter spacing, 944px container narrowing below 640px). Text alignment is inherited by nested children, a collapsed heading hides its own children and the siblings under it, and remote carets, selections, name tags and presence badges are drawn from `selectionV2` entries of the shown page only. - crates/playground `rich_text.rs`: `RichParagraph` is the one rich-text engine. `BlockFlow` lays out and paints paragraph and list text with it (`LaidOutRichParagraph::paint_at`) and reads remote carets and selections from its geometry. It now resolves `color` and `background` marks through the theme, follows CSS `bolder`, paints the generated `LinkedPageIcon` for references, wraps a reference as one inline object so the words before it stay on their line, aligns lines left, center or right together with their carets and decorations, and takes its code box metrics from constants a test keeps equal to `tokens/style-oracle.json` instead of embedding the oracle. - crates/playground `room_client.rs`: sans-I/O `RoomProtocol` for the relay's binary room protocol with `tokio-tungstenite` (`--room` / `--relay`) and browser `WebSocket` (`?room=&ws=`) transports, blob fetch (a bare HTTP/1.1 `GET` over TCP natively, `fetch` on the Web) and reconnect with backoff. Native transports reject `wss://` / `https://` relays up front, and a pending connect times out and never holds up blob fetches or shutdown. - Images decode PNG, JPEG, WebP, GIF and BMP once; bytes that are no image stay unavailable. A blob the page references before its upload finished is fetched again on the scheduler clock with a backoff capped at 4 s for as long as the page references it, showing `Loading image`, then `Image unavailable`, then the image. - Deterministic `seed_showcase_doc` workspace when no room is given; `bs-harness render` gains `--theme light|dark` and `--mode page|edgeless`. - `scripts/web-smoke.mjs` gains `--query` and `--min-title-ink` so a page that arrives over a live room is captured after it rendered. - `perf/accepted.json` acknowledges the larger Web bundle and headless binary; the comparator's gate self-test no longer depends on the repository's acceptance file. - Tests: token and block metrics against `tokens/style-oracle.json` in both themes on constants and rendered frames, showcase and edge-content audits across viewports down to 320px, scroll mapping, incremental relayout, text alignment with an inherited child and a remote caret, selection key matching, and live in-process relay tests covering edits, blobs, awareness, a blob uploaded after its image block, and presence after a reconnect. - @blocksuite/playground: `reusePartialSeedDoc` keeps `doc.load(initFn)` initializers working when a promoted seed winner fills a partially seeded doc (a bare `load()` leaves the initializer for the `load(initFn)` that follows), and `initRoomDocWithSeed` rejects a winner whose seed leaves no `affine:page` root. --- blocksuite/native-playground/AGENTS.md | 23 +- blocksuite/native-playground/Cargo.lock | 7 + .../crates/doc/src/awareness.rs | 13 + .../native-playground/crates/doc/src/lib.rs | 1 + .../native-playground/crates/doc/src/read.rs | 594 +++ .../native-playground/crates/doc/src/room.rs | 14 +- .../crates/doc/src/schema.rs | 4 +- .../crates/doc/src/session.rs | 62 +- .../crates/doc/tests/doc_room_sync.rs | 98 + .../crates/doc/tests/page_snapshot.rs | 568 +++ .../crates/playground/Cargo.toml | 27 +- .../crates/playground/src/bin/bs_harness.rs | 55 +- .../crates/playground/src/block_flow.rs | 2304 +++++++++++ .../crates/playground/src/lib.rs | 3599 +++++++++++++++-- .../crates/playground/src/main.rs | 17 +- .../crates/playground/src/rich_text.rs | 614 ++- .../crates/playground/src/room_client.rs | 1193 ++++++ .../crates/playground/src/theme.rs | 384 ++ .../native-playground/perf/accepted.json | 18 +- .../perf/compare-n3.test.mjs | 7 + .../native-playground/scripts/web-smoke.mjs | 25 +- .../sync/room/__tests__/room-sync.spec.ts | 203 +- .../apps/_common/sync/room/index.ts | 74 +- .../apps/starter/utils/collection.ts | 38 +- 24 files changed, 9471 insertions(+), 471 deletions(-) create mode 100644 blocksuite/native-playground/crates/doc/src/read.rs create mode 100644 blocksuite/native-playground/crates/doc/tests/page_snapshot.rs create mode 100644 blocksuite/native-playground/crates/playground/src/block_flow.rs create mode 100644 blocksuite/native-playground/crates/playground/src/room_client.rs create mode 100644 blocksuite/native-playground/crates/playground/src/theme.rs diff --git a/blocksuite/native-playground/AGENTS.md b/blocksuite/native-playground/AGENTS.md index 12dabc0454..8c8b7f063e 100644 --- a/blocksuite/native-playground/AGENTS.md +++ b/blocksuite/native-playground/AGENTS.md @@ -6,15 +6,15 @@ This document records the active engineering invariants enforced in CI today alo ### 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.3.0`. Preserves 53-bit `clientId` (`1..=2^53 - 1`), complete flavour schema defaults (0 JS writeback updates on initial load), top-level Awareness `color` alongside `user` and `selectionV2`, deterministic `now_ms`-driven undo/awareness clocks, WebSocket-only `seed-claim` / `seed-claim-result` single-winner arbitration (keyed by `seed:`), `?ws=` relay origin forwarding with permissive blob CORS headers, and `wasm32-unknown-unknown` compatibility under `--no-default-features`. -- `crates/playground`: Application layer owning the shipping `PlaygroundView`, registration of the tracked Inter variable and IBM Plex Mono (regular, bold, italic and bold italic) faces, the native macOS desktop entry (`native-playground`), the WebAssembly canvas entry (`wasm_main`), and the deterministic headless verification CLI (`bs-harness`). +- `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.3.0`. Preserves 53-bit `clientId` (`1..=2^53 - 1`), complete flavour schema defaults (0 JS writeback updates on initial load), top-level Awareness `color` alongside `user` and `selectionV2`, deterministic `now_ms`-driven undo/awareness clocks, 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.rs` (`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`, 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 (`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.rs` is the Page-mode renderer; `rich_text.rs` is the rich paragraph engine; `room_client.rs` is live room sync. Without a room the view shows the deterministic `seed_showcase_doc` workspace (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`. +- **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). ### 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()`. @@ -25,18 +25,28 @@ This document records the active engineering invariants enforced in CI today alo - **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`. 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). +### 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. +- **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.block.`, `page.presence..caret|label`, `chrome.theme_toggle`, `chrome.presence.`. A block records its element snapshot only while it lies completely inside the page viewport; a block cut by the fold is clipped on purpose. +- **Room sync**: `RoomProtocol` is the sans-I/O client of the relay's binary room protocol (`SyncStep1` / `SyncStep2` / `Update` document frames, awareness frames, unconditional reverse `Step2`) over a `DocState`. `connect` supplies the transport: `tokio-tungstenite` on a background thread natively (`--room [--relay ]`), a browser `WebSocket` on the Web (`?room=&ws=`), both fetching image blobs from `/api/collection/{room}/blob/{sourceId}` (a bare HTTP/1.1 `GET` over TCP natively, `fetch` on the Web) and reconnecting with backoff. Native transports speak plain `ws://` / `http://` only: `wss://` / `https://` relays are rejected up front (`RoomConfig::validate_native`) and stay available on the Web. A reconnect re-announces local awareness two clocks ahead, above the tombstone the relay wrote when the previous connection dropped. Awareness renewal and expiry run on the scheduler clock, never the wall clock. +- **Images and blobs**: A blob present in the document state is decoded once (PNG, JPEG, WebP, GIF, BMP); bytes that are no such image stay `Image unavailable` and are never fetched again. A blob the page references but the relay does not have yet (an uploader writes `sourceId` before its upload finishes, and the relay announces no completed upload) is fetched again on the scheduler clock with a backoff doubling from 500 ms to a 4 s cap, for as long as the page references it and the room is not offline; ordinary document updates never restart a tracked fetch. The frame shows `Loading image`, then `Image unavailable` after three misses, and the image as soon as a retry finds it. +- **Remote selections**: Read only from `selectionV2` entries of the shown page, keyed `` or `:` (split at the last colon, stricter than BlockSuite's prefix match); a selection in another page is never drawn. + ### 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`**: 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. Its drawn page-glyph prefix stands in for the SVG page icon until BlockFlow supports inline SVG painting. 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`. Plain and rich renders of one document can be reproduced with `bs-harness render-rich-sample --out-plain plain.png --out-rich rich.png`. +- **`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`. ## Planned Contracts (upcoming crates & features) -- **Editor & whiteboard rendering**: `BlockFlow`, `EditorSession`, and world-space content transforms/masks (implemented end-to-end in the GPU shaders) separating world-space document/whiteboard geometry from screen-space GPUI chrome. +- **Editor & whiteboard rendering**: `EditorSession`, world-space content transforms/masks implemented end-to-end in the GPU shaders (today `BlockFlow` applies the world-to-screen mapping per element on the CPU), and the Edgeless whiteboard surface (Edgeless mode shows a placeholder card). ## Build & verification commands @@ -49,6 +59,7 @@ CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p ui -p playground --target was 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 ./scripts/check-invariants.sh node --test perf/compare-n3.test.mjs node tokens/extract-tokens.mjs --check diff --git a/blocksuite/native-playground/Cargo.lock b/blocksuite/native-playground/Cargo.lock index 5f9532c47a..cbf8a1c4cb 100644 --- a/blocksuite/native-playground/Cargo.lock +++ b/blocksuite/native-playground/Cargo.lock @@ -2407,17 +2407,24 @@ name = "playground" version = "0.1.0" dependencies = [ "anyhow", + "async-channel", + "axum", "blocksuite-playground-doc", "console_error_panic_hook", + "futures-util", "image", + "js-sys", "serde", "serde_json", "tempfile", + "tokio", + "tokio-tungstenite 0.26.2", "ui", "unicode-bidi", "unicode-linebreak", "unicode-segmentation", "wasm-bindgen", + "wasm-bindgen-futures", "web-sys", "y-octo", ] diff --git a/blocksuite/native-playground/crates/doc/src/awareness.rs b/blocksuite/native-playground/crates/doc/src/awareness.rs index 9e096cca91..0d2a0791dc 100644 --- a/blocksuite/native-playground/crates/doc/src/awareness.rs +++ b/blocksuite/native-playground/crates/doc/src/awareness.rs @@ -160,6 +160,19 @@ impl RoomAwareness { Ok(self.inner.encode_update(Some(&[self.inner.local_id()]))?) } + /// Set the local payload again after the connection that carried it was lost. The relay + /// tombstoned this client one clock above its last state when that connection dropped, + /// so the local clock advances twice to land above the tombstone. + pub fn reannounce_local_payload( + &mut self, + payload: &AwarenessPayload, + now_ms: u64, + ) -> DocResult> { + payload.validate()?; + self.inner.set_local_state(serde_json::to_string(payload)?); + self.set_local_payload(payload, now_ms) + } + /// Mark the local client offline (`null`) and return the encoded removal update. pub fn clear_local_state(&mut self) -> DocResult> { self.inner.clear_local_state(); diff --git a/blocksuite/native-playground/crates/doc/src/lib.rs b/blocksuite/native-playground/crates/doc/src/lib.rs index 7ccf93cbef..671e634ef0 100644 --- a/blocksuite/native-playground/crates/doc/src/lib.rs +++ b/blocksuite/native-playground/crates/doc/src/lib.rs @@ -1,6 +1,7 @@ #![forbid(unsafe_code)] pub mod awareness; +pub mod read; #[cfg(all(feature = "server", not(target_family = "wasm")))] pub mod room; pub mod schema; diff --git a/blocksuite/native-playground/crates/doc/src/read.rs b/blocksuite/native-playground/crates/doc/src/read.rs new file mode 100644 index 0000000000..dd90b101f0 --- /dev/null +++ b/blocksuite/native-playground/crates/doc/src/read.rs @@ -0,0 +1,594 @@ +//! Typed, deterministic read snapshot of a page document's `blocks` tree. +//! +//! [`PageDocSession::read_page_snapshot`] walks the `blocks` root `Y.Map` from the +//! `affine:page` root through every `sys:children` array and returns ordered +//! [`BlockNode`]s. Each node carries a typed [`BlockContent`] for rendering plus the +//! normalized JSON of every `prop:*` entry, so no property is dropped on the way. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::Value as JsonValue; +use y_octo::{Any, SessionReadValue, TextDeltaOp, TextInsert, TypeTarget}; + +use crate::{ + DocResult, + schema::{ListType, ParagraphType, UnknownBlock}, + session::PageDocSession, +}; + +/// Maximum nesting depth followed through `sys:children` before a subtree is cut off. +pub const MAX_BLOCK_DEPTH: usize = 256; + +/// A `Y.Text` property: its plain string and its coalesced insert-only delta. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct RichText { + pub plain: String, + pub delta: Vec, +} + +impl RichText { + pub fn is_empty(&self) -> bool { + self.plain.is_empty() && self.delta.is_empty() + } +} + +/// `prop:displayMode` of an `affine:note`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NoteDisplayMode { + /// Shown in both Page and Edgeless modes (`"both"`). + Both, + /// Shown only in Page mode (`"doc"`). + DocOnly, + /// Shown only in Edgeless mode (`"edgeless"`). + EdgelessOnly, +} + +impl NoteDisplayMode { + pub fn as_str(self) -> &'static str { + match self { + Self::Both => "both", + Self::DocOnly => "doc", + Self::EdgelessOnly => "edgeless", + } + } + + fn parse(value: Option<&str>) -> Self { + match value { + // BlockSuite writes `"doc"`; `"page"` is read as the same mode. + Some("doc" | "page") => Self::DocOnly, + Some("edgeless") => Self::EdgelessOnly, + _ => Self::Both, + } + } +} + +/// `prop:textAlign` of a paragraph or list item. Children without a value of their own +/// inherit the alignment of the nearest ancestor that has one. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum TextAlign { + Left, + Center, + Right, +} + +impl TextAlign { + pub fn as_str(self) -> &'static str { + match self { + Self::Left => "left", + Self::Center => "center", + Self::Right => "right", + } + } + + pub fn parse(value: &str) -> Option { + match value { + "left" => Some(Self::Left), + "center" => Some(Self::Center), + "right" => Some(Self::Right), + _ => None, + } + } +} + +/// Typed content of a block, by `sys:flavour`. +#[derive(Debug, Clone, PartialEq)] +pub enum BlockContent { + Page { + title: RichText, + }, + Surface { + element_count: usize, + }, + Note { + display_mode: NoteDisplayMode, + xywh: String, + background: JsonValue, + hidden: bool, + }, + Paragraph { + kind: ParagraphType, + text: RichText, + collapsed: bool, + /// `prop:textAlign`, when the block sets one. + text_align: Option, + }, + List { + kind: ListType, + checked: bool, + collapsed: bool, + text: RichText, + /// Raw `prop:order` as stored by BlockSuite. + order: Option, + /// 1-based position inside its run of consecutive numbered siblings + /// (`None` unless `kind` is [`ListType::Numbered`]). + numbered_index: Option, + /// `prop:textAlign`, when the block sets one. + text_align: Option, + }, + Divider, + Code { + language: String, + wrap: bool, + text: String, + caption: String, + }, + Image { + source_id: String, + width: Option, + height: Option, + caption: String, + }, + Bookmark { + url: String, + title: Option, + description: Option, + caption: String, + }, + Frame { + title: RichText, + xywh: String, + }, + EdgelessText { + xywh: String, + }, + /// Any flavour without a typed reader, kept with its identity and property keys. + Unknown(UnknownBlock), +} + +/// One block of the document tree with its ordered children. +#[derive(Debug, Clone, PartialEq)] +pub struct BlockNode { + pub id: String, + pub flavour: String, + pub version: Option, + pub content: BlockContent, + /// Normalized JSON of every `prop:*` entry (`Y.Text` as its delta, nested `Y.Map` / + /// `Y.Array` as objects / arrays), keyed by the full property name. + pub props: BTreeMap, + pub children: Vec, +} + +impl BlockNode { + /// Whether this block exists only on the Edgeless canvas and is left out of Page mode. + pub fn is_edgeless_only(&self) -> bool { + match &self.content { + BlockContent::Surface { .. } + | BlockContent::Frame { .. } + | BlockContent::EdgelessText { .. } => true, + BlockContent::Note { display_mode, .. } => { + *display_mode == NoteDisplayMode::EdgelessOnly + } + _ => false, + } + } + + /// Depth-first pre-order iterator over this node and all of its descendants. + pub fn walk(&self) -> impl Iterator { + let mut stack = vec![self]; + std::iter::from_fn(move || { + let node = stack.pop()?; + stack.extend(node.children.iter().rev()); + Some(node) + }) + } +} + +/// Read snapshot of one page document. +#[derive(Debug, Clone, PartialEq)] +pub struct PageSnapshot { + pub doc_id: String, + /// The `affine:page` root block, if the document has been seeded. + pub root: Option, + /// Blocks present in `blocks` but not reachable from `root`, as subtrees ordered by id. + pub detached: Vec, +} + +impl PageSnapshot { + /// Number of blocks in the snapshot, reachable or detached. + pub fn block_count(&self) -> usize { + self.root + .iter() + .chain(self.detached.iter()) + .map(|node| node.walk().count()) + .sum() + } + + /// Find a block by id anywhere in the snapshot. + pub fn block(&self, id: &str) -> Option<&BlockNode> { + self.root + .iter() + .chain(self.detached.iter()) + .flat_map(BlockNode::walk) + .find(|node| node.id == id) + } + + /// Plain title of the `affine:page` root (empty when missing). + pub fn title(&self) -> &str { + match self.root.as_ref().map(|root| &root.content) { + Some(BlockContent::Page { title }) => &title.plain, + _ => "", + } + } +} + +struct RawBlock { + flavour: String, + version: Option, + children: Vec, + entries: BTreeMap, +} + +struct SnapshotReader<'a> { + page: &'a PageDocSession, + raw: BTreeMap, + visited: BTreeSet, +} + +impl PageDocSession { + /// Read the whole `blocks` tree into a typed, ordered [`PageSnapshot`]. + pub fn read_page_snapshot(&self) -> DocResult { + let mut reader = SnapshotReader { + page: self, + raw: BTreeMap::new(), + visited: BTreeSet::new(), + }; + reader.load()?; + + let root_id = reader + .raw + .iter() + .find(|(_, block)| block.flavour == "affine:page") + .map(|(id, _)| id.clone()); + let root = match root_id { + Some(id) => reader.build(&id, 0)?, + None => None, + }; + + // Detached subtrees start at unvisited blocks nobody else references; whatever is + // still unvisited afterwards sits on a reference cycle and is cut at its lowest id. + let referenced: BTreeSet = reader + .raw + .values() + .flat_map(|block| block.children.iter().cloned()) + .collect(); + let ids: Vec = reader.raw.keys().cloned().collect(); + let mut detached = Vec::new(); + for id in ids.iter().filter(|id| !referenced.contains(*id)) { + if let Some(node) = reader.build(id, 0)? { + detached.push(node); + } + } + for id in &ids { + if let Some(node) = reader.build(id, 0)? { + detached.push(node); + } + } + + Ok(PageSnapshot { + doc_id: self.guid().to_string(), + root, + detached, + }) + } +} + +impl SnapshotReader<'_> { + fn load(&mut self) -> DocResult { + let session = self.page.inner(); + for (block_id, value) in session.read_map(self.page.blocks_target())? { + let SessionReadValue::Map(identity) = value else { + continue; + }; + let mut flavour = String::new(); + let mut version = None; + let mut children = Vec::new(); + let mut entries = BTreeMap::new(); + for (key, value) in session.read_map(&TypeTarget::Identity(identity))? { + match (key.as_str(), value) { + ("sys:flavour", SessionReadValue::Any(Any::String(s))) => flavour = s, + ("sys:version", SessionReadValue::Any(any)) => { + version = any_as_f64(&any).map(|v| v as i64); + } + ("sys:children", SessionReadValue::Array(array)) => { + for item in session.read_array(&TypeTarget::Identity(array))? { + if let SessionReadValue::Any(Any::String(child)) = item { + children.push(child); + } + } + } + (_, value) => { + entries.insert(key, value); + } + } + } + self.raw.insert( + block_id, + RawBlock { + flavour, + version, + children, + entries, + }, + ); + } + Ok(()) + } + + fn build(&mut self, id: &str, depth: usize) -> DocResult> { + if depth > MAX_BLOCK_DEPTH || !self.raw.contains_key(id) || !self.visited.insert(id.into()) + { + return Ok(None); + } + let child_ids = self.raw[id].children.clone(); + let mut children = Vec::with_capacity(child_ids.len()); + for child_id in &child_ids { + if let Some(child) = self.build(child_id, depth + 1)? { + children.push(child); + } + } + assign_numbered_indices(&mut children); + + let block = &self.raw[id]; + let mut props = BTreeMap::new(); + for (key, value) in &block.entries { + if key.starts_with("prop:") { + props.insert(key.clone(), self.page.export_y_value(value)?); + } + } + let content = self.read_content(id, block)?; + Ok(Some(BlockNode { + id: id.to_string(), + flavour: block.flavour.clone(), + version: block.version, + content, + props, + children, + })) + } + + fn read_content(&self, id: &str, block: &RawBlock) -> DocResult { + let entries = &block.entries; + Ok(match block.flavour.as_str() { + "affine:page" => BlockContent::Page { + title: self.rich_text(entries.get("prop:title"))?, + }, + "affine:surface" => BlockContent::Surface { + element_count: self.surface_element_count(entries.get("prop:elements"))?, + }, + "affine:note" => BlockContent::Note { + display_mode: NoteDisplayMode::parse( + string(entries.get("prop:displayMode")).as_deref(), + ), + xywh: string(entries.get("prop:xywh")).unwrap_or_default(), + background: match entries.get("prop:background") { + Some(value) => self.page.export_y_value(value)?, + None => JsonValue::Null, + }, + hidden: boolean(entries.get("prop:hidden")), + }, + "affine:paragraph" => BlockContent::Paragraph { + kind: parse_paragraph_type(string(entries.get("prop:type")).as_deref()), + text: self.rich_text(entries.get("prop:text"))?, + collapsed: boolean(entries.get("prop:collapsed")), + text_align: text_align(entries.get("prop:textAlign")), + }, + "affine:list" => BlockContent::List { + kind: parse_list_type(string(entries.get("prop:type")).as_deref()), + checked: boolean(entries.get("prop:checked")), + collapsed: boolean(entries.get("prop:collapsed")), + text: self.rich_text(entries.get("prop:text"))?, + order: number(entries.get("prop:order")).map(|v| v as i64), + numbered_index: None, + text_align: text_align(entries.get("prop:textAlign")), + }, + "affine:divider" => BlockContent::Divider, + "affine:code" => BlockContent::Code { + language: string(entries.get("prop:language")).unwrap_or_default(), + wrap: boolean(entries.get("prop:wrap")), + text: self.rich_text(entries.get("prop:text"))?.plain, + caption: string(entries.get("prop:caption")).unwrap_or_default(), + }, + "affine:image" => BlockContent::Image { + source_id: string(entries.get("prop:sourceId")).unwrap_or_default(), + width: number(entries.get("prop:width")).filter(|v| *v > 0.0), + height: number(entries.get("prop:height")).filter(|v| *v > 0.0), + caption: string(entries.get("prop:caption")).unwrap_or_default(), + }, + "affine:bookmark" => BlockContent::Bookmark { + url: string(entries.get("prop:url")).unwrap_or_default(), + title: string(entries.get("prop:title")), + description: string(entries.get("prop:description")), + caption: string(entries.get("prop:caption")).unwrap_or_default(), + }, + "affine:frame" => BlockContent::Frame { + title: self.rich_text(entries.get("prop:title"))?, + xywh: string(entries.get("prop:xywh")).unwrap_or_default(), + }, + "affine:edgeless-text" => BlockContent::EdgelessText { + xywh: string(entries.get("prop:xywh")).unwrap_or_default(), + }, + _ => BlockContent::Unknown(UnknownBlock { + id: id.to_string(), + flavour: block.flavour.clone(), + version: block.version, + children: block.children.clone(), + prop_keys: entries + .keys() + .filter(|key| key.starts_with("prop:")) + .cloned() + .collect(), + }), + }) + } + + fn rich_text(&self, value: Option<&SessionReadValue>) -> DocResult { + match value { + Some(SessionReadValue::Text(identity)) => { + let raw = self + .page + .inner() + .read_text_delta(&TypeTarget::Identity(identity.clone()))?; + Ok(coalesce_delta(raw)) + } + Some(SessionReadValue::Any(Any::String(s))) if !s.is_empty() => Ok(RichText { + plain: s.clone(), + delta: vec![TextDeltaOp::Insert { + insert: TextInsert::Text(s.clone()), + format: None, + }], + }), + _ => Ok(RichText::default()), + } + } + + fn surface_element_count(&self, value: Option<&SessionReadValue>) -> DocResult { + let Some(SessionReadValue::Map(elements)) = value else { + return Ok(0); + }; + let session = self.page.inner(); + let elements = TypeTarget::Identity(elements.clone()); + match session.get_map_value(&elements, "value")? { + Some(SessionReadValue::Map(value)) => { + Ok(session.read_map(&TypeTarget::Identity(value))?.len()) + } + _ => Ok(0), + } + } +} + +/// Merge adjacent string inserts that share identical attributes (as Yjs `toDelta()` does) +/// and collect the plain string. Embeds stay separate ops and add nothing to `plain`. +fn coalesce_delta(raw: Vec) -> RichText { + let mut plain = String::new(); + let mut delta: Vec = Vec::with_capacity(raw.len()); + for op in raw { + let TextDeltaOp::Insert { insert, format } = op else { + continue; + }; + let format = format.filter(|attrs| !attrs.is_empty()); + match insert { + TextInsert::Text(text) => { + if text.is_empty() { + continue; + } + plain.push_str(&text); + if let Some(TextDeltaOp::Insert { + insert: TextInsert::Text(previous), + format: previous_format, + }) = delta.last_mut() + && *previous_format == format + { + previous.push_str(&text); + continue; + } + delta.push(TextDeltaOp::Insert { + insert: TextInsert::Text(text), + format, + }); + } + embed @ TextInsert::Embed(_) => delta.push(TextDeltaOp::Insert { + insert: embed, + format, + }), + } + } + RichText { plain, delta } +} + +/// Number each run of consecutive `numbered` list siblings. An explicit positive +/// `prop:order` restarts the run at that value, otherwise the run counts up from 1. +fn assign_numbered_indices(children: &mut [BlockNode]) { + let mut previous: Option = None; + for child in children { + previous = match &mut child.content { + BlockContent::List { + kind: ListType::Numbered, + order, + numbered_index, + .. + } => { + let index = order + .and_then(|value| u32::try_from(value).ok()) + .filter(|value| *value > 0) + .unwrap_or_else(|| previous.map_or(1, |value| value.saturating_add(1))); + *numbered_index = Some(index); + Some(index) + } + _ => None, + }; + } +} + +fn parse_paragraph_type(value: Option<&str>) -> ParagraphType { + match value { + Some("h1") => ParagraphType::H1, + Some("h2") => ParagraphType::H2, + Some("h3") => ParagraphType::H3, + Some("h4") => ParagraphType::H4, + Some("h5") => ParagraphType::H5, + Some("h6") => ParagraphType::H6, + Some("quote") => ParagraphType::Quote, + _ => ParagraphType::Text, + } +} + +fn parse_list_type(value: Option<&str>) -> ListType { + match value { + Some("numbered") => ListType::Numbered, + Some("todo") => ListType::Todo, + Some("toggle") => ListType::Toggle, + _ => ListType::Bulleted, + } +} + +fn any_as_f64(any: &Any) -> Option { + match any { + Any::Integer(value) => Some(f64::from(*value)), + Any::BigInt64(value) => Some(*value as f64), + Any::Float32(value) => Some(f64::from(value.0)), + Any::Float64(value) => Some(value.0), + _ => None, + } +} + +fn string(value: Option<&SessionReadValue>) -> Option { + match value { + Some(SessionReadValue::Any(Any::String(s))) => Some(s.clone()), + _ => None, + } +} + +fn text_align(value: Option<&SessionReadValue>) -> Option { + string(value).as_deref().and_then(TextAlign::parse) +} + +fn boolean(value: Option<&SessionReadValue>) -> bool { + matches!(value, Some(SessionReadValue::Any(Any::True))) +} + +fn number(value: Option<&SessionReadValue>) -> Option { + match value { + Some(SessionReadValue::Any(any)) => any_as_f64(any).filter(|v| v.is_finite()), + _ => None, + } +} diff --git a/blocksuite/native-playground/crates/doc/src/room.rs b/blocksuite/native-playground/crates/doc/src/room.rs index 1a447b494b..7bb2c6c4cc 100644 --- a/blocksuite/native-playground/crates/doc/src/room.rs +++ b/blocksuite/native-playground/crates/doc/src/room.rs @@ -310,15 +310,23 @@ impl RoomState { return; } + // `y-protocols` expires a remote peer by announcing `{ clock: c, state: null }` at the + // peer's current clock, and `Awareness::apply_update` accepts that equal-clock + // live-to-deleted transition, so it must reach the other connections as well. let forward_clients: Vec = to_apply .iter() .filter_map(|(&cid, incoming)| { - let is_newer = self + let changes_state = self .awareness .get_states() .get(&cid) - .is_none_or(|existing| incoming.clock() > existing.clock()); - is_newer.then_some(cid) + .is_none_or(|existing| { + incoming.clock() > existing.clock() + || (incoming.clock() == existing.clock() + && incoming.is_deleted() + && !existing.is_deleted()) + }); + changes_state.then_some(cid) }) .collect(); diff --git a/blocksuite/native-playground/crates/doc/src/schema.rs b/blocksuite/native-playground/crates/doc/src/schema.rs index c9d8cf487a..95fc7e31b0 100644 --- a/blocksuite/native-playground/crates/doc/src/schema.rs +++ b/blocksuite/native-playground/crates/doc/src/schema.rs @@ -50,7 +50,7 @@ pub fn affine_block_versions() -> BTreeMap<&'static str, i32> { ]) } -/// Phase-1 block flavours authored natively with full default properties. +/// Supported block flavours authored natively with full default properties. #[derive(Debug, Clone, PartialEq)] pub enum BlockSpec { Page { @@ -156,7 +156,7 @@ pub struct UnknownBlock { pub prop_keys: Vec, } -/// Phase-1 surface element specs written into `affine:surface` `prop:elements` (`Boxed(Y.Map)`). +/// Supported surface element specs written into `affine:surface` `prop:elements` (`Boxed(Y.Map)`). #[derive(Debug, Clone, PartialEq)] pub enum SurfaceElementSpec { Shape { diff --git a/blocksuite/native-playground/crates/doc/src/session.rs b/blocksuite/native-playground/crates/doc/src/session.rs index 5d6ba4d43e..f1d2e83d95 100644 --- a/blocksuite/native-playground/crates/doc/src/session.rs +++ b/blocksuite/native-playground/crates/doc/src/session.rs @@ -93,6 +93,11 @@ impl PageDocSession { &self.session } + /// Target of the `blocks` root `Y.Map` holding every block of this page. + pub fn blocks_target(&self) -> &TypeTarget { + &self.blocks_target + } + pub fn inner_mut(&mut self) -> &mut DocSession { &mut self.session } @@ -130,7 +135,7 @@ impl PageDocSession { }) } - /// Add a typed Phase-1 block with all BlockSuite default properties populated. + /// Add a typed block of a supported flavour with all BlockSuite default properties populated. /// If `parent_id` is `Some`, appends `block_id` to `parent.sys:children` (or inserts at `index`). pub fn add_block( &mut self, @@ -139,6 +144,57 @@ impl PageDocSession { parent_id: Option<&str>, index: Option, now_ms: u64, + ) -> DocResult>> { + let block_id = block_id.into(); + let entries = spec.into_yblock_entries(&block_id); + self.insert_block(block_id, entries, parent_id, index, now_ms) + } + + /// Add a block of any flavour from explicit `prop:*` entries, for flavours without a + /// typed [`BlockSpec`]. `sys:id`, `sys:flavour`, `sys:version` and an empty + /// `sys:children` are written alongside `props`; parent handling matches [`Self::add_block`]. + pub fn add_raw_block( + &mut self, + block_id: impl Into, + flavour: &str, + version: i32, + props: Vec<(String, SessionValue)>, + parent_id: Option<&str>, + index: Option, + now_ms: u64, + ) -> DocResult>> { + let block_id = block_id.into(); + if let Some((key, _)) = props.iter().find(|(key, _)| !key.starts_with("prop:")) { + return Err(DocError::InvalidState(format!( + "raw block property {key:?} must start with \"prop:\"" + ))); + } + let mut entries = vec![ + ( + "sys:id".to_string(), + SessionValue::Any(Any::String(block_id.clone())), + ), + ( + "sys:flavour".to_string(), + SessionValue::Any(Any::String(flavour.to_string())), + ), + ( + "sys:version".to_string(), + SessionValue::Any(Any::Integer(version)), + ), + ("sys:children".to_string(), SessionValue::Array(Vec::new())), + ]; + entries.extend(props); + self.insert_block(block_id, entries, parent_id, index, now_ms) + } + + fn insert_block( + &mut self, + block_id: String, + entries: Vec<(String, SessionValue)>, + parent_id: Option<&str>, + index: Option, + now_ms: u64, ) -> DocResult>> { if let Some(pid) = parent_id { let parent_target = TypeTarget::Path(TypePath::root("blocks").key(pid)); @@ -163,8 +219,6 @@ impl PageDocSession { } self.session.advance_time(now_ms); - let block_id = block_id.into(); - let entries = spec.into_yblock_entries(&block_id); self.session.begin_tx(SessionTxOrigin::Tracked)?; self.session.map_set( @@ -475,7 +529,7 @@ impl PageDocSession { Ok(JsonValue::Object(root)) } - fn export_y_value(&self, value: &SessionReadValue) -> DocResult { + pub(crate) fn export_y_value(&self, value: &SessionReadValue) -> DocResult { match value { SessionReadValue::Any(any) => Ok(any_to_normalized_json(any)), SessionReadValue::Map(id) => { diff --git a/blocksuite/native-playground/crates/doc/tests/doc_room_sync.rs b/blocksuite/native-playground/crates/doc/tests/doc_room_sync.rs index c916257eb5..4157ad5788 100644 --- a/blocksuite/native-playground/crates/doc/tests/doc_room_sync.rs +++ b/blocksuite/native-playground/crates/doc/tests/doc_room_sync.rs @@ -1035,6 +1035,104 @@ async fn room_hub_awareness_equal_clock_refcount_seed_promotion_and_blob_cors() assert!(obs_awareness.get_payload(shared_cid).is_none()); fresh_obs.close(None).await.unwrap(); + // 2b. Equal-clock live-to-null removal (how `y-protocols` expires a remote peer): an + // already-connected observer must receive it once the LAST owner releases the client. + let expiry_ws_url = format!("ws://{addr}/native-sync/rooms/room-equal-clock-expiry"); + let (mut watcher, _) = connect_async(&expiry_ws_url).await.unwrap(); + let (mut owner_a, _) = connect_async(&expiry_ws_url).await.unwrap(); + let (mut owner_b, _) = connect_async(&expiry_ws_url).await.unwrap(); + + let expiring_cid = (1u64 << 46) + 79; + let mut expiring_sender = RoomAwareness::new(expiring_cid).unwrap(); + let expiring_live = encode_binary_frame(&RoomBinaryFrame::Awareness( + expiring_sender + .set_local_payload(&AwarenessPayload::new("ExpiringPeer", "#ff8a00"), 0) + .unwrap(), + )) + .unwrap(); + let live_clock = expiring_sender + .states() + .get(&expiring_cid) + .expect("local awareness state") + .clock(); + let mut equal_clock_null = y_octo::Awareness::new(0); + equal_clock_null.apply_update(y_octo::AwarenessStates::from([( + expiring_cid, + y_octo::AwarenessState::new(live_clock, "null".to_string()), + )])); + let equal_clock_null_frame = encode_binary_frame(&RoomBinaryFrame::Awareness( + equal_clock_null + .encode_update(Some(&[expiring_cid])) + .unwrap(), + )) + .unwrap(); + + owner_a + .send(WsMsg::Binary(expiring_live.clone().into())) + .await + .unwrap(); + owner_b + .send(WsMsg::Binary(expiring_live.into())) + .await + .unwrap(); + + let mut watcher_awareness = RoomAwareness::new((1u64 << 46) + 80).unwrap(); + let live_seen = tokio::time::timeout(std::time::Duration::from_secs(2), watcher.next()) + .await + .expect("connected observer should receive the live awareness broadcast") + .unwrap() + .unwrap(); + if let WsMsg::Binary(b) = live_seen + && let RoomBinaryFrame::Awareness(payload) = decode_binary_frame(&b).unwrap() + { + watcher_awareness.apply_update(&payload, 10).unwrap(); + } + assert_eq!( + watcher_awareness + .get_payload(expiring_cid) + .map(|p| p.user.name), + Some("ExpiringPeer".to_string()) + ); + + // First owner releases at the same clock: owner_b still holds the client, nothing is sent. + owner_a + .send(WsMsg::Binary(equal_clock_null_frame.clone().into())) + .await + .unwrap(); + assert!( + tokio::time::timeout(std::time::Duration::from_millis(120), watcher.next()) + .await + .is_err(), + "equal-clock removal must stay local while another owner keeps the client alive" + ); + + // Last owner releases at the same clock: the connected observer must be told. + owner_b + .send(WsMsg::Binary(equal_clock_null_frame.into())) + .await + .unwrap(); + let removal_seen = tokio::time::timeout(std::time::Duration::from_secs(2), watcher.next()) + .await + .expect("connected observer should receive the equal-clock live-to-null removal") + .unwrap() + .unwrap(); + let WsMsg::Binary(removal_bytes) = removal_seen else { + panic!("unexpected removal frame: {removal_seen:?}"); + }; + let RoomBinaryFrame::Awareness(removal_payload) = decode_binary_frame(&removal_bytes).unwrap() + else { + panic!("expected an awareness frame for the equal-clock removal"); + }; + let removal_event = watcher_awareness + .apply_update(&removal_payload, 20) + .unwrap(); + assert_eq!(removal_event.removed(), &[expiring_cid]); + assert!(watcher_awareness.get_payload(expiring_cid).is_none()); + + watcher.close(None).await.unwrap(); + owner_a.close(None).await.unwrap(); + owner_b.close(None).await.unwrap(); + // 3. Seed CAS FIFO waiter promotion on partial-seed disconnect. let seed_ws_url = format!("ws://{addr}/native-sync/rooms/room-seed-promote"); let (mut s1, _) = connect_async(&seed_ws_url).await.unwrap(); diff --git a/blocksuite/native-playground/crates/doc/tests/page_snapshot.rs b/blocksuite/native-playground/crates/doc/tests/page_snapshot.rs new file mode 100644 index 0000000000..964266f00f --- /dev/null +++ b/blocksuite/native-playground/crates/doc/tests/page_snapshot.rs @@ -0,0 +1,568 @@ +#![forbid(unsafe_code)] + +use blocksuite_playground_doc::{ + client_id_from_seed, + read::{BlockContent, BlockNode, NoteDisplayMode, PageSnapshot, TextAlign}, + schema::{BlockSpec, ListType, ParagraphType}, + session::PageDocSession, +}; +use y_octo::{Any, SessionValue, TextAttributes, TextDeltaOp, TextInsert}; + +fn paragraph(kind: ParagraphType, text: &str) -> BlockSpec { + BlockSpec::Paragraph { + paragraph_type: kind, + text: text.to_string(), + } +} + +fn list(kind: ListType, text: &str, checked: bool, order: Option) -> BlockSpec { + BlockSpec::List { + list_type: kind, + text: text.to_string(), + checked, + order, + } +} + +fn seeded_page() -> PageDocSession { + let mut page = PageDocSession::new("doc:snapshot", client_id_from_seed(7)).unwrap(); + let mut now = 1_000_u64; + let mut add = |page: &mut PageDocSession, id: &str, spec: BlockSpec, parent: Option<&str>| { + now += 10; + page.add_block(id, spec, parent, None, now).unwrap(); + }; + + add( + &mut page, + "page", + BlockSpec::Page { + title: "Snapshot Title".to_string(), + }, + None, + ); + add(&mut page, "surface", BlockSpec::Surface, Some("page")); + add( + &mut page, + "note", + BlockSpec::Note { xywh: None }, + Some("page"), + ); + add( + &mut page, + "h1", + paragraph(ParagraphType::H1, "Heading"), + Some("note"), + ); + add( + &mut page, + "rich", + paragraph(ParagraphType::Text, "plain bold code"), + Some("note"), + ); + add( + &mut page, + "quote", + paragraph(ParagraphType::Quote, "Quoted"), + Some("note"), + ); + add( + &mut page, + "n1", + list(ListType::Numbered, "one", false, None), + Some("note"), + ); + add( + &mut page, + "n2", + list(ListType::Numbered, "two", false, None), + Some("note"), + ); + add( + &mut page, + "n2-a", + list(ListType::Numbered, "nested one", false, None), + Some("n2"), + ); + add( + &mut page, + "n2-b", + list(ListType::Numbered, "nested two", false, None), + Some("n2"), + ); + add( + &mut page, + "bullet", + list(ListType::Bulleted, "break", false, None), + Some("note"), + ); + add( + &mut page, + "n3", + list(ListType::Numbered, "restarted", false, None), + Some("note"), + ); + add( + &mut page, + "n4", + list(ListType::Numbered, "explicit", false, Some(7)), + Some("note"), + ); + add( + &mut page, + "n5", + list(ListType::Numbered, "after explicit", false, None), + Some("note"), + ); + add( + &mut page, + "todo", + list(ListType::Todo, "done", true, None), + Some("note"), + ); + add( + &mut page, + "toggle", + list(ListType::Toggle, "folded", false, None), + Some("note"), + ); + add( + &mut page, + "toggle-child", + paragraph(ParagraphType::Text, "hidden child"), + Some("toggle"), + ); + add(&mut page, "divider", BlockSpec::Divider, Some("note")); + add( + &mut page, + "code", + BlockSpec::Code { + text: "fn main() {}\n".to_string(), + language: Some("rust".to_string()), + caption: "Listing".to_string(), + }, + Some("note"), + ); + add( + &mut page, + "image", + BlockSpec::Image { + source_id: "blob-1".to_string(), + caption: "Figure".to_string(), + width: 320.0, + height: 200.0, + xywh: None, + }, + Some("note"), + ); + add( + &mut page, + "bookmark", + BlockSpec::Bookmark { + url: "https://affine.pro".to_string(), + title: Some("AFFiNE".to_string()), + description: None, + }, + Some("note"), + ); + add( + &mut page, + "edgeless-note", + BlockSpec::Note { + xywh: Some("[900,0,400,200]".to_string()), + }, + Some("page"), + ); + add( + &mut page, + "frame", + BlockSpec::Frame { + title: "Frame".to_string(), + xywh: None, + presentation_index: None, + }, + Some("page"), + ); + add( + &mut page, + "edgeless-text", + BlockSpec::EdgelessText { xywh: None }, + Some("page"), + ); + + page.set_block_prop( + "edgeless-note", + "prop:displayMode", + SessionValue::Any(Any::String("edgeless".to_string())), + 2_000, + ) + .unwrap(); + page.set_block_prop( + "toggle", + "prop:collapsed", + SessionValue::Any(Any::True), + 2_010, + ) + .unwrap(); + + let mut bold = TextAttributes::new(); + bold.insert("bold".to_string(), Any::True); + page.format_text("rich", "prop:text", 6, 4, bold, 2_020) + .unwrap(); + let mut code = TextAttributes::new(); + code.insert("code".to_string(), Any::True); + page.format_text("rich", "prop:text", 11, 4, code, 2_030) + .unwrap(); + + page.add_raw_block( + "database", + "affine:database", + 3, + vec![ + ( + "prop:title".to_string(), + SessionValue::Text(vec![TextDeltaOp::Insert { + insert: TextInsert::Text("Tasks".to_string()), + format: None, + }]), + ), + ("prop:views".to_string(), SessionValue::Array(Vec::new())), + ], + Some("note"), + None, + 2_040, + ) + .unwrap(); + page.add_raw_block( + "orphan", + "affine:paragraph", + 1, + vec![( + "prop:type".to_string(), + SessionValue::Any(Any::String("text".to_string())), + )], + None, + None, + 2_050, + ) + .unwrap(); + page +} + +fn child<'a>(node: &'a BlockNode, id: &str) -> &'a BlockNode { + node.children + .iter() + .find(|child| child.id == id) + .unwrap_or_else(|| panic!("missing child {id} under {}", node.id)) +} + +fn numbered_index(snapshot: &PageSnapshot, id: &str) -> Option { + match &snapshot.block(id).expect("block").content { + BlockContent::List { numbered_index, .. } => *numbered_index, + other => panic!("{id} is not a list: {other:?}"), + } +} + +#[test] +fn page_snapshot_reads_ordered_typed_tree_without_losing_properties() { + let page = seeded_page(); + let snapshot = page.read_page_snapshot().unwrap(); + + assert_eq!(snapshot.doc_id, "doc:snapshot"); + assert_eq!(snapshot.title(), "Snapshot Title"); + let root = snapshot.root.as_ref().expect("affine:page root"); + assert_eq!(root.flavour, "affine:page"); + assert_eq!(root.version, Some(2)); + assert_eq!( + root.children + .iter() + .map(|c| c.id.as_str()) + .collect::>(), + ["surface", "note", "edgeless-note", "frame", "edgeless-text"] + ); + + // Edgeless-only blocks stay in the tree but are flagged for Page mode to skip. + assert!(child(root, "surface").is_edgeless_only()); + assert!(child(root, "frame").is_edgeless_only()); + assert!(child(root, "edgeless-text").is_edgeless_only()); + assert!(child(root, "edgeless-note").is_edgeless_only()); + let note = child(root, "note"); + assert!(!note.is_edgeless_only()); + match ¬e.content { + BlockContent::Note { + display_mode, + xywh, + hidden, + background, + } => { + assert_eq!(*display_mode, NoteDisplayMode::Both); + assert_eq!(xywh, "[0,0,498,92]"); + assert!(!hidden); + assert_eq!(background["light"], "#ffffff"); + assert_eq!(background["dark"], "#252525"); + } + other => panic!("unexpected note content: {other:?}"), + } + + assert_eq!( + note.children + .iter() + .map(|c| c.id.as_str()) + .collect::>(), + [ + "h1", "rich", "quote", "n1", "n2", "bullet", "n3", "n4", "n5", "todo", "toggle", + "divider", "code", "image", "bookmark", "database", + ] + ); + + assert!(matches!( + &child(note, "h1").content, + BlockContent::Paragraph { kind: ParagraphType::H1, text, collapsed: false, text_align: None } + if text.plain == "Heading" + )); + assert!(matches!( + &child(note, "quote").content, + BlockContent::Paragraph { + kind: ParagraphType::Quote, + .. + } + )); + + // Inline marks arrive as a coalesced insert-only delta next to the plain string. + let BlockContent::Paragraph { text, .. } = &child(note, "rich").content else { + panic!("rich paragraph expected"); + }; + assert_eq!(text.plain, "plain bold code"); + let spans: Vec<(String, Vec)> = text + .delta + .iter() + .map(|op| match op { + TextDeltaOp::Insert { + insert: TextInsert::Text(s), + format, + } => ( + s.clone(), + format + .as_ref() + .map(|attrs| attrs.keys().cloned().collect()) + .unwrap_or_default(), + ), + other => panic!("unexpected delta op: {other:?}"), + }) + .collect(); + assert_eq!( + spans, + [ + ("plain ".to_string(), vec![]), + ("bold".to_string(), vec!["bold".to_string()]), + (" ".to_string(), vec![]), + ("code".to_string(), vec!["code".to_string()]), + ] + ); + + // Numbered runs: consecutive siblings count up, another block breaks the run, + // an explicit `prop:order` restarts it, and nested lists number independently. + assert_eq!(numbered_index(&snapshot, "n1"), Some(1)); + assert_eq!(numbered_index(&snapshot, "n2"), Some(2)); + assert_eq!(numbered_index(&snapshot, "n2-a"), Some(1)); + assert_eq!(numbered_index(&snapshot, "n2-b"), Some(2)); + assert_eq!(numbered_index(&snapshot, "bullet"), None); + assert_eq!(numbered_index(&snapshot, "n3"), Some(1)); + assert_eq!(numbered_index(&snapshot, "n4"), Some(7)); + assert_eq!(numbered_index(&snapshot, "n5"), Some(8)); + + assert!(matches!( + &child(note, "todo").content, + BlockContent::List { + kind: ListType::Todo, + checked: true, + .. + } + )); + let toggle = child(note, "toggle"); + assert!(matches!( + &toggle.content, + BlockContent::List { + kind: ListType::Toggle, + collapsed: true, + .. + } + )); + assert_eq!(toggle.children.len(), 1, "collapsed children stay readable"); + + assert_eq!(child(note, "divider").content, BlockContent::Divider); + assert_eq!( + child(note, "code").content, + BlockContent::Code { + language: "rust".to_string(), + wrap: false, + text: "fn main() {}\n".to_string(), + caption: "Listing".to_string(), + } + ); + assert_eq!( + child(note, "image").content, + BlockContent::Image { + source_id: "blob-1".to_string(), + width: Some(320.0), + height: Some(200.0), + caption: "Figure".to_string(), + } + ); + assert_eq!( + child(note, "bookmark").content, + BlockContent::Bookmark { + url: "https://affine.pro".to_string(), + title: Some("AFFiNE".to_string()), + description: None, + caption: String::new(), + } + ); + + // Unknown flavours keep identity, version, children and property keys. + let database = child(note, "database"); + let BlockContent::Unknown(unknown) = &database.content else { + panic!("affine:database must read as Unknown"); + }; + assert_eq!(unknown.id, "database"); + assert_eq!(unknown.flavour, "affine:database"); + assert_eq!(unknown.version, Some(3)); + assert_eq!(unknown.prop_keys, ["prop:title", "prop:views"]); + assert_eq!(database.props["prop:title"][0]["insert"], "Tasks"); + + // Every `prop:*` of every block survives, identical to the normalized doc export. + let exported = page.export_doc_json().unwrap(); + let exported_blocks = exported["blocks"].as_object().unwrap(); + assert_eq!(snapshot.block_count(), exported_blocks.len()); + for (id, exported_block) in exported_blocks { + let node = snapshot + .block(id) + .unwrap_or_else(|| panic!("block {id} missing")); + let exported_props: Vec<(&String, &serde_json::Value)> = exported_block + .as_object() + .unwrap() + .iter() + .filter(|(key, _)| key.starts_with("prop:")) + .collect(); + assert_eq!(node.props.len(), exported_props.len(), "props of {id}"); + for (key, value) in exported_props { + assert_eq!(&node.props[key], value, "{id}.{key}"); + } + } + + // Blocks outside the root tree are reported instead of being dropped. + assert_eq!( + snapshot + .detached + .iter() + .map(|n| n.id.as_str()) + .collect::>(), + ["orphan"] + ); +} + +#[test] +fn note_display_mode_and_text_align_use_blocksuite_wire_values() { + fn set(page: &mut PageDocSession, id: &str, key: &str, value: &str, now: u64) { + page.set_block_prop( + id, + key, + SessionValue::Any(Any::String(value.to_string())), + now, + ) + .unwrap(); + } + let mut page = seeded_page(); + set(&mut page, "h1", "prop:textAlign", "right", 3_000); + set(&mut page, "n1", "prop:textAlign", "center", 3_010); + set(&mut page, "quote", "prop:textAlign", "justify", 3_020); + + // BlockSuite writes `"doc"` for a note shown only in Page mode; `"page"` reads the same. + for (step, wire) in ["doc", "page"].into_iter().enumerate() { + set( + &mut page, + "note", + "prop:displayMode", + wire, + 3_100 + step as u64, + ); + let snapshot = page.read_page_snapshot().unwrap(); + let note = snapshot.block("note").unwrap(); + let BlockContent::Note { display_mode, .. } = ¬e.content else { + panic!("unexpected note content: {:?}", note.content); + }; + assert_eq!(*display_mode, NoteDisplayMode::DocOnly, "{wire}"); + assert_eq!(display_mode.as_str(), "doc"); + assert!(!note.is_edgeless_only(), "{wire}"); + } + + let snapshot = page.read_page_snapshot().unwrap(); + let align = |id: &str| match &snapshot.block(id).unwrap().content { + BlockContent::Paragraph { text_align, .. } | BlockContent::List { text_align, .. } => { + *text_align + } + other => panic!("unexpected content of {id}: {other:?}"), + }; + assert_eq!(align("h1"), Some(TextAlign::Right)); + assert_eq!(align("n1"), Some(TextAlign::Center)); + assert_eq!(align("n2"), None); + // Only `left`, `center` and `right` are alignments. + assert_eq!(align("quote"), None); + assert_eq!( + snapshot.block("h1").unwrap().props["prop:textAlign"], + "right" + ); + for value in [TextAlign::Left, TextAlign::Center, TextAlign::Right] { + assert_eq!(TextAlign::parse(value.as_str()), Some(value)); + } +} + +#[test] +fn page_snapshot_is_deterministic_and_survives_cycles_and_missing_children() { + let page = seeded_page(); + assert_eq!( + page.read_page_snapshot().unwrap(), + page.read_page_snapshot().unwrap() + ); + + // A replica that applied the same update reads the identical snapshot. + let mut replica = PageDocSession::new("doc:snapshot", client_id_from_seed(8)).unwrap(); + replica + .apply_remote_update_v1(&page.encode_update_v1().unwrap()) + .unwrap(); + assert_eq!( + replica.read_page_snapshot().unwrap(), + page.read_page_snapshot().unwrap() + ); + + let mut empty = PageDocSession::new("doc:empty", client_id_from_seed(9)).unwrap(); + let snapshot = empty.read_page_snapshot().unwrap(); + assert!(snapshot.root.is_none()); + assert!(snapshot.detached.is_empty()); + assert_eq!(snapshot.title(), ""); + + // `a` and `b` reference each other and a block that does not exist. + for (id, other) in [("a", "b"), ("b", "a")] { + empty + .add_raw_block(id, "affine:paragraph", 1, Vec::new(), None, None, 10) + .unwrap(); + let children = + y_octo::TypeTarget::Path(y_octo::TypePath::root("blocks").key(id).key("sys:children")); + empty + .inner_mut() + .array_push( + &children, + vec![ + SessionValue::Any(Any::String(other.to_string())), + SessionValue::Any(Any::String("ghost".to_string())), + ], + ) + .unwrap(); + } + let snapshot = empty.read_page_snapshot().unwrap(); + assert!(snapshot.root.is_none()); + assert_eq!(snapshot.block_count(), 2); + assert_eq!(snapshot.detached.len(), 1); + assert_eq!(snapshot.detached[0].id, "a"); + assert_eq!(snapshot.detached[0].children[0].id, "b"); + assert!(snapshot.detached[0].children[0].children.is_empty()); +} diff --git a/blocksuite/native-playground/crates/playground/Cargo.toml b/blocksuite/native-playground/crates/playground/Cargo.toml index ae13958d28..06ed5a2be1 100644 --- a/blocksuite/native-playground/crates/playground/Cargo.toml +++ b/blocksuite/native-playground/crates/playground/Cargo.toml @@ -26,6 +26,7 @@ required-features = ["harness"] [dependencies] anyhow.workspace = true +async-channel.workspace = true blocksuite-playground-doc = { path = "../doc", default-features = false } image.workspace = true serde.workspace = true @@ -40,7 +41,31 @@ y-octo = { version = "0.3.0", default-features = false, features = ["session"] } tempfile = "3" ui = { path = "../ui", features = ["harness"] } +[target.'cfg(not(target_family = "wasm"))'.dependencies] +futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] } +tokio = { version = "1", features = ["io-util", "macros", "net", "rt", "sync", "time"] } +tokio-tungstenite = "0.26" + +[target.'cfg(not(target_family = "wasm"))'.dev-dependencies] +axum = { version = "0.8", features = ["ws"] } +blocksuite-playground-doc = { path = "../doc", features = ["server"] } +tokio = { version = "1", features = ["io-util", "macros", "net", "rt-multi-thread", "sync", "time"] } + [target.'cfg(target_family = "wasm")'.dependencies] console_error_panic_hook.workspace = true +js-sys.workspace = true wasm-bindgen.workspace = true -web-sys = { workspace = true, features = ["Document", "Element", "HtmlCanvasElement", "Window"] } +wasm-bindgen-futures.workspace = true +web-sys = { workspace = true, features = [ + "BinaryType", + "CloseEvent", + "Document", + "Element", + "HtmlCanvasElement", + "Location", + "MessageEvent", + "Response", + "UrlSearchParams", + "WebSocket", + "Window", +] } diff --git a/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs b/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs index 2a5fecf682..96e133bbe9 100644 --- a/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs +++ b/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs @@ -5,7 +5,9 @@ use blocksuite_playground_doc::{ session::PageDocSession, wire::{DocMessage, RoomBinaryFrame, decode_binary_frame, encode_binary_frame}, }; -use playground::{PlaygroundView, register_bundled_fonts}; +use playground::{ + PlaygroundMode, PlaygroundOptions, PlaygroundTheme, PlaygroundView, register_bundled_fonts, +}; use serde::Serialize; use std::cell::RefCell; use std::path::PathBuf; @@ -76,7 +78,11 @@ struct HeadlessSession { headless_win: HeadlessWindow, } -fn start_headless_session(width: u32, height: u32) -> Result { +fn start_headless_session( + width: u32, + height: u32, + options: PlaygroundOptions, +) -> Result { let platform = HeadlessPlatform::new(width, height, 1.0); let init_cell: Rc>>>> = Rc::new(RefCell::new(None)); @@ -84,7 +90,7 @@ fn start_headless_session(width: u32, height: u32) -> Result { let app = Application::with_platform(platform.clone()).run_embedded(move |cx| { let res = (|| -> Result> { - register_bundled_fonts(cx).context("registering bundled Inter font")?; + register_bundled_fonts(cx).context("registering bundled fonts")?; cx.open_window( WindowOptions { window_bounds: Some(WindowBounds::Windowed(Bounds::new( @@ -93,7 +99,7 @@ fn start_headless_session(width: u32, height: u32) -> Result { ))), ..WindowOptions::default() }, - |_, cx| cx.new(PlaygroundView::new), + |_, cx| cx.new(|cx| PlaygroundView::with_options(options, cx)), ) .context("opening headless PlaygroundView window") })(); @@ -124,8 +130,11 @@ fn render_headless( out_png: PathBuf, out_snapshot: PathBuf, click_edgeless: bool, + options: PlaygroundOptions, ) -> Result<()> { - let session = start_headless_session(width, height)?; + let theme = options.theme; + let mode = options.mode; + let session = start_headless_session(width, height, options)?; session.headless_win.request_frame(); if click_edgeless { @@ -159,7 +168,7 @@ fn render_headless( anyhow::ensure!( glyph_count > 0, - "headless render produced 0 text glyphs; check bundled Inter font registration" + "headless render produced 0 text glyphs; check bundled font registration" ); if let Some(parent) = out_png.parent() { @@ -180,12 +189,18 @@ fn render_headless( std::fs::write(&out_snapshot, snapshot_json) .with_context(|| format!("writing snapshot to {}", out_snapshot.display()))?; + let shown_mode = if click_edgeless || mode == PlaygroundMode::Edgeless { + "edgeless" + } else { + "page" + }; println!( - "Rendered {}x{} headless PNG ({} glyphs{}) to {} and snapshot ({} elements) to {}", + "Rendered {}x{} headless PNG ({} glyphs, {} {}) to {} and snapshot ({} elements) to {}", width, height, glyph_count, - if click_edgeless { ", edgeless" } else { "" }, + shown_mode, + theme.as_str(), out_png.display(), snapshot.elements.len(), out_snapshot.display() @@ -327,7 +342,7 @@ fn run_fps_check() -> Result<()> { let dt_nanos = (1_000_000_000_u64 + u64::from(fps) / 2) / u64::from(fps); let dt = Duration::from_nanos(dt_nanos); - let session = start_headless_session(1280, 800)?; + let session = start_headless_session(1280, 800, PlaygroundOptions::default())?; session.headless_win.request_frame(); let (page_x, edgeless_x, click_pt) = session.app.update(|cx| { @@ -679,7 +694,7 @@ fn run_bench( let commit = resolve_commit_sha(explicit_commit.as_deref())?; let doc_1k_edits_ms = bench_doc_1k_edits_ms()?; let room_sync_1k_ops_ms = bench_room_sync_1k_ops_ms()?; - let session = start_headless_session(1280, 800)?; + let session = start_headless_session(1280, 800, PlaygroundOptions::default())?; // 1 warmup frame outside timing loop session.headless_win.request_frame(); @@ -760,6 +775,7 @@ fn main() -> Result<()> { let mut width = 1280_u32; let mut height = 800_u32; let mut click_edgeless = false; + let mut options = PlaygroundOptions::default(); while let Some(arg) = args.next() { match arg.as_str() { "--out" => out_png = PathBuf::from(args.next().context("--out requires path")?), @@ -772,10 +788,27 @@ fn main() -> Result<()> { height = args.next().context("--height requires value")?.parse()? } "--click-edgeless" => click_edgeless = true, + "--theme" => { + let value = args.next().context("--theme requires light|dark")?; + options.theme = PlaygroundTheme::parse(&value) + .with_context(|| format!("unknown theme {value:?} (light|dark)"))?; + } + "--mode" => { + let value = args.next().context("--mode requires page|edgeless")?; + options.mode = PlaygroundMode::parse(&value) + .with_context(|| format!("unknown mode {value:?} (page|edgeless)"))?; + } other => bail!("unknown render flag: {other}"), } } - render_headless(width, height, out_png, out_snapshot, click_edgeless) + render_headless( + width, + height, + out_png, + out_snapshot, + click_edgeless, + options, + ) } "render-rich-sample" => render_rich_sample(args), "audit" => { diff --git a/blocksuite/native-playground/crates/playground/src/block_flow.rs b/blocksuite/native-playground/crates/playground/src/block_flow.rs new file mode 100644 index 0000000000..7f66c70940 --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/block_flow.rs @@ -0,0 +1,2304 @@ +//! World-space page flow. +//! +//! [`BlockFlow`] lays a [`PageSnapshot`] out in document coordinates: the origin is the +//! top-left corner of the page column and `y` grows down the document, independent of the +//! window and of scrolling. A [`PageViewport`] then maps that world space onto the screen +//! (`screen = viewport origin + world - scroll`), and only the blocks intersecting the +//! viewport become elements. +//! +//! Block metrics follow BlockSuite's page styles as recorded in `tokens/style-oracle.json`: +//! sibling margins collapse the way CSS block margins do, list prefixes sit on the first +//! line, and nested children indent by [`CHILD_INDENT`]. Paragraph and list text is laid +//! out and painted by [`RichParagraph`]; single-style labels use the plain [`InlineLayout`]. + +use std::{ + collections::{BTreeMap, HashMap}, + hash::{Hash, Hasher}, + rc::Rc, + sync::Arc, +}; + +use blocksuite_playground_doc::{ + read::{BlockContent, BlockNode, PageSnapshot, RichText, TextAlign as BlockAlign}, + schema::{ListType, ParagraphType}, +}; +use ui::{ + AnyElement, App, BorderStyle, Bounds, Corners, Edges, Font, FontWeight, Hsla, Pixels, Point, + RenderImage, ShapedLine, SharedString, TextAlign, TextRun, Window, canvas, div, point, + prelude::*, px, size, +}; + +use crate::{ + rich_text::{ + CaretPosition, LaidOutRichParagraph, RichParagraph, RichParagraphStyle, WrapAffinity, + }, + theme::{FONT_CODE, FONT_SANS, IconPaint, Palette, PlaygroundTheme, TYPOGRAPHY}, +}; + +/// `--affine-editor-width`: maximum width of the page container. +pub const EDITOR_WIDTH: f32 = TYPOGRAPHY.editor_width_px; +/// Side padding of the page container on regular viewports. +pub const SIDE_PADDING: f32 = 96.0; +/// Side padding of the page container on viewports up to [`NARROW_VIEWPORT`] wide. +pub const SIDE_PADDING_NARROW: f32 = 24.0; +/// Viewport width at or below which the narrow side padding applies. +pub const NARROW_VIEWPORT: f32 = 640.0; +/// Vertical padding above and below the page title. +pub const TITLE_PADDING_Y: f32 = 38.0; +/// Padding below the last block of the page. +pub const BOTTOM_PADDING: f32 = 32.0; +/// Left indent of a block's children. +pub const CHILD_INDENT: f32 = 24.0; +/// Width reserved for a list prefix; the list text starts here. +pub const LIST_PREFIX_WIDTH: f32 = 24.0; +/// Vertical margin of paragraph and list blocks. +pub const TEXT_BLOCK_MARGIN: f32 = 10.0; +/// Vertical margin of code, image, bookmark and card blocks. +pub const CARD_BLOCK_MARGIN: f32 = 18.0; +/// Height of a horizontal bookmark card. +pub const BOOKMARK_HEIGHT: f32 = 116.0; +/// Height of the divider block container. +pub const DIVIDER_HEIGHT: f32 = 36.0; +/// Vertical and horizontal padding of the code block container. +pub const CODE_PADDING: (f32, f32) = (32.0, 20.0); +/// Corner radius of the code block container. +pub const CODE_RADIUS: f32 = 10.0; +/// Width of the code line-number column, including its gap to the code. +pub const CODE_GUTTER: f32 = 32.0; + +const COLLAPSED_MARKER_SIZE: f32 = 16.0; +const PRESENCE_LABEL_HEIGHT: f32 = 18.0; + +/// Typography and vertical margins of a text block. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TextSpec { + pub font_size: f32, + pub font_weight: f32, + pub line_height: f32, + /// Distance from the top of a line to the alphabetic baseline, as the browser places it. + pub baseline: f32, + /// Tracking in pixels (`letter-spacing`). + pub letter_spacing: f32, + pub margin_top: f32, + pub margin_bottom: f32, +} + +/// Page title typography (`.doc-title-container`). +pub const TITLE_SPEC: TextSpec = TextSpec { + font_size: 40.0, + font_weight: 700.0, + line_height: 50.0, + baseline: 40.0, + letter_spacing: 0.0, + margin_top: TITLE_PADDING_Y, + margin_bottom: TITLE_PADDING_Y, +}; + +/// Typography of an `affine:paragraph` by type. Margins are the block's effective margins: +/// the 10px block container margin collapsed with the heading wrapper's own margin. +pub fn paragraph_spec(kind: ParagraphType) -> TextSpec { + // (font size, weight, line height, baseline, letter spacing, wrapper margin top) + let (font_size, font_weight, line_height, baseline, letter_spacing, margin_top) = match kind { + ParagraphType::Text => ( + TYPOGRAPHY.font_base_px, + 400.0, + TYPOGRAPHY.line_height_base_px, + 17.0, + 0.0, + 0.0, + ), + ParagraphType::H1 => (TYPOGRAPHY.font_h1_px, 700.0, 36.0, 29.0, -0.56, 18.0), + ParagraphType::H2 => (TYPOGRAPHY.font_h2_px, 600.0, 36.0, 28.0, -0.52, 14.0), + ParagraphType::H3 => (TYPOGRAPHY.font_h3_px, 600.0, 32.0, 25.0, -0.48, 12.0), + ParagraphType::H4 => (TYPOGRAPHY.font_h4_px, 600.0, 30.0, 24.0, -0.33, 12.0), + ParagraphType::H5 => (TYPOGRAPHY.font_h5_px, 600.0, 28.0, 21.0, -0.30, 12.0), + ParagraphType::H6 => (TYPOGRAPHY.font_h6_px, 600.0, 26.0, 20.0, -0.27, 12.0), + ParagraphType::Quote => ( + TYPOGRAPHY.font_base_px, + 400.0, + 26.0, + 19.0, + 0.0, + TYPOGRAPHY.paragraph_space_px, + ), + }; + TextSpec { + font_size, + font_weight, + line_height, + baseline, + letter_spacing, + margin_top: margin_top.max(TEXT_BLOCK_MARGIN), + margin_bottom: TEXT_BLOCK_MARGIN, + } +} + +/// Padding (`left`, `top`, `bottom`) of a quote paragraph around its text. +pub const QUOTE_PADDING: (f32, f32, f32) = (17.0, 10.0, 10.0); +/// Width of the quote accent bar. +pub const QUOTE_BAR_WIDTH: f32 = 2.0; + +/// Ordered-list prefix for a 1-based `index` at list nesting `depth`: numbers, then +/// letters, then roman numerals, repeating every three levels. +pub fn number_prefix(index: u32, depth: usize) -> String { + let index = index.max(1); + let body = match depth % 3 { + 0 => index.to_string(), + 1 => { + let mut n = i64::from(index) - 1; + let mut letters = Vec::new(); + while n >= 0 { + letters.push(b'a' + (n % 26) as u8); + n = n / 26 - 1; + } + letters.reverse(); + String::from_utf8(letters).unwrap_or_default() + } + _ => { + const ROMAN: [(u32, &str); 13] = [ + (1000, "M"), + (900, "CM"), + (500, "D"), + (400, "CD"), + (100, "C"), + (90, "XC"), + (50, "L"), + (40, "XL"), + (10, "X"), + (9, "IX"), + (5, "V"), + (4, "IV"), + (1, "I"), + ]; + let mut rest = index; + let mut roman = String::new(); + for (value, symbol) in ROMAN { + while rest >= value { + roman.push_str(symbol); + rest -= value; + } + } + roman + } + }; + format!("{body}.") +} + +/// Horizontal placement of the page container and its content column in the window. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PageGeometry { + pub viewport_width: f32, + pub side_padding: f32, + /// Screen x of the content column's left edge. + pub column_x: f32, + /// Width of the content column (the world-space width of the flow). + pub column_width: f32, +} + +/// Resolve the page container for a viewport width: at most [`EDITOR_WIDTH`] wide, +/// centered, with side padding that narrows on small viewports. +pub fn page_geometry(viewport_width: f32) -> PageGeometry { + let viewport_width = viewport_width.max(0.0).floor(); + let container_width = viewport_width.min(EDITOR_WIDTH); + let side_padding = if viewport_width <= NARROW_VIEWPORT { + SIDE_PADDING_NARROW + } else { + SIDE_PADDING + }; + let column_width = (container_width - 2.0 * side_padding).max(0.0); + let container_x = ((viewport_width - container_width) / 2.0).floor(); + PageGeometry { + viewport_width, + side_padding, + column_x: container_x + side_padding, + column_width, + } +} + +/// Axis-aligned rectangle in flow units (logical pixels). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct FlowRect { + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, +} + +impl FlowRect { + pub const fn new(x: f32, y: f32, w: f32, h: f32) -> Self { + Self { x, y, w, h } + } + + pub fn right(&self) -> f32 { + self.x + self.w + } + + pub fn bottom(&self) -> f32 { + self.y + self.h + } + + fn bounds(&self, origin: Point) -> Bounds { + Bounds::new( + point(origin.x + px(self.x), origin.y + px(self.y)), + size(px(self.w), px(self.h)), + ) + } +} + +/// Style of a plain, single-style run of text. +#[derive(Clone, Debug, PartialEq)] +pub struct InlineStyle { + pub family: &'static str, + pub size: f32, + pub weight: f32, + pub color: Hsla, +} + +impl InlineStyle { + pub fn new(family: &'static str, size: f32, weight: f32, color: Hsla) -> Self { + Self { + family, + size, + weight, + color, + } + } + + fn font(&self) -> Font { + let mut font = ui::font(self.family); + font.weight = FontWeight(self.weight); + font + } +} + +/// Horizontal alignment of inline lines inside their box. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum InlineAlign { + Left, + Center, + Right, +} + +struct InlinePiece { + line: usize, + x: f32, + visible_width: f32, + baseline_shift: f32, + shaped: ShapedLine, + /// Position of the piece in the text, in UTF-16 code units. + source_start: usize, + source_len: usize, +} + +impl InlinePiece { + fn source_end(&self) -> usize { + self.source_start + self.source_len + } + + /// X of a UTF-16 offset inside this piece, relative to the inline box. + fn x_at(&self, source_offset: usize) -> f32 { + if source_offset <= self.source_start { + return self.x; + } + if source_offset >= self.source_end() { + return self.x + self.visible_width; + } + let mut units = 0; + let mut byte = self.shaped.text.len(); + for (index, ch) in self.shaped.text.char_indices() { + if units >= source_offset - self.source_start { + byte = index; + break; + } + units += ch.len_utf16(); + } + self.x + f32::from(self.shaped.x_for_index(byte)) + } +} + +/// Laid-out plain text for labels, titles and code: one style, wrapped at spaces (inside +/// a word only when the word alone is wider than the line), on lines of one height. +pub struct InlineLayout { + pieces: Vec, + pub line_count: usize, + pub line_height: f32, + /// Width the content was wrapped to. + pub width: f32, + /// Distance from the top of a line to the baseline. + pub baseline: f32, +} + +impl InlineLayout { + pub fn height(&self) -> f32 { + self.line_count as f32 * self.line_height + } + + /// Width of the widest line's visible content. + pub fn content_width(&self) -> f32 { + self.pieces + .iter() + .map(|piece| piece.x + piece.visible_width) + .fold(0.0, f32::max) + } + + /// Position of a UTF-16 source offset as `(x, line)`. + pub fn caret(&self, source_offset: usize) -> (f32, usize) { + let mut best: Option<&InlinePiece> = None; + for piece in &self.pieces { + if source_offset < piece.source_start { + break; + } + best = Some(piece); + if source_offset < piece.source_end() { + break; + } + } + match best { + Some(piece) => (piece.x_at(source_offset), piece.line), + None => (0.0, 0), + } + } + + /// Per-line `(line, x0, x1)` spans covering the UTF-16 source range `start..end`. + pub fn selection_spans(&self, start: usize, end: usize) -> Vec<(usize, f32, f32)> { + let mut spans: Vec<(usize, f32, f32)> = Vec::new(); + if end <= start { + return spans; + } + for piece in &self.pieces { + if piece.source_end() <= start || piece.source_start >= end { + continue; + } + let x0 = piece.x_at(start.max(piece.source_start)); + let x1 = if end >= piece.source_end() { + piece.x + f32::from(piece.shaped.width()) + } else { + piece.x_at(end) + }; + match spans.last_mut() { + Some((line, _, right)) if *line == piece.line => *right = right.max(x1), + _ => spans.push((piece.line, x0, x1)), + } + } + spans + } + + fn paint(&self, origin: Point, window: &mut Window, cx: &mut App) { + for piece in &self.pieces { + let piece_origin = point( + origin.x + px(piece.x), + origin.y + px(piece.line as f32 * self.line_height + piece.baseline_shift), + ); + let _ = piece.shaped.paint( + piece_origin, + px(self.line_height), + TextAlign::Left, + None, + window, + cx, + ); + } + } +} + +fn baseline_in_line(line_height: f32, shaped: &ShapedLine) -> f32 { + let ascent = f32::from(shaped.ascent); + let descent = f32::from(shaped.descent); + (line_height - ascent - descent) / 2.0 + ascent +} + +fn shape(window: &Window, text: &str, style: &InlineStyle) -> ShapedLine { + let run = TextRun { + len: text.len(), + font: style.font(), + color: style.color, + background_color: None, + underline: None, + strikethrough: None, + }; + window.text_system().shape_line( + SharedString::from(text.to_string()), + px(style.size), + &[run], + None, + ) +} + +/// Split text into words that keep their trailing whitespace; `None` marks a hard break. +fn inline_segments(text: &str) -> Vec> { + let mut segments = Vec::new(); + for (index, line) in text.split('\n').enumerate() { + if index > 0 { + segments.push(None); + } + let mut start = 0; + let mut in_space = false; + for (offset, ch) in line.char_indices() { + let space = ch.is_whitespace(); + if in_space && !space { + segments.push(Some(&line[start..offset])); + start = offset; + } + in_space = space; + } + if start < line.len() { + segments.push(Some(&line[start..])); + } + } + segments +} + +/// Shorten `text` with a trailing ellipsis until it fits `max_width`. +fn truncate_to_width( + window: &Window, + text: &str, + style: &InlineStyle, + max_width: f32, +) -> ShapedLine { + let shaped = shape(window, text, style); + if f32::from(shaped.width()) <= max_width { + return shaped; + } + let mut chars: Vec = text.chars().collect(); + while chars.len() > 1 { + chars.pop(); + let candidate: String = chars.iter().collect::() + "\u{2026}"; + let shaped = shape(window, &candidate, style); + if f32::from(shaped.width()) <= max_width { + return shaped; + } + } + shape(window, "\u{2026}", style) +} + +/// Where the baseline of an [`InlineLayout`] sits inside its lines. +#[derive(Clone, Copy)] +pub enum InlineBaseline<'a> { + /// Centered font metrics of this style, so text of another size or family lines up + /// with text set in it. + Of(&'a InlineStyle), + /// A fixed distance from the top of the line. + At(f32), +} + +/// Wrap `text` to `max_width` on lines of `line_height`. +pub fn layout_inline( + text: &str, + style: &InlineStyle, + max_width: f32, + line_height: f32, + baseline: InlineBaseline<'_>, + align: InlineAlign, + window: &Window, +) -> InlineLayout { + let max_width = max_width.max(1.0); + let baseline = match baseline { + InlineBaseline::Of(base) => baseline_in_line(line_height, &shape(window, "Ag", base)), + InlineBaseline::At(baseline) => baseline, + }; + let mut pieces: Vec = Vec::new(); + let mut line = 0_usize; + let mut x = 0.0_f32; + let mut source_cursor = 0_usize; + + for segment in inline_segments(text) { + let Some(mut rest) = segment else { + line += 1; + x = 0.0; + source_cursor += 1; + continue; + }; + while !rest.is_empty() { + let shaped = shape(window, rest, style); + let trimmed_len = rest.trim_end_matches(char::is_whitespace).len(); + let visible_width = if trimmed_len == rest.len() { + f32::from(shaped.width()) + } else { + f32::from(shaped.x_for_index(trimmed_len)) + }; + + if x > 0.0 && x + visible_width > max_width { + line += 1; + x = 0.0; + continue; + } + + let mut piece_text = rest; + let mut piece_shaped = shaped; + let mut piece_visible = visible_width; + let mut wrapped = false; + if visible_width > max_width && rest.chars().count() > 1 { + // A single word wider than the line: break it at the last glyph that fits. + let mut split = piece_shaped + .index_for_x(px(max_width)) + .unwrap_or(rest.len()); + while split > 0 && !rest.is_char_boundary(split) { + split -= 1; + } + if split == 0 { + split = rest.chars().next().map_or(rest.len(), char::len_utf8); + } + if split < rest.len() { + piece_text = &rest[..split]; + piece_shaped = shape(window, piece_text, style); + piece_visible = f32::from(piece_shaped.width()); + wrapped = true; + } + } + + let source_len = piece_text.encode_utf16().count(); + let advance = f32::from(piece_shaped.width()); + pieces.push(InlinePiece { + line, + x, + visible_width: piece_visible, + baseline_shift: baseline - baseline_in_line(line_height, &piece_shaped), + shaped: piece_shaped, + source_start: source_cursor, + source_len, + }); + source_cursor += source_len; + rest = &rest[piece_text.len()..]; + if wrapped { + line += 1; + x = 0.0; + } else { + x += advance; + } + } + } + + let line_count = line + 1; + if align != InlineAlign::Left { + let mut line_right = vec![0.0_f32; line_count]; + for piece in &pieces { + let right = piece.x + piece.visible_width; + line_right[piece.line] = line_right[piece.line].max(right); + } + for piece in &mut pieces { + let free = (max_width - line_right[piece.line]).max(0.0); + piece.x += match align { + InlineAlign::Center => (free / 2.0).floor(), + _ => free.floor(), + }; + } + } + + InlineLayout { + pieces, + line_count, + line_height, + width: max_width, + baseline, + } +} + +fn paint_quad( + window: &mut Window, + bounds: Bounds, + radius: f32, + fill: Option, + border: Option, + dashed: bool, +) { + window.paint_quad(ui::quad( + bounds, + Corners::all(px(radius)), + fill.unwrap_or_else(ui::transparent_black), + Edges::all(px(if border.is_some() { 1.0 } else { 0.0 })), + border.unwrap_or_else(ui::transparent_black), + if dashed { + BorderStyle::Dashed + } else { + BorderStyle::Solid + }, + )); +} + +/// What an `affine:image` block shows for its blob. +#[derive(Clone)] +pub enum ImageSlot { + /// The blob has not arrived yet. + Loading, + /// The blob cannot be decoded, or has stayed missing for several fetches. + Unavailable, + Ready(Arc), +} + +/// Decode PNG, JPEG, WebP, GIF (first frame) or BMP bytes into a renderable image; any +/// other format is rejected. +pub fn decode_image(bytes: &[u8]) -> Option> { + use image::ImageFormat::{Bmp, Gif, Jpeg, Png, WebP}; + let format = image::guess_format(bytes) + .ok() + .filter(|format| matches!(format, Png | Jpeg | WebP | Gif | Bmp))?; + let mut buffer = image::load_from_memory_with_format(bytes, format) + .ok()? + .into_rgba8(); + if buffer.width() == 0 || buffer.height() == 0 { + return None; + } + // The renderer samples BGRA. + for pixel in buffer.chunks_exact_mut(4) { + pixel.swap(0, 2); + } + Some(Arc::new(RenderImage::new(vec![image::Frame::new(buffer)]))) +} + +/// Paint primitive of a block, positioned relative to the block's own origin. +enum Prim { + Quad { + rect: FlowRect, + fill: Option, + border: Option, + radius: f32, + dashed: bool, + }, + Text { + x: f32, + y: f32, + layout: Rc, + clip: Option, + }, + Rich { + x: f32, + y: f32, + layout: Arc, + }, + Icon { + rect: FlowRect, + icon: IconPaint, + color: Hsla, + }, + Image { + rect: FlowRect, + image: Arc, + }, +} + +/// What a laid-out block is, for tests and snapshot consumers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FlowKind { + Title, + Paragraph(ParagraphType), + List(ListType), + Divider, + Code, + Image, + Bookmark, + Unknown, +} + +/// Laid-out text of a block: rich paragraph text or a plain single-style label. +#[derive(Clone)] +pub enum FlowTextLayout { + Rich(Arc), + Plain(Rc), +} + +impl FlowTextLayout { + pub fn line_height(&self) -> f32 { + match self { + Self::Rich(layout) => f32::from(layout.line_height()), + Self::Plain(layout) => layout.line_height, + } + } + + pub fn line_count(&self) -> usize { + match self { + Self::Rich(layout) => layout.lines().len(), + Self::Plain(layout) => layout.line_count, + } + } + + pub fn height(&self) -> f32 { + self.line_count() as f32 * self.line_height() + } + + /// Width of the widest line. + pub fn content_width(&self) -> f32 { + match self { + Self::Rich(layout) => f32::from(layout.size().width), + Self::Plain(layout) => layout.content_width(), + } + } + + /// Position of a UTF-16 source offset as `(x, line)`. + pub fn caret(&self, source_offset: usize) -> (f32, usize) { + match self { + Self::Rich(layout) => { + let (line, x) = layout.caret_line_and_x(CaretPosition { + utf16_offset: source_offset as u64, + affinity: WrapAffinity::Downstream, + }); + (f32::from(x), line) + } + Self::Plain(layout) => layout.caret(source_offset), + } + } + + /// Per-line `(line, x0, x1)` spans covering the UTF-16 source range `start..end`. + pub fn selection_spans(&self, start: usize, end: usize) -> Vec<(usize, f32, f32)> { + match self { + Self::Rich(layout) => { + let line_height = f32::from(layout.line_height()); + layout + .selection_rects(start as u64, end as u64) + .into_iter() + .map(|rect| { + let x0 = f32::from(rect.origin.x); + ( + (f32::from(rect.origin.y) / line_height).round() as usize, + x0, + x0 + f32::from(rect.size.width), + ) + }) + .collect() + } + Self::Plain(layout) => layout.selection_spans(start, end), + } + } + + fn prim(&self, x: f32, y: f32) -> Prim { + match self { + Self::Rich(layout) => Prim::Rich { + x, + y, + layout: layout.clone(), + }, + Self::Plain(layout) => Prim::Text { + x, + y, + layout: layout.clone(), + clip: None, + }, + } + } +} + +/// Primary text of a block, kept for caret and selection geometry. +pub struct FlowText { + pub x: f32, + pub y: f32, + pub layout: FlowTextLayout, +} + +/// Position-independent layout of one block: size, margins and paint primitives. +pub struct BlockBody { + pub kind: FlowKind, + pub width: f32, + pub height: f32, + pub margin_top: f32, + pub margin_bottom: f32, + /// Plain text recorded on the block's element snapshot. + pub plain: String, + pub text: Option, + /// Box of the list prefix (bullet, number, checkbox or toggle), if the block has one. + pub prefix: Option, + prims: Vec, +} + +impl BlockBody { + fn paint(&self, origin: Point, window: &mut Window, cx: &mut App) { + for prim in &self.prims { + match prim { + Prim::Quad { + rect, + fill, + border, + radius, + dashed, + } => paint_quad( + window, + rect.bounds(origin), + *radius, + *fill, + *border, + *dashed, + ), + Prim::Text { x, y, layout, clip } => { + let text_origin = point(origin.x + px(*x), origin.y + px(*y)); + match clip { + Some(clip) => window.with_content_mask( + Some(ui::ContentMask { + bounds: clip.bounds(origin), + }), + |window| layout.paint(text_origin, window, cx), + ), + None => layout.paint(text_origin, window, cx), + } + } + Prim::Rich { x, y, layout } => layout.paint_at( + point(origin.x + px(*x), origin.y + px(*y)), + &[], + &[], + None, + window, + cx, + ), + Prim::Icon { rect, icon, color } => { + icon.paint(rect.bounds(origin), *color, window, cx); + } + Prim::Image { rect, image } => { + let bounds = rect.bounds(origin); + let _ = window.paint_image( + bounds, + bounds, + Corners::all(px(0.0)), + image.clone(), + 0, + false, + ); + } + } + } + } +} + +/// A block placed in world space. +pub struct FlowBlock { + pub block_id: String, + /// Id of the block's element snapshot (`page.title_block` or `page.block.`). + pub snapshot_id: SharedString, + pub x: f32, + pub y: f32, + pub body: Rc, +} + +impl FlowBlock { + pub fn rect(&self) -> FlowRect { + FlowRect::new(self.x, self.y, self.body.width, self.body.height) + } +} + +/// Everything the layout pass reads besides the window's text system. +pub struct FlowInput<'a> { + pub snapshot: &'a PageSnapshot, + /// Width of the page column, the world-space width of the flow. + pub width: f32, + pub theme: PlaygroundTheme, + /// Titles of the workspace pages by id, for linked-page references. + pub page_titles: &'a BTreeMap, + /// Image blobs by `sourceId`; a missing entry is still loading. + pub images: &'a HashMap, + /// Bumped whenever `page_titles` or `images` change. + pub env_rev: u64, +} + +/// Counters of the latest [`BlockFlow::layout`] pass. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct FlowStats { + /// Blocks whose body was laid out from scratch. + pub laid_out: usize, + /// Blocks whose unchanged body was reused from the previous pass. + pub reused: usize, +} + +/// Result of a layout pass: blocks in document order, in world space. +pub struct FlowLayout { + pub blocks: Vec, + pub width: f32, + pub height: f32, + pub stats: FlowStats, +} + +impl FlowLayout { + pub fn block(&self, block_id: &str) -> Option<&FlowBlock> { + self.blocks.iter().find(|block| block.block_id == block_id) + } +} + +/// World-space page layout with per-block reuse across passes. +#[derive(Default)] +pub struct BlockFlow { + bodies: HashMap)>, +} + +struct FlowPass<'a> { + input: &'a FlowInput<'a>, + palette: Palette, + window: &'a Window, + previous: HashMap)>, + next: HashMap)>, + blocks: Vec, + stats: FlowStats, + y: f32, + /// Bottom margin of the previous sibling, `None` at the start of a flow root. + pending_margin: Option, +} + +impl BlockFlow { + pub fn new() -> Self { + Self::default() + } + + /// Lay the snapshot out in world space, reusing the body of every block whose content, + /// width and theme did not change since the previous pass. + pub fn layout(&mut self, input: &FlowInput<'_>, window: &Window) -> FlowLayout { + let mut pass = FlowPass { + input, + palette: input.theme.palette(), + window, + previous: std::mem::take(&mut self.bodies), + next: HashMap::new(), + blocks: Vec::new(), + stats: FlowStats::default(), + y: 0.0, + pending_margin: None, + }; + + if let Some(root) = &input.snapshot.root { + let title = match &root.content { + BlockContent::Page { title } => title.plain.as_str(), + _ => "", + }; + let body = pass.body("\u{0}title", &("title", title), |pass| { + pass.title_body(title) + }); + pass.y = TITLE_SPEC.margin_top; + pass.blocks.push(FlowBlock { + block_id: root.id.clone(), + snapshot_id: SharedString::from("page.title_block"), + x: 0.0, + y: pass.y, + body: body.clone(), + }); + pass.y += body.height + TITLE_SPEC.margin_bottom; + + for child in &root.children { + if child.is_edgeless_only() { + continue; + } + // Each note is its own flow root: margins never collapse across notes. + pass.pending_margin = None; + match &child.content { + BlockContent::Note { .. } => { + pass.flow(&child.children, 0.0, 0, BlockAlign::Left) + } + _ => pass.flow(std::slice::from_ref(child), 0.0, 0, BlockAlign::Left), + } + pass.y += pass.pending_margin.take().unwrap_or(0.0); + } + pass.y += BOTTOM_PADDING; + } + + self.bodies = pass.next; + FlowLayout { + blocks: pass.blocks, + width: input.width, + height: pass.y, + stats: pass.stats, + } + } +} + +fn heading_level(node: &BlockNode) -> Option { + match &node.content { + BlockContent::Paragraph { kind, .. } => match kind { + ParagraphType::H1 => Some(1), + ParagraphType::H2 => Some(2), + ParagraphType::H3 => Some(3), + ParagraphType::H4 => Some(4), + ParagraphType::H5 => Some(5), + ParagraphType::H6 => Some(6), + _ => None, + }, + _ => None, + } +} + +impl<'a> FlowPass<'a> { + fn body( + &mut self, + key: &str, + content: &dyn std::fmt::Debug, + build: impl FnOnce(&mut Self) -> BlockBody, + ) -> Rc { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + format!("{content:?}").hash(&mut hasher); + self.input.width.to_bits().hash(&mut hasher); + self.input.theme.hash(&mut hasher); + self.input.env_rev.hash(&mut hasher); + let fingerprint = hasher.finish(); + + let body = match self.previous.get(key) { + Some((previous, body)) if *previous == fingerprint => { + self.stats.reused += 1; + body.clone() + } + _ => { + self.stats.laid_out += 1; + Rc::new(build(self)) + } + }; + self.next + .insert(key.to_string(), (fingerprint, body.clone())); + body + } + + /// Place `nodes` as siblings at horizontal offset `x`, collapsing vertical margins. + /// `inherited_align` is the text alignment of the nearest ancestor that sets one. + fn flow( + &mut self, + nodes: &[BlockNode], + x: f32, + list_depth: usize, + inherited_align: BlockAlign, + ) { + let mut collapsed_heading: Option = None; + for node in nodes { + if let Some(level) = collapsed_heading { + match heading_level(node) { + Some(next) if next <= level => collapsed_heading = None, + _ => continue, + } + } + if node.is_edgeless_only() { + continue; + } + + let width = (self.input.width - x).max(0.0); + let align = match &node.content { + BlockContent::Paragraph { text_align, .. } + | BlockContent::List { text_align, .. } => text_align.unwrap_or(inherited_align), + _ => inherited_align, + }; + let fingerprint = ( + &node.content, + node.children.is_empty(), + width.to_bits(), + list_depth, + align, + ); + let body = self.body(&node.id, &fingerprint, |pass| { + pass.block_body(node, width, list_depth, align) + }); + let gap = match self.pending_margin { + None => body.margin_top, + Some(previous) => previous.max(body.margin_top), + }; + self.y += gap; + self.blocks.push(FlowBlock { + block_id: node.id.clone(), + snapshot_id: SharedString::from(format!("page.block.{}", node.id)), + x, + y: self.y, + body: body.clone(), + }); + self.y += body.height; + self.pending_margin = Some(body.margin_bottom); + + let (shows_children, child_depth) = match &node.content { + BlockContent::List { collapsed, .. } => (!collapsed, list_depth + 1), + // A collapsed heading hides its own children as well as the siblings under it. + BlockContent::Paragraph { + collapsed: true, .. + } if heading_level(node).is_some() => (false, 0), + BlockContent::Unknown(_) => (false, 0), + _ => (true, 0), + }; + if shows_children && !node.children.is_empty() { + // The block's own row has no bottom margin; the last child's bottom margin + // collapses through the children container into the block's. + self.pending_margin = Some(0.0); + self.flow(&node.children, x + CHILD_INDENT, child_depth, align); + self.pending_margin = + Some(self.pending_margin.unwrap_or(0.0).max(body.margin_bottom)); + } + + if let ( + Some(level), + BlockContent::Paragraph { + collapsed: true, .. + }, + ) = (heading_level(node), &node.content) + { + collapsed_heading = Some(level); + } + } + } + + fn plain_inline( + &self, + text: &str, + style: InlineStyle, + width: f32, + line_height: f32, + align: InlineAlign, + ) -> Rc { + Rc::new(layout_inline( + text, + &style, + width, + line_height, + InlineBaseline::Of(&style), + align, + self.window, + )) + } + + /// Lay out a block's rich text with the shared paragraph engine, at the block's + /// typography. A delta the engine rejects falls back to its plain string. + fn block_text( + &self, + text: &RichText, + spec: &TextSpec, + ink: Hsla, + width: f32, + align: BlockAlign, + ) -> FlowTextLayout { + let width = width.max(1.0); + let paragraph = RichParagraph::from_delta_with_resolver(text.delta.clone(), |page_id| { + self.input.page_titles.get(page_id).cloned() + }); + match paragraph { + Ok(paragraph) => { + let mut style = RichParagraphStyle::from_theme(self.input.theme.mode()); + // Inline code is set 3px below the block's size; its measured box scales + // with it. + let code_font_size = (spec.font_size - 3.0).max(8.0); + let code_scale = code_font_size / style.code_font_size; + style.code_font_size = code_font_size; + style.code_baseline *= code_scale; + style.code_descent *= code_scale; + style.font_size = spec.font_size; + style.base_weight = FontWeight(spec.font_weight); + style.line_height = spec.line_height; + style.baseline_offset = Some(spec.baseline); + style.letter_spacing = spec.letter_spacing; + style.align = match align { + BlockAlign::Left => TextAlign::Left, + BlockAlign::Center => TextAlign::Center, + BlockAlign::Right => TextAlign::Right, + }; + style.text_color = ink; + FlowTextLayout::Rich(Arc::new(paragraph.layout( + self.window.text_system(), + &style, + width, + ))) + } + Err(_) => FlowTextLayout::Plain(Rc::new(layout_inline( + &text.plain, + &InlineStyle::new(FONT_SANS, spec.font_size, spec.font_weight, ink), + width, + spec.line_height, + InlineBaseline::At(spec.baseline), + match align { + BlockAlign::Left => InlineAlign::Left, + BlockAlign::Center => InlineAlign::Center, + BlockAlign::Right => InlineAlign::Right, + }, + self.window, + ))), + } + } + + fn title_body(&mut self, title: &str) -> BlockBody { + let width = self.input.width; + let (text, color) = if title.is_empty() { + ("Title", self.palette.placeholder.opacity(0.5)) + } else { + (title, self.palette.text_primary) + }; + let style = InlineStyle::new( + FONT_SANS, + TITLE_SPEC.font_size, + TITLE_SPEC.font_weight, + color, + ); + let layout = Rc::new(layout_inline( + text, + &style, + width, + TITLE_SPEC.line_height, + InlineBaseline::At(TITLE_SPEC.baseline), + InlineAlign::Left, + self.window, + )); + BlockBody { + kind: FlowKind::Title, + width, + height: layout.height(), + margin_top: TITLE_SPEC.margin_top, + margin_bottom: TITLE_SPEC.margin_bottom, + plain: text.to_string(), + prims: vec![Prim::Text { + x: 0.0, + y: 0.0, + layout: layout.clone(), + clip: None, + }], + text: Some(FlowText { + x: 0.0, + y: 0.0, + layout: FlowTextLayout::Plain(layout), + }), + prefix: None, + } + } + + fn block_body( + &mut self, + node: &BlockNode, + width: f32, + list_depth: usize, + align: BlockAlign, + ) -> BlockBody { + match &node.content { + BlockContent::Paragraph { + kind, + text, + collapsed, + .. + } => self.paragraph_body(*kind, text, *collapsed, width, align), + BlockContent::List { + kind, + checked, + collapsed, + text, + numbered_index, + .. + } => self.list_body( + *kind, + *checked, + *collapsed && !node.children.is_empty(), + text, + numbered_index.unwrap_or(1), + list_depth, + width, + align, + ), + BlockContent::Divider => self.divider_body(width), + BlockContent::Code { + language, + wrap, + text, + caption, + } => self.code_body(language, *wrap, text, caption, width), + BlockContent::Image { + source_id, + width: image_width, + height: image_height, + caption, + } => self.image_body(source_id, *image_width, *image_height, caption, width), + BlockContent::Bookmark { + url, + title, + description, + caption, + } => self.bookmark_body( + url, + title.as_deref(), + description.as_deref(), + caption, + width, + ), + _ => self.unknown_body(&node.flavour, &node.id, width), + } + } + + fn paragraph_body( + &mut self, + kind: ParagraphType, + text: &RichText, + collapsed: bool, + width: f32, + align: BlockAlign, + ) -> BlockBody { + let spec = paragraph_spec(kind); + let (pad_left, pad_top, pad_bottom) = match kind { + ParagraphType::Quote => QUOTE_PADDING, + _ => (0.0, 0.0, 0.0), + }; + let layout = self.block_text( + text, + &spec, + self.palette.text_primary, + width - pad_left, + align, + ); + let height = pad_top + layout.height() + pad_bottom; + let mut prims = Vec::new(); + if kind == ParagraphType::Quote { + prims.push(Prim::Quad { + rect: FlowRect::new(0.0, pad_top, QUOTE_BAR_WIDTH, height - pad_top - pad_bottom), + fill: Some(self.palette.quote), + border: None, + radius: QUOTE_BAR_WIDTH / 2.0, + dashed: false, + }); + } + let is_heading = !matches!(kind, ParagraphType::Text | ParagraphType::Quote); + if collapsed && is_heading { + // A collapsed heading hides the blocks under it; a marker in the gutter, on the + // heading's first line, says so. + prims.push(Prim::Icon { + rect: FlowRect::new( + -COLLAPSED_MARKER_SIZE - 4.0, + ((spec.line_height - COLLAPSED_MARKER_SIZE) / 2.0).floor(), + COLLAPSED_MARKER_SIZE, + COLLAPSED_MARKER_SIZE, + ), + icon: IconPaint::named("ToggleRightIcon"), + color: self.palette.icon, + }); + } + prims.push(layout.prim(pad_left, pad_top)); + BlockBody { + kind: FlowKind::Paragraph(kind), + width, + height, + margin_top: spec.margin_top, + margin_bottom: spec.margin_bottom, + plain: text.plain.clone(), + prims, + text: Some(FlowText { + x: pad_left, + y: pad_top, + layout, + }), + prefix: None, + } + } + + fn list_body( + &mut self, + kind: ListType, + checked: bool, + collapsed: bool, + text: &RichText, + numbered_index: u32, + list_depth: usize, + width: f32, + align: BlockAlign, + ) -> BlockBody { + let spec = paragraph_spec(ParagraphType::Text); + let ink = if kind == ListType::Todo && checked { + self.palette.text_secondary + } else { + self.palette.text_primary + }; + let line_height = spec.line_height; + let marker = self.palette.list_marker; + let mut prims = Vec::new(); + let mut text_x = LIST_PREFIX_WIDTH; + let prefix; + // Every prefix is placed against the first line of text, never the whole block. + let prefix_height = match kind { + ListType::Toggle => line_height, + _ => LIST_PREFIX_WIDTH, + }; + let center_y = (prefix_height / 2.0).floor(); + + match kind { + ListType::Bulleted => { + let (size, filled, radius) = match list_depth % 4 { + 0 => (6.0, true, 3.0), + 1 => (6.0, false, 3.0), + 2 => (6.0, true, 1.0), + _ => (6.0, false, 1.0), + }; + let origin = (LIST_PREFIX_WIDTH - size) / 2.0; + prefix = FlowRect::new(origin, center_y - size / 2.0, size, size); + prims.push(Prim::Quad { + rect: prefix, + fill: filled.then_some(marker), + border: (!filled).then_some(marker), + radius, + dashed: false, + }); + } + ListType::Numbered => { + // The smaller number shares the baseline of the item's first line. + let label = number_prefix(numbered_index, list_depth); + let style = InlineStyle::new(FONT_SANS, TYPOGRAPHY.font_sm_px, 400.0, marker); + let layout = Rc::new(layout_inline( + &label, + &style, + f32::MAX, + line_height, + InlineBaseline::At(spec.baseline), + InlineAlign::Left, + self.window, + )); + let label_width = layout.content_width().ceil(); + text_x = (2.0 + label_width.max(22.0)).max(LIST_PREFIX_WIDTH); + prefix = FlowRect::new(2.0, 0.0, label_width, line_height); + prims.push(Prim::Text { + x: 2.0, + y: 0.0, + layout, + clip: None, + }); + } + ListType::Todo => { + let (icon, color) = if checked { + ("CheckBoxCheckSolidIcon", self.palette.brand) + } else { + ("CheckBoxUnIcon", self.palette.icon) + }; + prefix = FlowRect::new(0.0, center_y - 10.0, 20.0, 20.0); + prims.push(Prim::Icon { + rect: prefix, + icon: IconPaint::named(icon), + color, + }); + } + ListType::Toggle => { + let icon = if collapsed { + "ToggleRightIcon" + } else { + "ToggleDownIcon" + }; + prefix = FlowRect::new(2.0, center_y - 10.0, 20.0, 20.0); + prims.push(Prim::Icon { + rect: prefix, + icon: IconPaint::named(icon), + color: marker, + }); + } + } + + // The prefix stays at the left edge; only the text box follows the alignment. + let layout = self.block_text(text, &spec, ink, width - text_x, align); + let height = layout.height().max(prefix_height); + prims.push(layout.prim(text_x, 0.0)); + BlockBody { + kind: FlowKind::List(kind), + width, + height, + margin_top: TEXT_BLOCK_MARGIN, + margin_bottom: TEXT_BLOCK_MARGIN, + plain: text.plain.clone(), + prims, + text: Some(FlowText { + x: text_x, + y: 0.0, + layout, + }), + prefix: Some(prefix), + } + } + + fn divider_body(&mut self, width: f32) -> BlockBody { + BlockBody { + kind: FlowKind::Divider, + width, + height: DIVIDER_HEIGHT, + margin_top: TYPOGRAPHY.paragraph_space_px, + margin_bottom: 0.0, + plain: String::new(), + prims: vec![Prim::Quad { + rect: FlowRect::new(8.0, DIVIDER_HEIGHT / 2.0, (width - 16.0).max(0.0), 1.0), + fill: Some(self.palette.divider), + border: None, + radius: 0.0, + dashed: false, + }], + text: None, + prefix: None, + } + } + + /// Append a centered caption below a block body, if there is one. + fn push_caption(&self, body: &mut BlockBody, caption: &str) { + if caption.is_empty() { + return; + } + let style = InlineStyle::new(FONT_SANS, TYPOGRAPHY.font_sm_px, 400.0, self.palette.icon); + let layout = self.plain_inline(caption, style, body.width, 22.0, InlineAlign::Center); + let y = body.height + 4.0; + body.height = y + layout.height(); + body.prims.push(Prim::Text { + x: 0.0, + y, + layout, + clip: None, + }); + } + + fn code_body( + &mut self, + language: &str, + wrap: bool, + text: &str, + caption: &str, + width: f32, + ) -> BlockBody { + let (pad_y, pad_x) = CODE_PADDING; + let line_height = TYPOGRAPHY.font_xs_px + 8.0; + let code_style = InlineStyle::new( + FONT_CODE, + TYPOGRAPHY.font_xs_px, + 400.0, + self.palette.text_primary, + ); + let number_style = InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px, + 400.0, + self.palette.text_secondary, + ); + let code_x = pad_x + CODE_GUTTER; + let code_width = (width - code_x - pad_x).max(1.0); + + let mut prims = Vec::new(); + let mut y = pad_y; + let mut first_line: Option> = None; + for (index, line) in text.split('\n').enumerate() { + let layout = self.plain_inline( + line, + code_style.clone(), + if wrap { code_width } else { f32::MAX }, + line_height, + InlineAlign::Left, + ); + // Line numbers sit on the baseline of the code they count. + let number = Rc::new(layout_inline( + &(index + 1).to_string(), + &number_style, + f32::MAX, + line_height, + InlineBaseline::Of(&code_style), + InlineAlign::Left, + self.window, + )); + prims.push(Prim::Text { + x: pad_x, + y, + layout: number, + clip: None, + }); + let height = layout.height(); + first_line.get_or_insert_with(|| layout.clone()); + prims.push(Prim::Text { + x: code_x, + y, + layout, + // Unwrapped lines stop at the block's padding edge. + clip: (!wrap).then(|| FlowRect::new(code_x, y, code_width, height)), + }); + y += height; + } + let height = y + pad_y; + + prims.insert( + 0, + Prim::Quad { + rect: FlowRect::new(0.0, 0.0, width, height), + fill: Some(self.palette.code_background), + border: None, + radius: CODE_RADIUS, + dashed: false, + }, + ); + let label = if language.is_empty() { + "Plain Text" + } else { + language + }; + let label_style = InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px, + 400.0, + self.palette.text_secondary, + ); + let label_layout = self.plain_inline(label, label_style, f32::MAX, 16.0, InlineAlign::Left); + prims.push(Prim::Text { + x: pad_x, + y: 8.0, + layout: label_layout, + clip: Some(FlowRect::new( + pad_x, + 8.0, + (width - 2.0 * pad_x).max(0.0), + 16.0, + )), + }); + + let mut body = BlockBody { + kind: FlowKind::Code, + width, + height, + margin_top: CARD_BLOCK_MARGIN, + margin_bottom: CARD_BLOCK_MARGIN, + plain: text.to_string(), + prims, + text: first_line.map(|layout| FlowText { + x: code_x, + y: pad_y, + layout: FlowTextLayout::Plain(layout), + }), + prefix: None, + }; + self.push_caption(&mut body, caption); + body + } + + fn image_body( + &mut self, + source_id: &str, + image_width: Option, + image_height: Option, + caption: &str, + width: f32, + ) -> BlockBody { + let slot = self.input.images.get(source_id); + let natural = match slot { + Some(ImageSlot::Ready(image)) => { + let size = image.size(0); + Some((size.width.0 as f32, size.height.0 as f32)) + } + _ => None, + }; + // Explicit block dimensions win; otherwise the image's own size, then a 16:9 frame. + let (mut w, mut h) = match (image_width, image_height, natural) { + (Some(w), Some(h), _) => (w as f32, h as f32), + (Some(w), None, Some((nw, nh))) if nw > 0.0 => (w as f32, w as f32 * nh / nw), + (_, _, Some(natural)) => natural, + _ => (480.0, 270.0), + }; + if w > width && w > 0.0 { + h *= width / w; + w = width; + } + let (w, h) = (w.round().max(1.0), h.round().max(1.0)); + let x = ((width - w) / 2.0).floor().max(0.0); + + let mut prims = Vec::new(); + let plain; + match slot { + Some(ImageSlot::Ready(image)) => { + plain = caption.to_string(); + prims.push(Prim::Image { + rect: FlowRect::new(x, 0.0, w, h), + image: image.clone(), + }); + } + other => { + // Media frame shown until the blob arrives (or when it cannot be shown). + // Longest wording first; a small frame falls back to a shorter one. + let wordings: &[&str] = if matches!(other, Some(ImageSlot::Unavailable)) { + &["Image unavailable", "Unavailable", "No image"] + } else { + &["Loading image", "Loading"] + }; + let status = wordings[0]; + plain = status.to_string(); + prims.push(Prim::Quad { + rect: FlowRect::new(x, 0.0, w, h), + fill: Some(self.palette.background_secondary), + border: Some(self.palette.border), + radius: 8.0, + dashed: false, + }); + let inner = (w - 24.0).max(1.0); + let status_style = InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_sm_px, + 500.0, + self.palette.text_secondary, + ); + let fitting = wordings + .iter() + .find(|wording| { + f32::from(shape(self.window, wording, &status_style).width()) <= inner + }) + .unwrap_or(&status); + let lines = [ + (fitting.to_string(), status_style, 22.0), + ( + format!("{} \u{00d7} {}", w as i64, h as i64), + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px, + 400.0, + self.palette.text_secondary, + ), + 20.0, + ), + ( + source_id.to_string(), + InlineStyle::new( + FONT_CODE, + TYPOGRAPHY.font_xs_px, + 400.0, + self.palette.text_secondary, + ), + 20.0, + ), + ]; + let total: f32 = lines.iter().map(|(_, _, line_height)| line_height).sum(); + let mut y = ((h - total) / 2.0).floor().max(0.0); + for (text, style, line_height) in lines { + if y + line_height > h { + break; + } + let shaped = truncate_to_width(self.window, &text, &style, inner); + let text = shaped.text.to_string(); + let layout = + self.plain_inline(&text, style, inner, line_height, InlineAlign::Center); + prims.push(Prim::Text { + x: x + 12.0, + y, + layout, + clip: None, + }); + y += line_height; + } + } + } + + let mut body = BlockBody { + kind: FlowKind::Image, + width, + height: h, + margin_top: CARD_BLOCK_MARGIN, + margin_bottom: CARD_BLOCK_MARGIN, + plain, + prims, + text: None, + prefix: None, + }; + self.push_caption(&mut body, caption); + body + } + + fn bookmark_body( + &mut self, + url: &str, + title: Option<&str>, + description: Option<&str>, + caption: &str, + width: f32, + ) -> BlockBody { + // 1px border plus the content's 12px padding. + let pad = 13.0; + let inner = (width - 2.0 * pad).max(1.0); + let host = host_name(url); + let title = title.filter(|title| !title.is_empty()).unwrap_or(host); + // Without a fetched description the card falls back to the address itself. + let description = description + .filter(|description| !description.is_empty()) + .unwrap_or(url); + + let mut prims = vec![Prim::Quad { + rect: FlowRect::new(0.0, 0.0, width, BOOKMARK_HEIGHT), + fill: Some(self.palette.background), + border: Some(self.palette.card_border), + radius: 8.0, + dashed: false, + }]; + + // Title row: 16px link icon centered on the 22px title line. + let title_style = InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_sm_px, + 600.0, + self.palette.text_primary, + ); + let title_x = pad + 16.0 + 8.0; + let title_width = (width - title_x - pad).max(1.0); + let title_text = truncate_to_width(self.window, title, &title_style, title_width) + .text + .to_string(); + prims.push(Prim::Icon { + rect: FlowRect::new(pad, pad + 3.0, 16.0, 16.0), + icon: IconPaint::named("LinkIcon"), + color: self.palette.icon, + }); + prims.push(Prim::Text { + x: title_x, + y: pad, + layout: self.plain_inline( + &title_text, + title_style, + title_width, + 22.0, + InlineAlign::Left, + ), + clip: None, + }); + + // Description: at most two 20px lines. + let description_style = InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px, + 400.0, + self.palette.text_primary, + ); + let description_y = pad + 22.0 + 4.0; + prims.push(Prim::Text { + x: pad, + y: description_y, + layout: self.plain_inline( + description, + description_style, + inner, + 20.0, + InlineAlign::Left, + ), + clip: Some(FlowRect::new(pad, description_y, inner, 40.0)), + }); + + // Address row pinned to the bottom padding edge. + let url_style = InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px, + 400.0, + self.palette.text_secondary, + ); + let url_text = truncate_to_width(self.window, host, &url_style, inner) + .text + .to_string(); + prims.push(Prim::Text { + x: pad, + y: BOOKMARK_HEIGHT - pad - 20.0, + layout: self.plain_inline(&url_text, url_style, inner, 20.0, InlineAlign::Left), + clip: None, + }); + + let mut body = BlockBody { + kind: FlowKind::Bookmark, + width, + height: BOOKMARK_HEIGHT, + margin_top: CARD_BLOCK_MARGIN, + margin_bottom: CARD_BLOCK_MARGIN, + plain: title.to_string(), + prims, + text: None, + prefix: None, + }; + self.push_caption(&mut body, caption); + body + } + + fn unknown_body(&mut self, flavour: &str, block_id: &str, width: f32) -> BlockBody { + let pad = 12.0; + let inner = (width - 2.0 * pad).max(1.0); + let title_style = InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_sm_px, + 500.0, + self.palette.text_secondary, + ); + let id_style = InlineStyle::new( + FONT_CODE, + TYPOGRAPHY.font_xs_px, + 400.0, + self.palette.text_secondary, + ); + let label = format!("Unsupported block: {flavour}"); + let title = self.plain_inline(&label, title_style, inner, 22.0, InlineAlign::Left); + let id_text = truncate_to_width(self.window, block_id, &id_style, inner) + .text + .to_string(); + let id = self.plain_inline(&id_text, id_style, inner, 20.0, InlineAlign::Left); + let height = pad + title.height() + id.height() + pad; + let id_y = pad + title.height(); + BlockBody { + kind: FlowKind::Unknown, + width, + height, + margin_top: CARD_BLOCK_MARGIN, + margin_bottom: CARD_BLOCK_MARGIN, + plain: format!("[Unsupported block: {flavour}]"), + prims: vec![ + Prim::Quad { + rect: FlowRect::new(0.0, 0.0, width, height), + fill: None, + border: Some(self.palette.divider), + radius: 8.0, + dashed: true, + }, + Prim::Text { + x: pad, + y: pad, + layout: title, + clip: None, + }, + Prim::Text { + x: pad, + y: id_y, + layout: id, + clip: None, + }, + ], + text: None, + prefix: None, + } + } +} + +/// Host of a URL without scheme, credentials, port or path; the input itself if it has none. +fn host_name(url: &str) -> &str { + let rest = url.split_once("://").map_or(url, |(_, rest)| rest); + let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest); + let host = authority + .rsplit_once('@') + .map_or(authority, |(_, host)| host); + let host = host.split(':').next().unwrap_or(host); + if host.is_empty() { url } else { host } +} + +/// One end of a remote text selection: a UTF-16 range inside a block's text. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RemotePoint { + pub block_id: String, + pub index: usize, + pub length: usize, +} + +/// A remote collaborator's text selection (BlockSuite `TextSelection`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RemoteSelection { + pub from: RemotePoint, + pub to: Option, + pub reverse: bool, +} + +/// A remote collaborator from room awareness. +#[derive(Clone, Debug, PartialEq)] +pub struct RemotePresence { + pub client_id: u64, + pub name: String, + pub color: Hsla, + pub selection: Option, +} + +/// World-space geometry of a remote collaborator's selection, caret and name tag. +pub struct PresenceMark { + pub client_id: u64, + pub name: SharedString, + pub color: Hsla, + pub highlights: Vec, + pub caret: FlowRect, + pub label: FlowRect, + label_text: ShapedLine, +} + +impl FlowLayout { + /// Resolve remote selections against this layout. Collaborators whose selection points + /// at a block that is not laid out (or has no text) produce no mark. + pub fn presence_marks( + &self, + presences: &[RemotePresence], + palette: &Palette, + window: &Window, + ) -> Vec { + let text_blocks: Vec<(usize, &FlowBlock, &FlowText)> = self + .blocks + .iter() + .enumerate() + .filter_map(|(index, block)| block.body.text.as_ref().map(|text| (index, block, text))) + .collect(); + let find = |block_id: &str| { + text_blocks + .iter() + .position(|(_, block, _)| block.block_id == block_id) + }; + + let mut marks = Vec::new(); + for presence in presences { + let Some(selection) = &presence.selection else { + continue; + }; + let Some(from_index) = find(&selection.from.block_id) else { + continue; + }; + let to_index = selection + .to + .as_ref() + .and_then(|to| find(&to.block_id)) + .filter(|to_index| *to_index > from_index); + + let mut highlights = Vec::new(); + let mut cover = |position: usize, start: usize, end: usize| { + let (_, block, text) = text_blocks[position]; + for (line, x0, x1) in text.layout.selection_spans(start, end) { + let left = (block.x + text.x + x0).floor(); + let right = (block.x + text.x + x1).ceil().min(self.width); + highlights.push(FlowRect::new( + left, + block.y + text.y + line as f32 * text.layout.line_height(), + (right - left).max(0.0), + text.layout.line_height(), + )); + } + }; + let from_end = selection.from.index.saturating_add(selection.from.length); + cover(from_index, selection.from.index, from_end); + if let (Some(to_index), Some(to)) = (to_index, &selection.to) { + for between in from_index + 1..to_index { + cover(between, 0, usize::MAX); + } + cover(to_index, to.index, to.index.saturating_add(to.length)); + } + + // The caret sits at the focus end of the selection. + let (caret_position, caret_offset) = if selection.reverse { + (from_index, selection.from.index) + } else { + match (to_index, &selection.to) { + (Some(to_index), Some(to)) => (to_index, to.index.saturating_add(to.length)), + _ => (from_index, from_end), + } + }; + let (_, block, text) = text_blocks[caret_position]; + let (caret_x, caret_line) = text.layout.caret(caret_offset); + let line_height = text.layout.line_height(); + let caret = FlowRect::new( + (block.x + text.x + caret_x - 1.0) + .round() + .clamp(0.0, (self.width - 2.0).max(0.0)), + block.y + text.y + caret_line as f32 * line_height, + 2.0, + line_height, + ); + + let label_style = + InlineStyle::new(FONT_SANS, TYPOGRAPHY.font_xs_px, 500.0, palette.on_accent); + let max_label = (self.width - 8.0).max(1.0); + let label_text = truncate_to_width(window, &presence.name, &label_style, max_label); + let label_width = (f32::from(label_text.width()).ceil() + 8.0).min(self.width); + // The tag hangs above the caret, shifted left at the column edge and flipped + // below the caret when there is no room above. + let label_x = caret.x.min((self.width - label_width).max(0.0)); + let label_y = if caret.y >= PRESENCE_LABEL_HEIGHT { + caret.y - PRESENCE_LABEL_HEIGHT + } else { + caret.bottom() + }; + marks.push(PresenceMark { + client_id: presence.client_id, + name: SharedString::from(presence.name.clone()), + color: presence.color, + highlights, + caret, + label: FlowRect::new(label_x, label_y, label_width, PRESENCE_LABEL_HEIGHT), + label_text, + }); + } + marks + } +} + +/// Mapping of world space onto the screen for one frame. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PageViewport { + /// X of the page column's left edge inside the viewport element. + pub column_x: f32, + /// Height of the viewport element. + pub height: f32, + /// World y shown at the top of the viewport. + pub scroll_y: f32, +} + +impl PageViewport { + fn fully_visible(&self, rect: &FlowRect) -> bool { + rect.y >= self.scroll_y && rect.bottom() <= self.scroll_y + self.height + } + + fn intersects(&self, rect: &FlowRect) -> bool { + rect.bottom() > self.scroll_y && rect.y < self.scroll_y + self.height + } +} + +/// Snapshot parent id of every page block element. +pub const PAGE_SURFACE_ID: &str = "page.editor_surface"; + +/// Build the elements of the blocks and presence marks intersecting `viewport`, positioned +/// absolutely inside the viewport element. +/// +/// Only blocks lying completely inside the viewport record an element snapshot: a block +/// cut by the fold is clipped on purpose and would read as a clipping fault otherwise. +pub fn page_elements( + layout: &Rc, + marks: Vec, + viewport: PageViewport, +) -> Vec { + let mut elements = Vec::new(); + for block in &layout.blocks { + let rect = block.rect(); + if !viewport.intersects(&rect) { + continue; + } + let body = block.body.clone(); + let mut element = div() + .absolute() + .left(px(viewport.column_x + rect.x)) + .top(px(rect.y - viewport.scroll_y)) + .w(px(rect.w)) + .h(px(rect.h)); + if viewport.fully_visible(&rect) { + element = element + .snapshot(block.snapshot_id.clone(), Some(PAGE_SURFACE_ID)) + .snapshot_text(block.body.plain.clone()); + } + elements.push( + element + .child( + canvas( + |_, _, _| (), + move |bounds, _, window, cx| body.paint(bounds.origin, window, cx), + ) + .size_full(), + ) + .into_any_element(), + ); + } + + // Presence paints after every block so name tags stay above neighbouring text. + for mark in marks { + let screen = |rect: &FlowRect| { + FlowRect::new( + viewport.column_x + rect.x, + rect.y - viewport.scroll_y, + rect.w, + rect.h, + ) + }; + // Same wash and corner radius as BlockSuite's remote selection rects. + let highlight = mark.color.opacity(0.2); + for rect in &mark.highlights { + if !viewport.intersects(rect) { + continue; + } + let rect = screen(rect); + elements.push( + div() + .absolute() + .left(px(rect.x)) + .top(px(rect.y)) + .w(px(rect.w)) + .h(px(rect.h)) + .rounded(px(3.0)) + .bg(highlight) + .into_any_element(), + ); + } + if viewport.intersects(&mark.caret) { + let rect = screen(&mark.caret); + let mut caret = div() + .absolute() + .left(px(rect.x)) + .top(px(rect.y)) + .w(px(rect.w)) + .h(px(rect.h)) + .bg(mark.color); + if viewport.fully_visible(&mark.caret) { + caret = caret.snapshot( + SharedString::from(format!("page.presence.{}.caret", mark.client_id)), + Some(PAGE_SURFACE_ID), + ); + } + elements.push(caret.into_any_element()); + } + if viewport.intersects(&mark.label) { + let rect = screen(&mark.label); + let text = mark.label_text.clone(); + let mut label = div() + .absolute() + .left(px(rect.x)) + .top(px(rect.y)) + .w(px(rect.w)) + .h(px(rect.h)) + .rounded(px(4.0)) + .bg(mark.color); + if viewport.fully_visible(&mark.label) { + label = label + .snapshot( + SharedString::from(format!("page.presence.{}.label", mark.client_id)), + Some(PAGE_SURFACE_ID), + ) + .snapshot_text(mark.name.clone()); + } + elements.push( + label + .child( + canvas( + |_, _, _| (), + move |bounds, _, window, cx| { + let origin = point(bounds.origin.x + px(4.0), bounds.origin.y); + let _ = text.paint( + origin, + px(PRESENCE_LABEL_HEIGHT), + TextAlign::Left, + None, + window, + cx, + ); + }, + ) + .size_full(), + ) + .into_any_element(), + ); + } + } + elements +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn number_prefix_cycles_numbers_letters_and_roman_numerals() { + assert_eq!(number_prefix(1, 0), "1."); + assert_eq!(number_prefix(12, 0), "12."); + assert_eq!(number_prefix(1, 1), "a."); + assert_eq!(number_prefix(26, 1), "z."); + assert_eq!(number_prefix(27, 1), "aa."); + assert_eq!(number_prefix(1, 2), "I."); + assert_eq!(number_prefix(4, 2), "IV."); + assert_eq!(number_prefix(14, 2), "XIV."); + assert_eq!(number_prefix(3, 3), "3."); + assert_eq!(number_prefix(0, 0), "1."); + } + + #[test] + fn page_geometry_centers_the_column_and_narrows_on_small_viewports() { + let wide = page_geometry(1280.0); + assert_eq!(wide.column_width, 752.0); + assert_eq!(wide.column_x, 264.0); + assert_eq!(wide.side_padding, SIDE_PADDING); + + // Between the narrow breakpoint and the editor width the column fills the viewport. + let medium = page_geometry(800.0); + assert_eq!(medium.column_x, SIDE_PADDING); + assert_eq!(medium.column_width, 800.0 - 2.0 * SIDE_PADDING); + + for width in [640.0, 390.0, 320.0] { + let narrow = page_geometry(width); + assert_eq!(narrow.side_padding, SIDE_PADDING_NARROW); + assert_eq!(narrow.column_x, SIDE_PADDING_NARROW); + assert_eq!(narrow.column_width, width - 2.0 * SIDE_PADDING_NARROW); + assert!(narrow.column_x + narrow.column_width <= width); + } + assert_eq!(page_geometry(0.0).column_width, 0.0); + } + + #[test] + fn inline_segments_keep_trailing_whitespace_and_hard_breaks() { + assert_eq!( + inline_segments("two words\nnext"), + vec![Some("two "), Some("words"), None, Some("next")] + ); + assert_eq!(inline_segments(""), Vec::>::new()); + assert_eq!(inline_segments("a\n"), vec![Some("a"), None]); + assert_eq!(inline_segments(" lead"), vec![Some(" "), Some("lead")]); + } + + #[test] + fn host_name_strips_scheme_credentials_port_and_path() { + assert_eq!(host_name("https://affine.pro/blog?x=1"), "affine.pro"); + assert_eq!( + host_name("http://user:pw@example.com:8080/a"), + "example.com" + ); + assert_eq!(host_name("example.org"), "example.org"); + assert_eq!(host_name(""), ""); + } +} diff --git a/blocksuite/native-playground/crates/playground/src/lib.rs b/blocksuite/native-playground/crates/playground/src/lib.rs index a7cbaa4ba9..9a76f2764c 100644 --- a/blocksuite/native-playground/crates/playground/src/lib.rs +++ b/blocksuite/native-playground/crates/playground/src/lib.rs @@ -1,74 +1,348 @@ //! Native BlockSuite Playground shell (native desktop + Web Wasm canvas + headless harness). //! -//! All targets execute the single shipping [`PlaygroundView`] element tree. +//! All targets execute the single shipping [`PlaygroundView`] element tree: screen-space +//! chrome (top bar, mode switcher, theme toggle, presence) around the world-space page +//! rendered by [`block_flow`]. +pub mod block_flow; pub mod rich_text; +pub mod room_client; +pub mod theme; -use std::borrow::Cow; -use ui::{App, FontWeight, Hsla, Motion, MotionCurve, Window, div, prelude::*, px}; +use std::{ + collections::{BTreeMap, BTreeSet, HashMap}, + rc::Rc, + sync::Arc, + time::Duration, +}; -/// Tracked repository Inter variable font registered into the text system on all targets. -const INTER_VARIABLE_TTF: &[u8] = include_bytes!( - "../../../../../packages/frontend/component/src/fonts/inter/Inter-VariableFont_slnt,wght.ttf" -); +use blocksuite_playground_doc::{ + DocResult, + awareness::{AwarenessPayload, RoomAwareness, TextRangePoint, TextSelectionState}, + client_id_from_seed, + read::{BlockContent, PageSnapshot}, + schema::{BlockSpec, ListType, ParagraphType}, + session::PageDocSession, +}; +use ui::{ + AnyElement, BorderStyle, Bounds, Corners, Edges, FontWeight, Motion, MotionCurve, ScrollEvent, + SharedString, Task, TextRun, Window, canvas, div, point, prelude::*, px, size, +}; +use y_octo::{AHashMap, Any, SessionValue, TextAttributes}; -macro_rules! plex_mono { - ($face:literal) => { - Cow::Borrowed( - include_bytes!(concat!( - "../../../../../packages/frontend/component/src/fonts/ibm-plex-mono/IBMPlexMono-", - $face, - ".ttf" - )) - .as_slice(), - ) - }; -} +use crate::{ + block_flow::{ + BlockFlow, FlowInput, FlowLayout, ImageSlot, PAGE_SURFACE_ID, PageViewport, RemotePoint, + RemotePresence, RemoteSelection, decode_image, page_elements, page_geometry, + }, + room_client::{ + DocState, RoomCommand, RoomConfig, RoomEffects, RoomEvent, RoomLink, RoomProtocol, + RoomStatus, + }, + theme::{FONT_SANS, Palette}, +}; -/// Registers the Inter variable font and four IBM Plex Mono faces. -/// -/// Must be called before opening any window across macOS, Linux headless, and Web Wasm. -pub fn register_bundled_fonts(cx: &App) -> anyhow::Result<()> { - cx.text_system().add_fonts(vec![ - Cow::Borrowed(INTER_VARIABLE_TTF), - plex_mono!("Regular"), - plex_mono!("Bold"), - plex_mono!("Italic"), - plex_mono!("BoldItalic"), - ]) -} +pub use crate::theme::{PlaygroundTheme, register_bundled_fonts}; + +/// Height of the top bar, including its bottom border. +pub const TOPBAR_HEIGHT: f32 = 53.0; + +/// Room id of the built-in showcase workspace. +pub const SHOWCASE_ROOM: &str = "showcase"; +/// Page shown first in any workspace, and the showcase page id. +pub const HOME_PAGE_ID: &str = "doc:home"; +/// Name of the showcase's remote collaborator. +pub const SHOWCASE_PEER_NAME: &str = "Ada"; +/// `sourceId` of the showcase image blob. +pub const SHOWCASE_IMAGE_ID: &str = "showcase-gradient"; /// Active view mode for the playground frame. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum PlaygroundMode { + #[default] Page, Edgeless, } +impl PlaygroundMode { + pub fn parse(value: &str) -> Option { + match value { + "page" => Some(Self::Page), + "edgeless" => Some(Self::Edgeless), + _ => None, + } + } +} + +/// Initial configuration of a [`PlaygroundView`]. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PlaygroundOptions { + pub theme: PlaygroundTheme, + pub mode: PlaygroundMode, + /// Live room to join. Without one the view shows the built-in showcase document. + pub room: Option, +} + +impl PlaygroundOptions { + /// Parse command-line flags: `--theme light|dark`, `--mode page|edgeless`, + /// `--room ` and `--relay ` (a relay without a room is an error). + pub fn from_args(args: impl IntoIterator) -> anyhow::Result { + let mut options = Self::default(); + let mut room = None; + let mut relay = None; + let mut args = args.into_iter(); + while let Some(flag) = args.next() { + let mut value = || { + args.next() + .ok_or_else(|| anyhow::anyhow!("{flag} requires a value")) + }; + match flag.as_str() { + "--theme" => { + let value = value()?; + options.theme = PlaygroundTheme::parse(&value) + .ok_or_else(|| anyhow::anyhow!("unknown theme {value:?} (light|dark)"))?; + } + "--mode" => { + let value = value()?; + options.mode = PlaygroundMode::parse(&value) + .ok_or_else(|| anyhow::anyhow!("unknown mode {value:?} (page|edgeless)"))?; + } + "--room" => room = Some(value()?), + "--relay" => relay = Some(value()?), + other => anyhow::bail!("unknown flag: {other}"), + } + } + match (room, relay) { + (Some(room), relay) => { + let config = RoomConfig::new(&room, relay.as_deref()); + #[cfg(not(target_family = "wasm"))] + config.validate_native()?; + options.room = Some(config); + } + (None, Some(_)) => anyhow::bail!("--relay requires --room "), + (None, None) => {} + } + Ok(options) + } +} + +const PILL_WIDTH: f32 = 186.0; const PILL_PAGE_X: f64 = 4.0; const PILL_EDGELESS_X: f64 = 94.0; const PILL_TRANSITION_MS: f64 = 200.0; +const THEME_TOGGLE_SIZE: f32 = 32.0; +const TOPBAR_EDGE: f32 = 12.0; +const SCROLL_LINE: f32 = 20.0; + +/// Images whose blob is still missing after this many fetches show as unavailable. +const BLOB_MISSES_SHOWN_UNAVAILABLE: u32 = 3; +/// Longest wait between two fetches of a blob the relay does not have yet. +const BLOB_RETRY_MAX_MS: u64 = 4_000; + +/// Wait before fetching a blob again after `misses` consecutive misses: 500 ms, doubling +/// up to [`BLOB_RETRY_MAX_MS`]. +fn blob_retry_backoff_ms(misses: u32) -> u64 { + (250_u64 << misses.clamp(1, 5)).min(BLOB_RETRY_MAX_MS) +} + +/// Fetch of a room blob the page references but the document state does not hold yet. +/// It is retried for as long as the page references the blob: an uploader writes the +/// `sourceId` into the document before its upload finishes, and the relay announces no +/// completed upload. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct BlobFetchState { + in_flight: bool, + /// Consecutive fetches that found no blob. + misses: u32, + /// Scheduler time of the next fetch, once none is in flight. + next_retry_ms: u64, +} + +struct RoomRuntime { + config: RoomConfig, + protocol: RoomProtocol, + link: RoomLink, + error: Option, +} + +type LayoutKey = (u64, u32, PlaygroundTheme, u64); /// Interactive GPUI root view for desktop, Web canvas, and headless verification sessions. pub struct PlaygroundView { mode: PlaygroundMode, + theme: PlaygroundTheme, origin_time: ui::scheduler::Instant, pill_motion: Option, + state: DocState, + room: Option, + page_id: Option, + snapshot: Option>, + page_titles: BTreeMap, + /// What each referenced image shows. An entry without a pending fetch was decoded + /// from its blob and is final. + images: HashMap, + blob_fetches: BTreeMap, + doc_rev: u64, + env_rev: u64, + flow: BlockFlow, + layout: Option<(LayoutKey, Rc)>, + scroll_y: f32, + max_scroll: f32, + _tasks: Vec>, +} + +#[cfg(not(target_family = "wasm"))] +fn fresh_client_id() -> u64 { + blocksuite_playground_doc::random_client_id() +} + +#[cfg(target_family = "wasm")] +fn fresh_client_id() -> u64 { + client_id_from_seed((js_sys::Math::random() * 9_007_199_254_740_992.0) as u64) } impl PlaygroundView { + /// Open the built-in showcase document in the light theme. pub fn new(cx: &mut Context) -> Self { - Self { - mode: PlaygroundMode::Page, + Self::with_options(PlaygroundOptions::default(), cx) + } + + /// Open the view with an explicit theme and mode, joining `options.room` when given. + pub fn with_options(options: PlaygroundOptions, cx: &mut Context) -> Self { + let mut tasks = Vec::new(); + let (state, room) = match options.room { + Some(config) => { + let state = DocState::new(&config.room, fresh_client_id()) + .expect("generated client ids are always in the 53-bit range"); + let link = room_client::connect(config.clone()); + let events = link.events().clone(); + tasks.push(cx.spawn(async move |this, cx| { + while let Ok(event) = events.recv().await { + let handled = this.update(cx, |this, cx| this.handle_room_event(event, cx)); + if handled.is_err() { + break; + } + } + })); + tasks.push(cx.spawn(async move |this, cx| { + loop { + cx.background_executor().timer(Duration::from_secs(1)).await; + if this.update(cx, |this, cx| this.tick_room(cx)).is_err() { + break; + } + } + })); + let runtime = RoomRuntime { + protocol: RoomProtocol::new(config.room.clone()), + config, + link, + error: None, + }; + (state, Some(runtime)) + } + None => ( + seed_showcase_doc().expect("the showcase document seeds deterministically"), + None, + ), + }; + + let mut view = Self { + mode: options.mode, + theme: options.theme, origin_time: cx.background_executor().now(), pill_motion: None, - } + state, + room, + page_id: None, + snapshot: None, + page_titles: BTreeMap::new(), + images: HashMap::new(), + blob_fetches: BTreeMap::new(), + doc_rev: 0, + env_rev: 0, + flow: BlockFlow::new(), + layout: None, + scroll_y: 0.0, + max_scroll: 0.0, + _tasks: tasks, + }; + view.refresh_document(); + view } pub fn mode(&self) -> PlaygroundMode { self.mode } + pub fn theme(&self) -> PlaygroundTheme { + self.theme + } + + pub fn set_theme(&mut self, theme: PlaygroundTheme, cx: &mut Context) { + if self.theme != theme { + self.theme = theme; + cx.notify(); + } + } + + /// Document, presence and blobs currently shown. + pub fn document(&self) -> &DocState { + &self.state + } + + /// Replace the shown document, e.g. with one prepared by a host or a test. + pub fn set_document(&mut self, state: DocState, cx: &mut Context) { + self.state = state; + self.images.clear(); + self.blob_fetches.clear(); + self.scroll_y = 0.0; + self.refresh_document(); + cx.notify(); + } + + /// Mutate the shown document and re-read it. + pub fn edit_document( + &mut self, + cx: &mut Context, + edit: impl FnOnce(&mut DocState) -> R, + ) -> R { + let result = edit(&mut self.state); + self.refresh_document(); + cx.notify(); + result + } + + /// Snapshot of the page currently shown, if its root block exists. + pub fn page_snapshot(&self) -> Option<&PageSnapshot> { + self.snapshot.as_deref() + } + + /// World-space layout painted by the latest Page frame. + pub fn flow_layout(&self) -> Option> { + self.layout.as_ref().map(|(_, layout)| layout.clone()) + } + + /// Connection state of the live room, `None` for the showcase document. + pub fn room_status(&self) -> Option { + self.room.as_ref().map(|room| room.protocol.status()) + } + + /// Handle every room event already delivered by the transport; returns how many. + /// + /// The view also handles events as they arrive on its own; hosts that step the + /// application manually call this to apply what is queued right now. + pub fn pump_room(&mut self, cx: &mut Context) -> usize { + let Some(events) = self.room.as_ref().map(|room| room.link.events().clone()) else { + return 0; + }; + let mut handled = 0; + while let Ok(event) = events.try_recv() { + self.handle_room_event(event, cx); + handled += 1; + } + handled + } + fn now_ms(&self, cx: &Context) -> f64 { cx.background_executor() .now() @@ -77,6 +351,177 @@ impl PlaygroundView { * 1000.0 } + fn handle_room_event(&mut self, event: RoomEvent, cx: &mut Context) { + let now_ms = self.now_ms(cx) as u64; + let Some(room) = self.room.as_mut() else { + return; + }; + let effects = match event { + RoomEvent::Opened => { + let effects = room.protocol.on_open(&mut self.state, now_ms); + // A fresh connection fetches every missing blob again right away. + for (source_id, fetch) in &mut self.blob_fetches { + fetch.misses = 0; + fetch.next_retry_ms = now_ms; + if !fetch.in_flight { + fetch.in_flight = true; + room.link.send(RoomCommand::FetchBlob(source_id.clone())); + } + if matches!(self.images.get(source_id), Some(ImageSlot::Unavailable)) { + self.images.insert(source_id.clone(), ImageSlot::Loading); + self.env_rev += 1; + } + } + effects + } + RoomEvent::Frame(frame) => room.protocol.on_frame(&mut self.state, &frame, now_ms), + RoomEvent::Closed(reason) => Ok(room.protocol.on_close(reason)), + RoomEvent::Blob { + source_id, + bytes: Some(bytes), + } => { + // Present bytes are decoded once; bytes that are no image stay unavailable + // and are never fetched again. + self.blob_fetches.remove(&source_id); + let slot = decode_image(&bytes).map_or(ImageSlot::Unavailable, ImageSlot::Ready); + self.state.blobs.insert(source_id.clone(), Arc::new(bytes)); + self.images.insert(source_id, slot); + self.env_rev += 1; + Ok(RoomEffects::default()) + } + RoomEvent::Blob { + source_id, + bytes: None, + } => { + if let Some(fetch) = self.blob_fetches.get_mut(&source_id) { + fetch.in_flight = false; + fetch.misses = fetch.misses.saturating_add(1); + fetch.next_retry_ms = + now_ms.saturating_add(blob_retry_backoff_ms(fetch.misses)); + // The frame says so after a few misses; the fetch keeps retrying. + if fetch.misses >= BLOB_MISSES_SHOWN_UNAVAILABLE + && !matches!(self.images.get(&source_id), Some(ImageSlot::Unavailable)) + { + self.images.insert(source_id, ImageSlot::Unavailable); + self.env_rev += 1; + } + } + Ok(RoomEffects::default()) + } + }; + match effects { + Ok(effects) => { + room.error = None; + for frame in effects.outbound { + room.link.send(RoomCommand::Send(frame)); + } + if effects.doc_changed { + self.refresh_document(); + } + } + Err(err) => room.error = Some(err.to_string()), + } + cx.notify(); + } + + fn tick_room(&mut self, cx: &mut Context) { + let now_ms = self.now_ms(cx) as u64; + let Some(room) = self.room.as_mut() else { + return; + }; + if let Ok(effects) = room.protocol.tick(&mut self.state, now_ms) { + for frame in effects.outbound { + room.link.send(RoomCommand::Send(frame)); + } + if effects.awareness_changed { + cx.notify(); + } + } + // Fetch missing blobs again once their backoff ran out, unless the room is offline. + if !matches!(room.protocol.status(), RoomStatus::Offline(_)) { + for (source_id, fetch) in &mut self.blob_fetches { + if !fetch.in_flight && now_ms >= fetch.next_retry_ms { + fetch.in_flight = true; + room.link.send(RoomCommand::FetchBlob(source_id.clone())); + } + } + } + } + + /// Re-read the shown page from the workspace and bring images in line with the blobs. + fn refresh_document(&mut self) { + let pages = self.state.workspace.list_pages().unwrap_or_default(); + let titles: BTreeMap = pages + .iter() + .map(|page| (page.id.clone(), page.title.clone())) + .collect(); + if titles != self.page_titles { + self.page_titles = titles; + self.env_rev += 1; + } + + self.page_id = pages + .iter() + .find(|page| page.id == HOME_PAGE_ID) + .or(pages.first()) + .map(|page| page.id.clone()); + self.snapshot = self + .page_id + .as_deref() + .and_then(|id| self.state.workspace.page(id)) + .and_then(|page| page.read_page_snapshot().ok()) + .filter(|snapshot| snapshot.root.is_some()) + .map(Rc::new); + self.doc_rev += 1; + + let mut referenced = BTreeSet::new(); + for node in self + .snapshot + .iter() + .flat_map(|snapshot| snapshot.root.iter()) + .flat_map(|root| root.walk()) + { + if let BlockContent::Image { source_id, .. } = &node.content + && !source_id.is_empty() + { + referenced.insert(source_id.clone()); + } + } + // Fetches of blobs the page no longer references stop. An ordinary document + // update never restarts a fetch that is already tracked. + let images = &mut self.images; + self.blob_fetches.retain(|source_id, _| { + let keep = referenced.contains(source_id); + if !keep { + images.remove(source_id); + } + keep + }); + for source_id in referenced { + if let Some(bytes) = self.state.blobs.get(&source_id) { + // Decoded once; a blob that is no image stays unavailable. + if !self.images.contains_key(&source_id) + || self.blob_fetches.remove(&source_id).is_some() + { + let slot = decode_image(bytes).map_or(ImageSlot::Unavailable, ImageSlot::Ready); + self.images.insert(source_id, slot); + self.env_rev += 1; + } + } else if let Some(room) = &self.room + && !self.blob_fetches.contains_key(&source_id) + { + self.blob_fetches.insert( + source_id.clone(), + BlobFetchState { + in_flight: true, + ..BlobFetchState::default() + }, + ); + room.link.send(RoomCommand::FetchBlob(source_id)); + } + } + } + fn target_pill_x(mode: PlaygroundMode) -> f64 { match mode { PlaygroundMode::Page => PILL_PAGE_X, @@ -107,17 +552,110 @@ impl PlaygroundView { )); cx.notify(); } -} -fn rgb_hex(hex: u32) -> Hsla { - let r = ((hex >> 16) & 0xff) as f32 / 255.0; - let g = ((hex >> 8) & 0xff) as f32 / 255.0; - let b = (hex & 0xff) as f32 / 255.0; - ui::Rgba { r, g, b, a: 1.0 }.into() -} + fn on_scroll(&mut self, event: &ScrollEvent, _: &mut Window, cx: &mut Context) { + let delta = f32::from(event.delta.pixel_delta(px(SCROLL_LINE)).y); + let target = (self.scroll_y - delta).clamp(0.0, self.max_scroll).round(); + if target != self.scroll_y { + self.scroll_y = target; + cx.notify(); + } + } -impl ui::Render for PlaygroundView { - fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + /// Remote collaborators of the shown page, ordered by client id. + fn remote_presences(&self, palette: &Palette) -> Vec { + const FALLBACK_COLORS: [&str; 8] = [ + "--affine-multi-players-purple", + "--affine-multi-players-magenta", + "--affine-multi-players-red", + "--affine-multi-players-orange", + "--affine-multi-players-green", + "--affine-multi-players-blue", + "--affine-multi-players-brown", + "--affine-multi-players-grey", + ]; + let awareness = &self.state.awareness; + awareness + .active_remote_clients() + .into_iter() + .filter_map(|client_id| { + let payload = awareness.get_payload(client_id)?; + let color = self.theme.css_color(&payload.color).unwrap_or_else(|| { + let fallback = FALLBACK_COLORS[(client_id % 8) as usize]; + self.theme.css_var(fallback).unwrap_or(palette.brand) + }); + Some(RemotePresence { + client_id, + name: payload.user.name.clone(), + color, + selection: self.text_selection(&payload), + }) + }) + .collect() + } + + /// The collaborator's text selection in the shown page, if it has one. + fn text_selection(&self, payload: &AwarenessPayload) -> Option { + let page_id = self.page_id.as_deref()?; + // BlockSuite keys `selectionV2` by `${store.id}:${nanoid()}`, and a bare page id is + // accepted too. JS matches entries with `startsWith(store.id)`; splitting at the + // last colon is deliberately stricter, so `doc:home` never picks up the selections + // of `doc:home2` or `doc:home:archive`, and a selection in another page is never + // shown in this one. + let selection = payload + .selection_v2 + .iter() + .filter(|(key, _)| { + key.as_str() == page_id + || key + .rsplit_once(':') + .is_some_and(|(store, id)| store == page_id && !id.is_empty()) + }) + .flat_map(|(_, selections)| selections) + .filter_map(|value| serde_json::from_value::(value.clone()).ok()) + .find(|selection| selection.kind == "text")?; + let remote_point = |point: TextRangePoint| RemotePoint { + block_id: point.block_id, + index: usize::try_from(point.index).unwrap_or(usize::MAX), + length: usize::try_from(point.length).unwrap_or(0), + }; + Some(RemoteSelection { + from: remote_point(selection.from), + to: selection.to.map(remote_point), + reverse: selection.reverse.unwrap_or(false), + }) + } + + fn ensure_layout(&mut self, width: f32, window: &Window) -> Option> { + let snapshot = self.snapshot.clone()?; + let key = (self.doc_rev, width.to_bits(), self.theme, self.env_rev); + if let Some((cached, layout)) = &self.layout + && *cached == key + { + return Some(layout.clone()); + } + let layout = Rc::new(self.flow.layout( + &FlowInput { + snapshot: &snapshot, + width, + theme: self.theme, + page_titles: &self.page_titles, + images: &self.images, + env_rev: self.env_rev, + }, + window, + )); + self.layout = Some((key, layout.clone())); + Some(layout) + } + + fn render_mode_switcher( + &mut self, + palette: &Palette, + left: f32, + window: &mut Window, + cx: &mut Context, + ) -> impl IntoElement + use<> { let now_ms = self.now_ms(cx); let raw_indicator_x = self.indicator_x(now_ms); if let Some(motion) = self.pill_motion { @@ -128,34 +666,9 @@ impl ui::Render for PlaygroundView { } } let indicator_x = raw_indicator_x.round() as f32; - - let bg_canvas = rgb_hex(0xFFFFFF); - let bg_toolbar = rgb_hex(0xFBFBFB); - let border_subtle = rgb_hex(0xE3E2E4); - let accent_blue = rgb_hex(0x1E96EB); - let edgeless_bg = rgb_hex(0xF5F8FC); - let edgeless_border = rgb_hex(0xBFDBFE); - let pill_bg = rgb_hex(0xF4F4F5); - let card_bg = rgb_hex(0xFAFAFA); - let ink_primary = rgb_hex(0x121212); - let ink_muted = rgb_hex(0x52525B); - let is_page = self.mode == PlaygroundMode::Page; let is_edgeless = self.mode == PlaygroundMode::Edgeless; - let title_text = match self.mode { - PlaygroundMode::Page => "Native BlockSuite Playground", - PlaygroundMode::Edgeless => "Edgeless Spatial Canvas", - }; - let body_text = match self.mode { - PlaygroundMode::Page => { - "Deterministic native canvas shell rendered across Metal, WGPU, and WebAssembly." - } - PlaygroundMode::Edgeless => { - "Infinite spatial canvas mode active — click Page to return to document layout." - } - }; - let indicator = div() .absolute() .left(px(indicator_x)) @@ -163,28 +676,37 @@ impl ui::Render for PlaygroundView { .w(px(86.0)) .h(px(26.0)) .rounded(px(6.0)) - .bg(bg_canvas) + .bg(palette.background) .border_1() - .border_color(accent_blue) + .border_color(palette.brand) .snapshot( "chrome.mode_switcher.indicator", Some("chrome.mode_switcher"), ); - let page_btn = div() - .id("mode-page") - .absolute() - .left(px(PILL_PAGE_X as f32)) - .top(px(4.0)) - .w(px(86.0)) - .h(px(26.0)) - .rounded(px(6.0)) - .flex() - .items_center() - .justify_center() - .text_color(if is_page { ink_primary } else { ink_muted }) - .text_size(px(13.0)) - .font_weight(FontWeight::MEDIUM) + let segment = |id: &'static str, x: f64, active: bool| { + div() + .id(id) + .absolute() + .left(px(x as f32)) + .top(px(4.0)) + .w(px(86.0)) + .h(px(26.0)) + .rounded(px(6.0)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .text_color(if active { + palette.text_primary + } else { + palette.text_secondary + }) + .text_size(px(13.0)) + .font_weight(FontWeight::MEDIUM) + }; + + let page_button = segment("mode-page", PILL_PAGE_X, is_page) .on_click(cx.listener(|this, _, _, cx| { this.set_mode(PlaygroundMode::Page, cx); })) @@ -193,20 +715,7 @@ impl ui::Render for PlaygroundView { .snapshot_text("Page") .child("Page"); - let edgeless_btn = div() - .id("mode-edgeless") - .absolute() - .left(px(PILL_EDGELESS_X as f32)) - .top(px(4.0)) - .w(px(86.0)) - .h(px(26.0)) - .rounded(px(6.0)) - .flex() - .items_center() - .justify_center() - .text_color(if is_edgeless { ink_primary } else { ink_muted }) - .text_size(px(13.0)) - .font_weight(FontWeight::MEDIUM) + let edgeless_button = segment("mode-edgeless", PILL_EDGELESS_X, is_edgeless) .on_click(cx.listener(|this, _, _, cx| { this.set_mode(PlaygroundMode::Edgeless, cx); })) @@ -219,90 +728,896 @@ impl ui::Render for PlaygroundView { .child("Edgeless"); div() - .size_full() - .font_family("Inter") - .flex() - .flex_col() - .bg(if is_edgeless { edgeless_bg } else { bg_canvas }) - .snapshot("root.canvas", None) + .absolute() + .left(px(left)) + .top(px(8.0)) + .w(px(PILL_WIDTH)) + .h(px(36.0)) + .p(px(4.0)) + .rounded(px(10.0)) + .bg(palette.background_secondary) + .border_1() + .border_color(palette.border) + .snapshot("chrome.mode_switcher", Some("chrome.topbar")) + .child(indicator) + .child(page_button) + .child(edgeless_button) + } + + fn render_theme_toggle( + &self, + palette: &Palette, + cx: &mut Context, + ) -> impl IntoElement + use<> { + let ink = palette.text_primary; + let hover = palette.hover; + div() + .id("theme-toggle") + .flex_none() + .w(px(THEME_TOGGLE_SIZE)) + .h(px(THEME_TOGGLE_SIZE)) + .rounded(px(8.0)) + .bg(palette.background) + .border_1() + .border_color(palette.border) + .cursor_pointer() + .hover(move |style| style.bg(hover)) + .on_click(cx.listener(|this, _, _, cx| { + let next = this.theme.toggled(); + this.set_theme(next, cx); + })) + .snapshot("chrome.theme_toggle", Some("chrome.topbar")) + .snapshot_text(match self.theme { + PlaygroundTheme::Light => "Light", + PlaygroundTheme::Dark => "Dark", + }) .child( + // Contrast glyph: a ring whose left half is filled. + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let glyph = Bounds::new( + point( + bounds.origin.x + (bounds.size.width - px(14.0)) / 2.0, + bounds.origin.y + (bounds.size.height - px(14.0)) / 2.0, + ), + size(px(14.0), px(14.0)), + ); + window.paint_quad(ui::quad( + glyph, + Corners::all(px(7.0)), + ui::transparent_black(), + Edges::all(px(1.5)), + ink, + BorderStyle::Solid, + )); + window.paint_quad(ui::quad( + Bounds::new(glyph.origin, size(px(7.0), px(14.0))), + Corners { + top_left: px(7.0), + top_right: px(0.0), + bottom_right: px(0.0), + bottom_left: px(7.0), + }, + ink, + Edges::all(px(0.0)), + ui::transparent_black(), + BorderStyle::Solid, + )); + }, + ) + .size_full(), + ) + } + + /// Presence badges that fit in `available` px: name pills on regular viewports, + /// initials on narrow ones, and a `+N` chip for collaborators that do not fit. + fn render_presence( + presences: &[RemotePresence], + palette: &Palette, + available: f32, + compact: bool, + window: &Window, + ) -> Vec { + const NAME_MAX: f32 = 72.0; + let slot = if compact { + 32.0 + } else { + 8.0 + 8.0 + 6.0 + NAME_MAX + 10.0 + 8.0 + }; + let capacity = ((available / slot).floor().max(0.0) as usize).min(3); + if capacity == 0 || presences.is_empty() { + return Vec::new(); + } + let shown = if presences.len() > capacity { + capacity - 1 + } else { + presences.len() + }; + let mut badges = Vec::new(); + let hidden = presences.len() - shown; + if hidden > 0 { + badges.push( div() - .w_full() - .h(px(53.0)) - .bg(bg_toolbar) - .border_b_1() - .border_color(border_subtle) + .flex_none() + .w(px(24.0)) + .h(px(24.0)) + .rounded(px(12.0)) + .bg(palette.background_secondary) .flex() .items_center() .justify_center() - .snapshot("chrome.topbar", Some("root.canvas")) + .text_size(px(11.0)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text_secondary) + .snapshot("chrome.presence.more", Some("chrome.topbar")) + .snapshot_text(format!("+{hidden}")) + .child(format!("+{hidden}")) + .into_any_element(), + ); + } + for presence in &presences[..shown] { + let id = SharedString::from(format!("chrome.presence.{}", presence.client_id)); + let name = SharedString::from(presence.name.clone()); + let badge = if compact { + let initial: String = presence + .name + .chars() + .find(|ch| ch.is_alphanumeric()) + .map(|ch| ch.to_uppercase().collect()) + .unwrap_or_else(|| "?".to_string()); + div() + .flex_none() + .w(px(24.0)) + .h(px(24.0)) + .rounded(px(12.0)) + .bg(presence.color) + .flex() + .items_center() + .justify_center() + .text_size(px(12.0)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.on_accent) + .snapshot(id, Some("chrome.topbar")) + .snapshot_text(name) + .child(initial) + } else { + // The name box gets an explicit whole-pixel width so the pill stays on + // the pixel grid whatever the name measures. + let mut font = ui::font(FONT_SANS); + font.weight = FontWeight::MEDIUM; + let measured = window.text_system().shape_line( + name.clone(), + px(12.0), + &[TextRun { + len: name.len(), + font, + color: palette.text_primary, + background_color: None, + underline: None, + strikethrough: None, + }], + None, + ); + let name_width = f32::from(measured.width()).ceil().min(NAME_MAX); + div() + .flex_none() + .h(px(24.0)) + .pl(px(8.0)) + .pr(px(10.0)) + .rounded(px(12.0)) + .bg(presence.color.opacity(0.14)) + .flex() + .items_center() + .gap(px(6.0)) + .snapshot(id, Some("chrome.topbar")) + .snapshot_text(name.clone()) .child( div() - .relative() - .w(px(186.0)) - .h(px(36.0)) - .p(px(4.0)) - .rounded(px(10.0)) - .bg(pill_bg) - .border_1() - .border_color(border_subtle) - .snapshot("chrome.mode_switcher", Some("chrome.topbar")) - .child(indicator) - .child(page_btn) - .child(edgeless_btn), - ), + .flex_none() + .w(px(8.0)) + .h(px(8.0)) + .rounded(px(4.0)) + .bg(presence.color), + ) + .child( + div() + .flex_none() + .w(px(name_width)) + .truncate() + .text_size(px(12.0)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text_primary) + .child(name), + ) + }; + badges.push(badge.into_any_element()); + } + badges + } + + fn render_page( + &mut self, + palette: &Palette, + viewport_width: f32, + viewport_height: f32, + presences: &[RemotePresence], + window: &mut Window, + cx: &mut Context, + ) -> AnyElement { + let geometry = page_geometry(viewport_width); + let surface = div() + .id("page-viewport") + .relative() + .flex_1() + .w_full() + .min_h_0() + .overflow_hidden() + .bg(palette.background) + .on_scroll(cx.listener(Self::on_scroll)) + .snapshot(PAGE_SURFACE_ID, Some("root.canvas")); + + let Some(layout) = self.ensure_layout(geometry.column_width, window) else { + self.max_scroll = 0.0; + self.scroll_y = 0.0; + return surface + .child(self.render_status(palette, &geometry)) + .into_any_element(); + }; + self.max_scroll = (layout.height - viewport_height).max(0.0).ceil(); + self.scroll_y = self.scroll_y.clamp(0.0, self.max_scroll).round(); + let marks = layout.presence_marks(presences, palette, window); + surface + .children(page_elements( + &layout, + marks, + PageViewport { + column_x: geometry.column_x, + height: viewport_height, + scroll_y: self.scroll_y, + }, + )) + .into_any_element() + } + + /// Shown while a live room has not delivered a page yet. + fn render_status( + &self, + palette: &Palette, + geometry: &block_flow::PageGeometry, + ) -> impl IntoElement + use<> { + let (headline, detail) = match &self.room { + Some(room) => { + let headline = match room.protocol.status() { + RoomStatus::Connecting => format!("Connecting to room {}", room.config.room), + RoomStatus::Syncing { .. } => format!("Syncing room {}", room.config.room), + RoomStatus::Live => format!("Room {} has no page yet", room.config.room), + RoomStatus::Offline(_) => format!("Room {} is offline", room.config.room), + }; + let detail = match (room.protocol.status(), &room.error) { + (_, Some(error)) => error.clone(), + (RoomStatus::Offline(reason), None) => reason, + (RoomStatus::Live, None) => { + "The page appears here as soon as a peer creates it.".to_string() + } + _ => room.config.ws_url.clone(), + }; + (headline, detail) + } + None => ( + "This document has no page yet".to_string(), + "Add an affine:page root block to see it here.".to_string(), + ), + }; + div() + .absolute() + .left(px(geometry.column_x)) + .top(px(block_flow::TITLE_PADDING_Y)) + .w(px(geometry.column_width)) + .flex() + .flex_col() + .gap(px(8.0)) + .snapshot("page.status", Some(PAGE_SURFACE_ID)) + .snapshot_text(headline.clone()) + .child( + div() + .text_size(px(20.0)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.text_primary) + .child(headline), ) .child( div() - .flex_1() - .flex() - .justify_center() - .pt(px(48.0)) - .pb(px(48.0)) - .px(px(48.0)) - .child( - div() - .w(px(944.0)) - .h_full() - .p(px(32.0)) - .rounded(px(12.0)) - .bg(if is_edgeless { bg_canvas } else { card_bg }) - .border_1() - .border_color(if is_edgeless { - edgeless_border - } else { - border_subtle - }) - .flex() - .flex_col() - .gap(px(16.0)) - .snapshot("page.editor_surface", Some("root.canvas")) - .child( - div() - .text_size(px(24.0)) - .font_weight(FontWeight::BOLD) - .text_color(ink_primary) - .snapshot("page.title_block", Some("page.editor_surface")) - .snapshot_text(title_text) - .child(title_text), - ) - .child(div().w_full().h(px(1.0)).bg(if is_edgeless { - edgeless_border - } else { - border_subtle - })) - .child( - div() - .text_size(px(14.0)) - .font_weight(FontWeight::NORMAL) - .text_color(ink_muted) - .snapshot("page.body_block", Some("page.editor_surface")) - .snapshot_text(body_text) - .child(body_text), - ), - ), + .text_size(px(14.0)) + .text_color(palette.text_secondary) + .child(detail), ) } + + fn render_edgeless(&self, palette: &Palette, viewport_width: f32) -> AnyElement { + let title_text = "Edgeless Spatial Canvas"; + let body_text = + "Infinite spatial canvas mode active — click Page to return to document layout."; + let gutter = if viewport_width <= block_flow::NARROW_VIEWPORT { + 24.0 + } else { + 48.0 + }; + div() + .flex_1() + .w_full() + .min_h_0() + .flex() + .justify_center() + .p(px(gutter)) + .bg(palette.background_secondary) + .child( + div() + .w_full() + .max_w(px(block_flow::EDITOR_WIDTH)) + .h_full() + .p(px(32.0)) + .rounded(px(12.0)) + .bg(palette.background) + .border_1() + .border_color(palette.border) + .flex() + .flex_col() + .gap(px(16.0)) + .snapshot(PAGE_SURFACE_ID, Some("root.canvas")) + .child( + div() + .text_size(px(24.0)) + .font_weight(FontWeight::BOLD) + .text_color(palette.text_primary) + .snapshot("page.title_block", Some(PAGE_SURFACE_ID)) + .snapshot_text(title_text) + .child(title_text), + ) + .child(div().w_full().h(px(1.0)).bg(palette.border)) + .child( + div() + .text_size(px(14.0)) + .font_weight(FontWeight::NORMAL) + .text_color(palette.text_secondary) + .snapshot("page.body_block", Some(PAGE_SURFACE_ID)) + .snapshot_text(body_text) + .child(body_text), + ), + ) + .into_any_element() + } +} + +impl ui::Render for PlaygroundView { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let palette = self.theme.palette(); + let viewport = window.viewport_size(); + let viewport_width = f32::from(viewport.width).floor(); + let viewport_height = (f32::from(viewport.height) - TOPBAR_HEIGHT) + .max(0.0) + .floor(); + + let presences = self.remote_presences(&palette); + let switcher_left = ((viewport_width - PILL_WIDTH) / 2.0).floor().max(0.0); + let mode_switcher = self.render_mode_switcher(&palette, switcher_left, window, cx); + let theme_toggle = self.render_theme_toggle(&palette, cx); + let presence_room = viewport_width + - TOPBAR_EDGE + - THEME_TOGGLE_SIZE + - 8.0 + - (switcher_left + PILL_WIDTH + 8.0); + let badges = Self::render_presence( + &presences, + &palette, + presence_room, + viewport_width < 720.0, + window, + ); + + let content = match self.mode { + PlaygroundMode::Page => self.render_page( + &palette, + viewport_width, + viewport_height, + &presences, + window, + cx, + ), + PlaygroundMode::Edgeless => self.render_edgeless(&palette, viewport_width), + }; + + div() + .size_full() + .font_family(FONT_SANS) + .flex() + .flex_col() + .bg(palette.background) + .text_color(palette.text_primary) + .snapshot("root.canvas", None) + .child( + div() + .relative() + .flex_none() + .w_full() + .h(px(TOPBAR_HEIGHT)) + .bg(palette.panel) + .border_b_1() + .border_color(palette.border) + .snapshot("chrome.topbar", Some("root.canvas")) + .child(mode_switcher) + .child( + div() + .absolute() + .right(px(TOPBAR_EDGE)) + .top(px(0.0)) + .h(px(TOPBAR_HEIGHT - 1.0)) + .flex() + .items_center() + .gap(px(8.0)) + .children(badges) + .child(theme_toggle), + ), + ) + .child(content) + } +} + +struct ShowcaseSeed<'a> { + page: &'a mut PageDocSession, + now_ms: u64, +} + +impl ShowcaseSeed<'_> { + fn tick(&mut self) -> u64 { + self.now_ms += 600; + self.now_ms + } + + fn add(&mut self, id: &str, spec: BlockSpec, parent: Option<&str>) -> DocResult { + let now_ms = self.tick(); + self.page.add_block(id, spec, parent, None, now_ms)?; + Ok(()) + } + + fn paragraph(&mut self, id: &str, kind: ParagraphType, text: &str, parent: &str) -> DocResult { + self.add( + id, + BlockSpec::Paragraph { + paragraph_type: kind, + text: text.to_string(), + }, + Some(parent), + ) + } + + fn list( + &mut self, + id: &str, + kind: ListType, + text: &str, + checked: bool, + parent: &str, + ) -> DocResult { + self.add( + id, + BlockSpec::List { + list_type: kind, + text: text.to_string(), + checked, + order: None, + }, + Some(parent), + ) + } + + /// A numbered item with its explicit `prop:order`, as the JavaScript editor stores it. + fn numbered(&mut self, id: &str, text: &str, order: i32, parent: &str) -> DocResult { + self.add( + id, + BlockSpec::List { + list_type: ListType::Numbered, + text: text.to_string(), + checked: false, + order: Some(order), + }, + Some(parent), + ) + } + + /// Apply an inline attribute to the first occurrence of `needle` in the block's text. + fn mark(&mut self, id: &str, text: &str, needle: &str, key: &str, value: Any) -> DocResult { + let Some(start) = text.find(needle) else { + return Ok(()); + }; + let index = text[..start].encode_utf16().count() as u64; + let len = needle.encode_utf16().count() as u64; + let mut attrs = TextAttributes::new(); + attrs.insert(key.to_string(), value); + let now_ms = self.tick(); + self.page + .format_text(id, "prop:text", index, len, attrs, now_ms)?; + Ok(()) + } +} + +/// The showcase image: a 64 × 40 diagonal gradient PNG, byte-identical on every target. +fn showcase_gradient_png() -> Vec { + const WIDTH: u32 = 64; + const HEIGHT: u32 = 40; + const FROM: [u32; 3] = [30, 150, 235]; + const TO: [u32; 3] = [123, 97, 255]; + let span = 2 * (WIDTH - 1) * (HEIGHT - 1); + let mut rgba = Vec::with_capacity((WIDTH * HEIGHT * 4) as usize); + for y in 0..HEIGHT { + for x in 0..WIDTH { + let t = x * (HEIGHT - 1) + y * (WIDTH - 1); + for channel in 0..3 { + rgba.push(((FROM[channel] * (span - t) + TO[channel] * t) / span) as u8); + } + rgba.push(255); + } + } + encode_png_rgba(WIDTH, HEIGHT, &rgba) +} + +/// Encode 8-bit RGBA pixels as a PNG whose image data sits in stored (uncompressed) +/// deflate blocks: small, dependency-free, and the same bytes everywhere. +fn encode_png_rgba(width: u32, height: u32, rgba: &[u8]) -> Vec { + fn crc32(bytes: &[u8]) -> u32 { + let mut crc = u32::MAX; + for &byte in bytes { + crc ^= u32::from(byte); + for _ in 0..8 { + crc = (crc >> 1) ^ (0xEDB8_8320 & 0_u32.wrapping_sub(crc & 1)); + } + } + !crc + } + fn chunk(out: &mut Vec, kind: &[u8; 4], data: &[u8]) { + out.extend_from_slice(&(data.len() as u32).to_be_bytes()); + let start = out.len(); + out.extend_from_slice(kind); + out.extend_from_slice(data); + let crc = crc32(&out[start..]); + out.extend_from_slice(&crc.to_be_bytes()); + } + + // Scanlines: a zero filter byte followed by the row's pixels. + let stride = width as usize * 4; + let mut raw = Vec::with_capacity((stride + 1) * height as usize); + for row in rgba.chunks_exact(stride).take(height as usize) { + raw.push(0); + raw.extend_from_slice(row); + } + + let mut zlib = vec![0x78, 0x01]; + let mut blocks = raw.chunks(0xFFFF).peekable(); + while let Some(block) = blocks.next() { + let len = block.len() as u16; + zlib.push(u8::from(blocks.peek().is_none())); + zlib.extend_from_slice(&len.to_le_bytes()); + zlib.extend_from_slice(&(!len).to_le_bytes()); + zlib.extend_from_slice(block); + } + let (mut a, mut b) = (1_u32, 0_u32); + for &byte in &raw { + a = (a + u32::from(byte)) % 65_521; + b = (b + a) % 65_521; + } + zlib.extend_from_slice(&((b << 16) | a).to_be_bytes()); + + let mut png = vec![0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1A, b'\n']; + let mut header = Vec::with_capacity(13); + header.extend_from_slice(&width.to_be_bytes()); + header.extend_from_slice(&height.to_be_bytes()); + // 8 bits per channel, RGBA, deflate, adaptive filtering, no interlace. + header.extend_from_slice(&[8, 6, 0, 0, 0]); + chunk(&mut png, b"IHDR", &header); + chunk(&mut png, b"IDAT", &zlib); + chunk(&mut png, b"IEND", &[]); + png +} + +/// Build the deterministic showcase workspace: one page exercising every Page-mode block, +/// its image blob, and one remote collaborator with a text selection. +pub fn seed_showcase_doc() -> DocResult { + const CREATED: i64 = 1_700_000_000_000; + const REFERENCED_PAGE: &str = "doc:edgeless-notes"; + const INTRO: &str = "This page is a y-octo document laid out by the native BlockFlow \ + renderer. Inline marks keep their styles: bold, italic, inline code, links, and page \ + references such as ."; + const INTRO_TAIL: &str = + " Remote carets and selections are drawn in each collaborator's color."; + + let mut state = DocState::new(SHOWCASE_ROOM, client_id_from_seed(0x4d32))?; + state.workspace.initialize_meta()?; + state + .workspace + .create_page(HOME_PAGE_ID, "Native BlockSuite Playground", CREATED)?; + state + .workspace + .create_page(REFERENCED_PAGE, "Edgeless notes", CREATED + 1)?; + + let page = state.workspace.ensure_page(HOME_PAGE_ID)?; + let mut seed = ShowcaseSeed { + page, + now_ms: 1_000, + }; + seed.add( + "showcase-page", + BlockSpec::Page { + title: "Native BlockSuite Playground".to_string(), + }, + None, + )?; + seed.add( + "showcase-surface", + BlockSpec::Surface, + Some("showcase-page"), + )?; + seed.add( + "showcase-note", + BlockSpec::Note { xywh: None }, + Some("showcase-page"), + )?; + let note = "showcase-note"; + + seed.paragraph("showcase-h1", ParagraphType::H1, "Page mode", note)?; + seed.paragraph("showcase-intro", ParagraphType::Text, INTRO, note)?; + seed.mark("showcase-intro", INTRO, "bold", "bold", Any::True)?; + seed.mark("showcase-intro", INTRO, "italic", "italic", Any::True)?; + seed.mark("showcase-intro", INTRO, "inline code", "code", Any::True)?; + seed.mark( + "showcase-intro", + INTRO, + "links", + "link", + Any::String("https://affine.pro".to_string()), + )?; + // A linked-page reference is a single placeholder character carrying the page id. + let reference_index = INTRO.encode_utf16().count() as u64 - 1; + let now_ms = seed.tick(); + seed.page + .insert_text("showcase-intro", "prop:text", reference_index, " ", now_ms)?; + let mut reference = AHashMap::default(); + reference.insert("type".to_string(), Any::String("LinkedPage".to_string())); + reference.insert( + "pageId".to_string(), + Any::String(REFERENCED_PAGE.to_string()), + ); + let mut attrs = TextAttributes::new(); + attrs.insert("reference".to_string(), Any::Object(Box::new(reference))); + let now_ms = seed.tick(); + seed.page.format_text( + "showcase-intro", + "prop:text", + reference_index, + 1, + attrs, + now_ms, + )?; + let now_ms = seed.tick(); + seed.page.insert_text( + "showcase-intro", + "prop:text", + reference_index + 2, + INTRO_TAIL, + now_ms, + )?; + + seed.paragraph("showcase-h2", ParagraphType::H2, "Blocks", note)?; + seed.paragraph( + "showcase-quote", + ParagraphType::Quote, + "Every block below comes from the same document the JavaScript editor edits.", + note, + )?; + + seed.list( + "showcase-bullet", + ListType::Bulleted, + "Bulleted list item", + false, + note, + )?; + seed.list( + "showcase-bullet-nested", + ListType::Bulleted, + "Nested item", + false, + "showcase-bullet", + )?; + seed.list( + "showcase-bullet-deep", + ListType::Bulleted, + "Third level", + false, + "showcase-bullet-nested", + )?; + seed.numbered("showcase-numbered-1", "First step", 1, note)?; + seed.numbered("showcase-numbered-2", "Second step", 2, note)?; + seed.numbered( + "showcase-numbered-nested", + "Sub-step", + 1, + "showcase-numbered-2", + )?; + seed.list( + "showcase-todo-open", + ListType::Todo, + "Render remote selections", + false, + note, + )?; + seed.list( + "showcase-todo-done", + ListType::Todo, + "Read the block tree", + true, + note, + )?; + seed.list( + "showcase-toggle-open", + ListType::Toggle, + "Toggle with details", + false, + note, + )?; + seed.paragraph( + "showcase-toggle-open-child", + ParagraphType::Text, + "Children stay visible while the toggle is open.", + "showcase-toggle-open", + )?; + seed.list( + "showcase-toggle-closed", + ListType::Toggle, + "Collapsed toggle", + false, + note, + )?; + seed.paragraph( + "showcase-toggle-closed-child", + ParagraphType::Text, + "Hidden until expanded.", + "showcase-toggle-closed", + )?; + let now_ms = seed.tick(); + seed.page.set_block_prop( + "showcase-toggle-closed", + "prop:collapsed", + SessionValue::Any(Any::True), + now_ms, + )?; + + seed.add("showcase-divider", BlockSpec::Divider, Some(note))?; + seed.add( + "showcase-code", + BlockSpec::Code { + text: "fn main() {\n println!(\"hello, blocks\");\n}".to_string(), + language: Some("rust".to_string()), + caption: String::new(), + }, + Some(note), + )?; + // Wrapped, so narrow windows show every character instead of clipping the long line. + let now_ms = seed.tick(); + seed.page.set_block_prop( + "showcase-code", + "prop:wrap", + SessionValue::Any(Any::True), + now_ms, + )?; + seed.add( + "showcase-bookmark", + BlockSpec::Bookmark { + url: "https://affine.pro/".to_string(), + title: Some("AFFiNE".to_string()), + description: Some( + "Open-source workspace for docs, whiteboards and databases.".to_string(), + ), + }, + Some(note), + )?; + seed.add( + "showcase-image", + BlockSpec::Image { + source_id: SHOWCASE_IMAGE_ID.to_string(), + caption: "A 64 \u{00d7} 40 gradient decoded from the blob store".to_string(), + width: 320.0, + height: 200.0, + xywh: None, + }, + Some(note), + )?; + let now_ms = seed.tick(); + seed.page.add_raw_block( + "showcase-database", + "affine:database", + 3, + vec![ + ( + "prop:title".to_string(), + SessionValue::Text(vec![y_octo::TextDeltaOp::Insert { + insert: y_octo::TextInsert::Text("Tasks".to_string()), + format: None, + }]), + ), + ("prop:views".to_string(), SessionValue::Array(Vec::new())), + ("prop:columns".to_string(), SessionValue::Array(Vec::new())), + ("prop:cells".to_string(), SessionValue::Map(Vec::new())), + ], + Some(note), + None, + now_ms, + )?; + + let image = showcase_gradient_png(); + if !image.is_empty() { + state + .blobs + .insert(SHOWCASE_IMAGE_ID.to_string(), Arc::new(image)); + } + + // One remote collaborator selecting the first words of the intro paragraph, which + // stay on its first line at every viewport width. + let mut peer = RoomAwareness::new(client_id_from_seed(0x0ada))?; + let mut payload = + AwarenessPayload::new(SHOWCASE_PEER_NAME, "var(--affine-multi-players-purple)"); + let selected = "y-octo document"; + let index = INTRO + .find(selected) + .map_or(0, |start| INTRO[..start].encode_utf16().count()); + payload.set_text_selection( + HOME_PAGE_ID, + TextSelectionState::range( + TextRangePoint { + block_id: "showcase-intro".to_string(), + index: index as u64, + length: selected.encode_utf16().count() as u64, + }, + None, + false, + ), + )?; + let update = peer.set_local_payload(&payload, 0)?; + state.awareness.apply_update(&update, 0)?; + + Ok(state) +} + +#[cfg(target_family = "wasm")] +fn web_options() -> PlaygroundOptions { + let mut options = PlaygroundOptions::default(); + let Some(window) = web_sys::window() else { + return options; + }; + let location = window.location(); + let Some(params) = location + .search() + .ok() + .and_then(|search| web_sys::UrlSearchParams::new_with_str(&search).ok()) + else { + return options; + }; + if let Some(theme) = params.get("theme").and_then(|v| PlaygroundTheme::parse(&v)) { + options.theme = theme; + } + if let Some(mode) = params.get("mode").and_then(|v| PlaygroundMode::parse(&v)) { + options.mode = mode; + } + if let Some(room) = params.get("room").filter(|room| !room.is_empty()) { + // `?ws=` names the relay; without it the page's own origin serves the room. + let relay = params.get("ws").filter(|ws| !ws.is_empty()).or_else(|| { + let protocol = location.protocol().ok()?; + let host = location.host().ok()?; + let scheme = if protocol == "https:" { "wss" } else { "ws" }; + Some(format!("{scheme}://{host}")) + }); + options.room = Some(RoomConfig::new(&room, relay.as_deref())); + } + options } #[cfg(target_family = "wasm")] @@ -312,10 +1627,11 @@ pub fn wasm_main() { let platform = std::rc::Rc::new(ui::WebPlatform::new(false)); ui::Application::with_platform(platform).run(|cx| { if let Err(err) = register_bundled_fonts(cx) { - panic!("failed to register bundled Inter font on web: {err:#}"); + panic!("failed to register bundled fonts on web: {err:#}"); } + let options = web_options(); if let Err(err) = cx.open_window(ui::WindowOptions::default(), |_, cx| { - cx.new(PlaygroundView::new) + cx.new(|cx| PlaygroundView::with_options(options, cx)) }) { panic!("failed to open playground web window: {err:#}"); } @@ -325,95 +1641,189 @@ pub fn wasm_main() { #[cfg(test)] mod tests { use super::*; + use crate::{ + block_flow::{ + BOOKMARK_HEIGHT, CHILD_INDENT, CODE_PADDING, CODE_RADIUS, DIVIDER_HEIGHT, FlowKind, + FlowTextLayout, LIST_PREFIX_WIDTH, QUOTE_BAR_WIDTH, QUOTE_PADDING, TITLE_PADDING_Y, + TITLE_SPEC, paragraph_spec, + }, + room_client::RoomFrame, + theme::{TYPOGRAPHY, tokens}, + }; + use blocksuite_playground_doc::{ + room::RoomHub, + session::WorkspaceSession, + wire::{ + DocMessage, DocSyncState, RoomBinaryFrame, RoomControlFrame, decode_binary_frame, + decode_control_frame, encode_binary_frame, + }, + }; + use futures_util::{SinkExt, StreamExt}; use std::cell::RefCell; - use std::rc::Rc; - use std::time::Duration; - use ui::{Application, Bounds, HeadlessPlatform, WindowBounds, WindowOptions, point, size}; + use tokio_tungstenite::{connect_async, tungstenite::Message as WsMessage}; + use ui::{ + Application, ApplicationHandle, FrameSnapshot, HeadlessPlatform, HeadlessWindow, + WindowBounds, WindowHandle, WindowOptions, audit_frame_snapshot, + }; - #[test] - fn headless_playground_renders_and_clicking_edgeless_mutates_snapshot_and_image() { - let platform = HeadlessPlatform::new(1280, 800, 1.0); - let handle_cell: Rc>>> = + struct Session { + platform: Rc, + app: ApplicationHandle, + window: WindowHandle, + headless: HeadlessWindow, + } + + fn open(width: u32, height: u32, options: PlaygroundOptions) -> Session { + let platform = HeadlessPlatform::new(width, height, 1.0); + let handle_cell: Rc>>> = Rc::new(RefCell::new(None)); let handle_out = handle_cell.clone(); - let app = Application::with_platform(platform.clone()).run_embedded(move |cx| { - register_bundled_fonts(cx).expect("register bundled Inter font"); - let window_handle = cx + register_bundled_fonts(cx).expect("register bundled fonts"); + let window = cx .open_window( WindowOptions { window_bounds: Some(WindowBounds::Windowed(Bounds::new( point(px(0.0), px(0.0)), - size(px(1280.0), px(800.0)), + size(px(width as f32), px(height as f32)), ))), ..WindowOptions::default() }, - |_, cx| cx.new(PlaygroundView::new), + |_, cx| cx.new(|cx| PlaygroundView::with_options(options, cx)), ) .expect("open headless window"); - *handle_out.borrow_mut() = Some(window_handle); + *handle_out.borrow_mut() = Some(window); }); - - let window_handle = handle_cell.borrow_mut().take().expect("window opened"); - let headless_win = platform + let window = handle_cell.borrow_mut().take().expect("window opened"); + let headless = platform .windows() .into_iter() .next() .expect("headless window registered"); + Session { + platform, + app, + window, + headless, + } + } - // Render initial Page frame via real GPUI Window::draw() - headless_win.request_frame(); - let (page_snap, page_img, page_glyphs) = app.update(|cx| { - window_handle + impl Session { + /// Draw a frame through the real `Window::draw()` and read it back. + fn frame(&self) -> (FrameSnapshot, image::RgbaImage) { + self.headless.request_frame(); + self.app.update(|cx| { + self.window + .update(cx, |_, window, _| { + let snapshot = window.frame_snapshot().clone(); + let image = window.render_to_image().expect("render frame"); + (snapshot, image) + }) + .expect("read frame") + }) + } + + fn view( + &self, + f: impl FnOnce(&mut PlaygroundView, &mut Context) -> R, + ) -> R { + self.app.update(|cx| { + self.window + .update(cx, |view, _, cx| f(view, cx)) + .expect("update view") + }) + } + + fn click(&self, snapshot: &FrameSnapshot, id: &str) { + let bounds = snapshot.elements[id].bounds; + self.headless.simulate_click(point( + px(bounds.x + bounds.width * 0.5), + px(bounds.y + bounds.height * 0.5), + )); + self.platform.run_until_parked(); + } + } + + fn assert_no_violations(snapshot: &FrameSnapshot, context: &str) { + let violations = audit_frame_snapshot(snapshot); + assert!(violations.is_empty(), "{context}: {violations:#?}"); + } + + fn pixel(image: &image::RgbaImage, x: f32, y: f32) -> [u8; 3] { + let pixel = image.get_pixel(x as u32, y as u32); + [pixel[0], pixel[1], pixel[2]] + } + + fn assert_color(actual: [u8; 3], expected: [u8; 3], what: &str) { + let close = actual + .iter() + .zip(expected) + .all(|(a, e)| (i32::from(*a) - i32::from(e)).abs() <= 2); + assert!(close, "{what}: rendered {actual:?}, expected {expected:?}"); + } + + fn token_rgb(color: tokens::Rgba) -> [u8; 3] { + [color.r, color.g, color.b] + } + + fn css_px(value: &serde_json::Value) -> f32 { + value + .as_str() + .and_then(|text| text.strip_suffix("px")) + .and_then(|number| number.parse().ok()) + .unwrap_or_else(|| panic!("not a px value: {value}")) + } + + /// Parse `rgb(r, g, b)`, `rgba(r, g, b, a)` or `#RRGGBB` as recorded by the oracle. + fn css_rgb(value: &serde_json::Value) -> [u8; 3] { + let text = value + .as_str() + .unwrap_or_else(|| panic!("not a color: {value}")); + if let Some(hex) = text.strip_prefix('#') { + let channel = |index: usize| u8::from_str_radix(&hex[index * 2..index * 2 + 2], 16); + return [ + channel(0).expect("hex color"), + channel(1).expect("hex color"), + channel(2).expect("hex color"), + ]; + } + let inner = text + .split_once('(') + .and_then(|(_, rest)| rest.strip_suffix(')')) + .unwrap_or_else(|| panic!("unsupported color: {text}")); + let mut channels = inner.split(',').map(|part| part.trim().parse::()); + let mut next = || channels.next().expect("channel").expect("number") as u8; + [next(), next(), next()] + } + + fn oracle() -> serde_json::Value { + serde_json::from_str(include_str!("../../../tokens/style-oracle.json")) + .expect("style oracle is valid JSON") + } + + #[test] + fn headless_playground_renders_and_clicking_edgeless_mutates_snapshot_and_image() { + let session = open(1280, 800, PlaygroundOptions::default()); + let (page_snap, page_img) = session.frame(); + let page_glyphs = session.app.update(|cx| { + session + .window .update(cx, |_, window, _| { - let snap = window.frame_snapshot().clone(); - let img = window.render_to_image().expect("render Page PNG"); - let glyphs = window.rendered_scene().monochrome_sprites.len(); - (snap, img, glyphs) + window.rendered_scene().monochrome_sprites.len() }) - .expect("read initial frame") + .expect("read scene") }); - assert!( page_glyphs > 50, "expected real shaped glyphs in initial frame, got {page_glyphs}" ); - let violations = ui::audit_frame_snapshot(&page_snap); - assert!( - violations.is_empty(), - "Page audit violations: {violations:#?}" - ); - - let edgeless_btn = page_snap - .elements - .get("chrome.mode_switcher.edgeless") - .expect("edgeless button in snapshot"); - let click_pt = point( - px(edgeless_btn.bounds.x + edgeless_btn.bounds.width * 0.5), - px(edgeless_btn.bounds.y + edgeless_btn.bounds.height * 0.5), - ); + assert_no_violations(&page_snap, "Page"); // Dispatch real click on Edgeless and step scheduler past 200ms transition - headless_win.simulate_click(click_pt); - platform.run_until_parked(); - platform.advance_clock(Duration::from_millis(250)); - headless_win.request_frame(); - - let (edgeless_snap, edgeless_img) = app.update(|cx| { - window_handle - .update(cx, |_, window, _| { - let snap = window.frame_snapshot().clone(); - let img = window.render_to_image().expect("render Edgeless PNG"); - (snap, img) - }) - .expect("read edgeless frame") - }); - - let violations = ui::audit_frame_snapshot(&edgeless_snap); - assert!( - violations.is_empty(), - "Edgeless audit violations: {violations:#?}" - ); + session.click(&page_snap, "chrome.mode_switcher.edgeless"); + session.platform.advance_clock(Duration::from_millis(250)); + let (edgeless_snap, edgeless_img) = session.frame(); + assert_no_violations(&edgeless_snap, "Edgeless"); let page_ind_x = page_snap.elements["chrome.mode_switcher.indicator"] .bounds @@ -427,6 +1837,10 @@ mod tests { ); assert!(edgeless_snap.elements["chrome.mode_switcher.edgeless"].focused); assert!(!edgeless_snap.elements["chrome.mode_switcher.page"].focused); + assert_eq!( + page_snap.elements["page.title_block"].text.as_deref(), + Some("Native BlockSuite Playground") + ); assert_ne!( page_snap.elements["page.title_block"].text, edgeless_snap.elements["page.title_block"].text @@ -447,14 +1861,14 @@ mod tests { let font_size = px(24.0); let app = Application::with_platform(platform.clone()).run_embedded(move |cx| { - register_bundled_fonts(cx).expect("register bundled Inter font"); + register_bundled_fonts(cx).expect("register bundled fonts"); }); - let (width_400, ink_400, width_700, ink_700) = app.update(|cx| { + let (width_400, ink_400, width_700, ink_700, mono_width) = app.update(|cx| { let platform_ts = platform.text_system(); - let measure = |weight: FontWeight| -> (f32, u64) { - let mut font = ui::font("Inter"); + let measure = |family: &'static str, weight: FontWeight| -> (f32, u64) { + let mut font = ui::font(family); font.weight = weight; let font_id = cx.text_system().resolve_font(&font); let layout = platform_ts.layout_line( @@ -492,9 +1906,10 @@ mod tests { (f32::from(layout.width), ink) }; - let (w400, i400) = measure(FontWeight::NORMAL); - let (w700, i700) = measure(FontWeight::BOLD); - (w400, i400, w700, i700) + let (w400, i400) = measure(FONT_SANS, FontWeight::NORMAL); + let (w700, i700) = measure(FONT_SANS, FontWeight::BOLD); + let (mono, _) = measure(theme::FONT_CODE, FontWeight::NORMAL); + (w400, i400, w700, i700, mono) }); assert!( @@ -505,5 +1920,1709 @@ mod tests { ink_700 * 100 > ink_400 * 115, "expected Bold (700) rasterized ink > 1.15x Regular (400): bold={ink_700}, regular={ink_400}" ); + // IBM Plex Mono is registered: every glyph advances exactly 0.6em. + let expected_mono = text.chars().count() as f32 * 24.0 * 0.6; + assert!( + (mono_width - expected_mono).abs() < 1.0, + "expected monospace advance {expected_mono}, got {mono_width}" + ); + } + + #[test] + fn showcase_covers_every_block_kind_with_zero_violations_across_themes_and_viewports() { + for (width, height) in [(1280_u32, 1700_u32), (800, 1900), (390, 2800), (320, 3600)] { + for theme in [PlaygroundTheme::Light, PlaygroundTheme::Dark] { + let context = format!("{width}x{height} {}", theme.as_str()); + let session = open( + width, + height, + PlaygroundOptions { + theme, + ..PlaygroundOptions::default() + }, + ); + let (snapshot, _) = session.frame(); + assert_no_violations(&snapshot, &context); + + let layout = session.view(|view, _| view.flow_layout().expect("page layout")); + assert!( + layout.height <= height as f32 - TOPBAR_HEIGHT, + "{context}: page is {} tall; raise the test viewport", + layout.height + ); + for kind in [ + FlowKind::Title, + FlowKind::Paragraph(ParagraphType::H1), + FlowKind::Paragraph(ParagraphType::H2), + FlowKind::Paragraph(ParagraphType::Text), + FlowKind::Paragraph(ParagraphType::Quote), + FlowKind::List(ListType::Bulleted), + FlowKind::List(ListType::Numbered), + FlowKind::List(ListType::Todo), + FlowKind::List(ListType::Toggle), + FlowKind::Divider, + FlowKind::Code, + FlowKind::Bookmark, + FlowKind::Image, + FlowKind::Unknown, + ] { + assert!( + layout.blocks.iter().any(|block| block.body.kind == kind), + "{context}: no {kind:?} block laid out" + ); + } + + let column = page_geometry(width as f32); + for block in &layout.blocks { + // Every block is on the pixel grid, inside the column, and recorded. + let element = snapshot + .elements + .get(block.snapshot_id.as_ref()) + .unwrap_or_else(|| panic!("{context}: {} not recorded", block.snapshot_id)); + assert!( + element.bounds.x >= column.column_x + && element.bounds.right() <= column.column_x + column.column_width, + "{context}: {} overflows the column: {:?}", + block.snapshot_id, + element.bounds + ); + // Wrapped text never extends past its block. + if let Some(text) = &block.body.text { + assert!( + text.x + text.layout.content_width() <= block.body.width + 0.5, + "{context}: text of {} is {} wide in a {} wide block", + block.snapshot_id, + text.x + text.layout.content_width(), + block.body.width + ); + } + } + assert_eq!( + snapshot.elements["page.block.showcase-database"] + .text + .as_deref(), + Some("[Unsupported block: affine:database]") + ); + // The image blob decoded: the block shows the picture, not the loading frame. + assert_ne!( + snapshot.elements["page.block.showcase-image"] + .text + .as_deref(), + Some("Loading image") + ); + } + } + } + + /// Title, every heading, a paragraph, a quote, a three-line code block and a divider. + fn oracle_document() -> DocState { + let mut state = DocState::new("oracle", client_id_from_seed(0x0c1e)).expect("state"); + state.workspace.initialize_meta().expect("meta"); + state + .workspace + .create_page(HOME_PAGE_ID, "Oracle", 1) + .expect("page"); + let page = state.workspace.ensure_page(HOME_PAGE_ID).expect("page"); + let mut seed = ShowcaseSeed { page, now_ms: 0 }; + seed.add( + "o-page", + BlockSpec::Page { + title: "Oracle".to_string(), + }, + None, + ) + .expect("page block"); + seed.add("o-note", BlockSpec::Note { xywh: None }, Some("o-page")) + .expect("note"); + for (id, kind, text) in [ + ("o-h1", ParagraphType::H1, "Heading 1"), + ("o-h2", ParagraphType::H2, "Heading 2"), + ("o-h3", ParagraphType::H3, "Heading 3"), + ("o-h4", ParagraphType::H4, "Heading 4"), + ("o-h5", ParagraphType::H5, "Heading 5"), + ("o-h6", ParagraphType::H6, "Heading 6"), + ("o-text", ParagraphType::Text, "Paragraph"), + ("o-quote", ParagraphType::Quote, "Quote"), + ] { + seed.paragraph(id, kind, text, "o-note").expect("paragraph"); + } + seed.add( + "o-code", + BlockSpec::Code { + text: "one\ntwo\nthree".to_string(), + language: Some("rust".to_string()), + caption: String::new(), + }, + Some("o-note"), + ) + .expect("code"); + seed.add("o-divider", BlockSpec::Divider, Some("o-note")) + .expect("divider"); + state + } + + #[test] + fn tokens_and_block_metrics_match_the_style_oracle_in_light_and_dark() { + let oracle = oracle(); + let mut light_geometry: Vec<(String, ui::SnapshotRect)> = Vec::new(); + + for theme in [PlaygroundTheme::Light, PlaygroundTheme::Dark] { + let name = theme.as_str(); + let themed = &oracle["themes"][name]; + let vars = &themed["root_css_vars"]; + let blocks = &themed["page_blocks"]; + let inline = &themed["inline_formats"]; + let tokens = theme.tokens(); + + // L1: generated tokens against the browser's resolved CSS variables. + for (token, var) in [ + (tokens.text_primary, "--affine-text-primary-color"), + (tokens.text_secondary, "--affine-text-secondary-color"), + ( + tokens.background_primary, + "--affine-background-primary-color", + ), + ( + tokens.background_code_block, + "--affine-background-code-block", + ), + (tokens.divider, "--affine-divider-color"), + (tokens.quote, "--affine-quote-color"), + (tokens.link, "--affine-link-color"), + ] { + assert_eq!(token_rgb(token), css_rgb(&vars[var]), "{name} {var}"); + } + for (value, var) in [ + (TYPOGRAPHY.font_base_px, "--affine-font-base"), + (TYPOGRAPHY.font_sm_px, "--affine-font-sm"), + (TYPOGRAPHY.font_xs_px, "--affine-font-xs"), + (TYPOGRAPHY.font_h1_px, "--affine-font-h-1"), + (TYPOGRAPHY.font_h2_px, "--affine-font-h-2"), + (TYPOGRAPHY.font_h3_px, "--affine-font-h-3"), + (TYPOGRAPHY.font_h4_px, "--affine-font-h-4"), + (TYPOGRAPHY.font_h5_px, "--affine-font-h-5"), + (TYPOGRAPHY.font_h6_px, "--affine-font-h-6"), + (block_flow::EDITOR_WIDTH, "--affine-editor-width"), + (TYPOGRAPHY.paragraph_space_px, "--affine-paragraph-space"), + ] { + assert_eq!(value, css_px(&vars[var]), "{name} {var}"); + } + + // L1: typography and box metrics of each block against computed styles. + let title = &blocks["page_title"]["computed"]; + assert_eq!(TITLE_SPEC.font_size, css_px(&title["font_size"])); + assert_eq!(TITLE_SPEC.line_height, css_px(&title["line_height"])); + assert_eq!(TITLE_SPEC.font_weight.to_string(), title["font_weight"]); + assert_eq!(title["letter_spacing"], "normal"); + assert_eq!(TITLE_SPEC.letter_spacing, 0.0); + // The browser reports a baseline one pixel apart between its two theme passes; + // the light pass is the reference. + let baseline_slack = if theme == PlaygroundTheme::Light { + 0.0 + } else { + 1.0 + }; + let title_baseline = blocks["page_title"]["baseline_offset_px"].as_f64().unwrap(); + assert!( + (TITLE_SPEC.baseline - title_baseline as f32).abs() <= baseline_slack, + "{name} title baseline {title_baseline}" + ); + assert_eq!( + token_rgb(tokens.text_primary), + css_rgb(&title["color"]), + "{name} title color" + ); + for (key, kind) in [ + ("h1", ParagraphType::H1), + ("h2", ParagraphType::H2), + ("h3", ParagraphType::H3), + ("h4", ParagraphType::H4), + ("h5", ParagraphType::H5), + ("h6", ParagraphType::H6), + ("paragraph_rich", ParagraphType::Text), + ("quote", ParagraphType::Quote), + ] { + let computed = &blocks[key]["computed"]; + let spec = paragraph_spec(kind); + assert_eq!(spec.font_size, css_px(&computed["font_size"]), "{key} size"); + assert_eq!( + spec.font_weight.to_string(), + computed["font_weight"], + "{key} weight" + ); + assert_eq!( + spec.line_height, + css_px(&computed["line_height"]), + "{key} line height" + ); + // The wrapper margin collapses with the block container's 10px margin. + assert_eq!( + spec.margin_top, + css_px(&computed["margin_top"]).max(block_flow::TEXT_BLOCK_MARGIN), + "{key} margin top" + ); + assert_eq!( + spec.margin_bottom, + css_px(&computed["margin_bottom"]).max(block_flow::TEXT_BLOCK_MARGIN), + "{key} margin bottom" + ); + let letter_spacing = match computed["letter_spacing"].as_str() { + Some("normal") => 0.0, + _ => css_px(&computed["letter_spacing"]), + }; + assert_eq!(spec.letter_spacing, letter_spacing, "{key} letter spacing"); + // Measured from the top of the wrapper, so below its top padding. + let baseline = blocks[key]["baseline_offset_px"].as_f64().unwrap() as f32 + - css_px(&computed["padding_top"]); + assert!( + (spec.baseline - baseline).abs() <= baseline_slack, + "{name} {key} baseline {baseline} vs {}", + spec.baseline + ); + assert_eq!( + token_rgb(tokens.text_primary), + css_rgb(&computed["color"]), + "{name} {key} color" + ); + } + let quote = &blocks["quote"]["computed"]; + assert_eq!(QUOTE_PADDING.0, css_px("e["padding_left"])); + assert_eq!(QUOTE_PADDING.1, css_px("e["padding_top"])); + assert_eq!(QUOTE_PADDING.2, css_px("e["padding_bottom"])); + let bar = &themed["quote_accent_bar"]; + assert_eq!(QUOTE_BAR_WIDTH, css_px(&bar["width"])); + assert_eq!(QUOTE_PADDING.1, css_px(&bar["margin_top"])); + assert_eq!(token_rgb(tokens.quote), css_rgb(&bar["background_color"])); + + let code = &blocks["code"]["computed"]; + assert_eq!(CODE_PADDING.0, css_px(&code["padding_top"])); + assert_eq!(CODE_PADDING.0, css_px(&code["padding_bottom"])); + assert_eq!(CODE_PADDING.1, css_px(&code["padding_left"])); + assert_eq!(CODE_PADDING.1, css_px(&code["padding_right"])); + assert_eq!(CODE_RADIUS, css_px(&code["border_radius"])); + assert_eq!( + token_rgb(tokens.background_code_block), + css_rgb(&code["background_color"]) + ); + let code_text = &blocks["code_inline_editor"]["computed"]; + assert_eq!(TYPOGRAPHY.font_xs_px, css_px(&code_text["font_size"])); + assert_eq!( + TYPOGRAPHY.font_xs_px + 8.0, + css_px(&code_text["line_height"]) + ); + assert!( + code_text["font_family"] + .as_str() + .is_some_and(|family| family.starts_with("\"IBM Plex Mono\"")), + "code font family" + ); + + let divider = &blocks["divider"]; + assert_eq!(DIVIDER_HEIGHT, divider["rect"]["height"]); + assert_eq!( + TYPOGRAPHY.paragraph_space_px, + css_px(÷r["computed"]["margin_top"]) + ); + assert_eq!( + token_rgb(tokens.divider), + css_rgb(&blocks["divider_hr"]["computed"]["border_top_color"]) + ); + + let palette = theme.palette(); + let bookmark = &blocks["bookmark"]; + assert_eq!(BOOKMARK_HEIGHT, bookmark["rect"]["height"]); + assert_eq!( + Some(palette.card_border), + theme.css_color(&format!( + "#{:02x}{:02x}{:02x}", + css_rgb(&bookmark["computed"]["border_top_color"])[0], + css_rgb(&bookmark["computed"]["border_top_color"])[1], + css_rgb(&bookmark["computed"]["border_top_color"])[2], + )), + "{name} bookmark border" + ); + let inline_code = &inline["inline_code"]["computed"]; + assert_eq!( + TYPOGRAPHY.font_base_px - 3.0, + css_px(&inline_code["font_size"]) + ); + assert_eq!( + token_rgb(tokens.background_code_block), + css_rgb(&inline_code["background_color"]) + ); + assert_eq!( + token_rgb(tokens.border), + css_rgb(&inline_code["border_top_color"]) + ); + assert_eq!( + token_rgb(tokens.link), + css_rgb(&inline["link"]["computed"]["color"]) + ); + + // L2: the rendered frame against the oracle's layout rectangles. + let session = open( + 1280, + 1400, + PlaygroundOptions { + theme, + ..PlaygroundOptions::default() + }, + ); + session.view(|view, cx| view.set_document(oracle_document(), cx)); + let (snapshot, image) = session.frame(); + assert_no_violations(&snapshot, name); + + let column = page_geometry(1280.0); + let title = snapshot.elements["page.title_block"].bounds; + assert_eq!(title.x, column.column_x); + assert_eq!(title.y, TOPBAR_HEIGHT + TITLE_PADDING_Y); + assert_eq!(title.width, blocks["page_title"]["rect"]["width"]); + assert_eq!(title.height, blocks["page_title"]["rect"]["height"]); + let note_top = title.bottom() + TITLE_PADDING_Y; + + let light_blocks = &oracle["themes"]["light"]["page_blocks"]; + let mut geometry = Vec::new(); + for (id, key) in [ + ("o-h1", "h1"), + ("o-h2", "h2"), + ("o-h3", "h3"), + ("o-h4", "h4"), + ("o-h5", "h5"), + ("o-h6", "h6"), + ("o-text", "paragraph_rich"), + ("o-quote", "quote"), + ] { + let bounds = snapshot.elements[&format!("page.block.{id}")].bounds; + // Plain single-line blocks stack exactly like the light oracle page. + let rect = &light_blocks[key]["rect"]; + assert_eq!(bounds.x - column.column_x, rect["x"], "{name} {id} x"); + assert_eq!(bounds.y - note_top, rect["y"], "{name} {id} y"); + assert_eq!(bounds.width, rect["width"], "{name} {id} width"); + assert_eq!(bounds.height, rect["height"], "{name} {id} height"); + // The dark oracle paragraph holds taller inline content; headings and the + // quote match the themed oracle as well. + if key != "paragraph_rich" { + assert_eq!(bounds.height, blocks[key]["rect"]["height"], "{name} {id}"); + } + geometry.push((id.to_string(), bounds)); + } + let quote = snapshot.elements["page.block.o-quote"].bounds; + let code = snapshot.elements["page.block.o-code"].bounds; + let divider = snapshot.elements["page.block.o-divider"].bounds; + assert_eq!(code.y, quote.bottom() + block_flow::CARD_BLOCK_MARGIN); + assert_eq!(code.height, blocks["code"]["rect"]["height"]); + assert_eq!(code.width, blocks["code"]["rect"]["width"]); + // Code's 18px bottom margin wins over the divider's 8px top margin. + assert_eq!(divider.y, code.bottom() + block_flow::CARD_BLOCK_MARGIN); + assert_eq!(divider.height, DIVIDER_HEIGHT); + geometry.push(("o-code".to_string(), code)); + geometry.push(("o-divider".to_string(), divider)); + + // Painted pixels carry the oracle colors. + assert_color( + pixel(&image, 20.0, 600.0), + token_rgb(tokens.background_primary), + "page background", + ); + assert_color( + pixel(&image, code.x + 300.0, code.y + 6.0), + token_rgb(tokens.background_code_block), + "code block background", + ); + assert_color( + pixel(&image, divider.x + 100.0, divider.y + DIVIDER_HEIGHT / 2.0), + token_rgb(tokens.divider), + "divider line", + ); + assert_color( + pixel(&image, quote.x, quote.y + 20.0), + token_rgb(tokens.quote), + "quote accent bar", + ); + + // Switching the theme recolors the page without moving a block. + if theme == PlaygroundTheme::Light { + light_geometry = geometry; + } else { + assert_eq!(light_geometry, geometry); + } + } + } + + #[test] + fn list_prefixes_sit_on_the_first_line_and_children_indent_and_collapse() { + let long = "wraps onto a second line because it carries far more words than \ + one row of the page column can hold at its regular width, even on a wide window"; + let mut state = DocState::new("lists", client_id_from_seed(0x1157)).expect("state"); + state.workspace.initialize_meta().expect("meta"); + state + .workspace + .create_page(HOME_PAGE_ID, "Lists", 1) + .expect("page"); + { + let page = state.workspace.ensure_page(HOME_PAGE_ID).expect("page"); + let mut seed = ShowcaseSeed { page, now_ms: 0 }; + seed.add( + "l-page", + BlockSpec::Page { + title: "Lists".to_string(), + }, + None, + ) + .expect("page block"); + seed.add("l-note", BlockSpec::Note { xywh: None }, Some("l-page")) + .expect("note"); + for (id, kind) in [ + ("l-bullet", ListType::Bulleted), + ("l-number", ListType::Numbered), + ("l-todo", ListType::Todo), + ("l-toggle", ListType::Toggle), + ] { + seed.list(id, kind, &format!("{kind:?} item {long}"), false, "l-note") + .expect("list"); + } + } + + let session = open(1280, 900, PlaygroundOptions::default()); + session.view(|view, cx| view.set_document(state, cx)); + let (snapshot, _) = session.frame(); + assert_no_violations(&snapshot, "lists"); + let layout = session.view(|view, _| view.flow_layout().expect("layout")); + for id in ["l-bullet", "l-number", "l-todo", "l-toggle"] { + let body = &layout.block(id).expect("list block").body; + let text = body.text.as_ref().expect("list text"); + assert!(text.layout.line_count() >= 2, "{id} should wrap"); + assert_eq!(body.height, text.layout.height(), "{id} height"); + let prefix = body.prefix.expect("list prefix"); + let first_line_center = text.layout.line_height() / 2.0; + let prefix_center = prefix.y + prefix.h / 2.0; + assert!( + (prefix_center - first_line_center).abs() <= 1.0, + "{id} prefix center {prefix_center} is off the first line center {first_line_center}" + ); + assert!( + prefix.right() <= text.x, + "{id} prefix overlaps the text column" + ); + } + + // The showcase nests lists, keeps an open toggle's child and hides a collapsed one. + let session = open(1280, 1700, PlaygroundOptions::default()); + session.frame(); + let layout = session.view(|view, _| view.flow_layout().expect("layout")); + let block = |id: &str| layout.block(id).unwrap_or_else(|| panic!("{id} laid out")); + assert_eq!(block("showcase-bullet").x, 0.0); + assert_eq!(block("showcase-bullet-nested").x, CHILD_INDENT); + assert_eq!(block("showcase-bullet-deep").x, 2.0 * CHILD_INDENT); + assert_eq!(block("showcase-toggle-open-child").x, CHILD_INDENT); + assert!(layout.block("showcase-toggle-closed-child").is_none()); + // Sibling margins collapse to a single 10px gap, also after nested children. + let gap = |above: &str, below: &str| block(below).y - block(above).rect().bottom(); + assert_eq!(gap("showcase-bullet", "showcase-bullet-nested"), 10.0); + assert_eq!(gap("showcase-bullet-deep", "showcase-numbered-1"), 10.0); + assert_eq!(gap("showcase-toggle-closed", "showcase-divider"), 10.0); + assert_eq!(gap("showcase-divider", "showcase-code"), 18.0); + assert_eq!(gap("showcase-code", "showcase-bookmark"), 18.0); + } + + #[test] + fn editing_one_block_lays_out_only_that_block_again() { + let session = open(1280, 800, PlaygroundOptions::default()); + session.frame(); + let first = session.view(|view, _| view.flow_layout().expect("layout")); + assert_eq!(first.stats.laid_out, first.blocks.len()); + assert_eq!(first.stats.reused, 0); + + session.view(|view, cx| { + view.edit_document(cx, |state| { + state + .workspace + .page_mut(HOME_PAGE_ID) + .expect("showcase page") + .insert_text("showcase-quote", "prop:text", 0, "Edited. ", 900_000) + .expect("insert text"); + }); + }); + let (snapshot, _) = session.frame(); + let second = session.view(|view, _| view.flow_layout().expect("layout")); + assert_eq!(second.blocks.len(), first.blocks.len()); + assert_eq!( + second.stats.laid_out, 1, + "only the edited quote is laid out" + ); + assert_eq!(second.stats.reused, first.blocks.len() - 1); + assert!( + snapshot.elements["page.block.showcase-quote"] + .text + .as_deref() + .is_some_and(|text| text.starts_with("Edited. ")) + ); + } + + #[test] + fn theme_toggle_and_remote_presence_render_in_chrome_and_page() { + let peer = client_id_from_seed(0x0ada); + let session = open(1280, 800, PlaygroundOptions::default()); + let (light, light_image) = session.frame(); + assert_no_violations(&light, "light"); + assert_eq!( + light.elements["chrome.theme_toggle"].text.as_deref(), + Some("Light") + ); + assert_color( + pixel(&light_image, 20.0, 400.0), + token_rgb(tokens::LIGHT_THEME.background_primary), + "light page background", + ); + + // The collaborator shows as a badge in the top bar and as caret + name tag in the page. + let badge = &light.elements[&format!("chrome.presence.{peer}")]; + assert_eq!(badge.text.as_deref(), Some(SHOWCASE_PEER_NAME)); + let caret = light.elements[&format!("page.presence.{peer}.caret")].bounds; + let label = &light.elements[&format!("page.presence.{peer}.label")]; + assert_eq!(label.text.as_deref(), Some(SHOWCASE_PEER_NAME)); + let intro = light.elements["page.block.showcase-intro"].bounds; + assert!(caret.x >= intro.x && caret.right() <= intro.right()); + assert!(caret.y >= intro.y && caret.bottom() <= intro.bottom()); + assert_eq!( + label.bounds.bottom(), + caret.y, + "name tag hangs above the caret" + ); + assert!(label.bounds.x >= intro.x && label.bounds.right() <= intro.right()); + // The caret is painted in the collaborator's color. + let purple = tokens::LIGHT_THEME + .color("--affine-multi-players-purple") + .expect("presence color token"); + assert_color( + pixel(&light_image, caret.x, caret.y + caret.height / 2.0), + token_rgb(purple), + "remote caret", + ); + + session.click(&light, "chrome.theme_toggle"); + let (dark, dark_image) = session.frame(); + assert_no_violations(&dark, "dark"); + assert_eq!(session.view(|view, _| view.theme()), PlaygroundTheme::Dark); + assert_eq!( + dark.elements["chrome.theme_toggle"].text.as_deref(), + Some("Dark") + ); + assert_color( + pixel(&dark_image, 20.0, 400.0), + token_rgb(tokens::DARK_THEME.background_primary), + "dark page background", + ); + // Same elements at the same places: only colors change with the theme. + assert_eq!( + light.elements.keys().collect::>(), + dark.elements.keys().collect::>() + ); + for (id, element) in &light.elements { + assert_eq!(element.bounds, dark.elements[id].bounds, "{id}"); + } + + // A narrow window keeps the badge as an initial and never overlaps the switcher. + let narrow = open(390, 800, PlaygroundOptions::default()); + let (snapshot, _) = narrow.frame(); + assert_no_violations(&snapshot, "narrow"); + let switcher = snapshot.elements["chrome.mode_switcher"].bounds; + let badge = snapshot.elements[&format!("chrome.presence.{peer}")].bounds; + let toggle = snapshot.elements["chrome.theme_toggle"].bounds; + assert!( + switcher.right() <= badge.x, + "badge overlaps the mode switcher" + ); + assert!(badge.right() <= toggle.x); + assert!(toggle.right() <= 390.0); + assert_eq!((badge.width, badge.height), (24.0, 24.0)); + } + + /// Content that stresses the layout: an empty title, a collapsed heading, an unbroken + /// long word, decorated inline runs, a hard break, images without usable bytes, a bare + /// bookmark, an empty code block, an Edgeless-only note and a second page note. + fn edge_document() -> DocState { + let mut state = DocState::new("edge", client_id_from_seed(0x0ed6)).expect("state"); + state.workspace.initialize_meta().expect("meta"); + state + .workspace + .create_page(HOME_PAGE_ID, "", 1) + .expect("page"); + state + .blobs + .insert("broken".to_string(), Arc::new(b"not an image".to_vec())); + let page = state.workspace.ensure_page(HOME_PAGE_ID).expect("page"); + let mut seed = ShowcaseSeed { page, now_ms: 0 }; + seed.add( + "e-page", + BlockSpec::Page { + title: String::new(), + }, + None, + ) + .expect("page block"); + seed.add("e-note", BlockSpec::Note { xywh: None }, Some("e-page")) + .expect("note"); + let note = "e-note"; + + seed.paragraph("e-collapsed", ParagraphType::H2, "Collapsed section", note) + .expect("heading"); + seed.paragraph( + "e-hidden-child", + ParagraphType::Text, + "Hidden child", + "e-collapsed", + ) + .expect("paragraph"); + seed.paragraph("e-hidden", ParagraphType::Text, "Hidden paragraph", note) + .expect("paragraph"); + seed.paragraph("e-hidden-h3", ParagraphType::H3, "Hidden subsection", note) + .expect("heading"); + seed.paragraph("e-next", ParagraphType::H2, "Next section", note) + .expect("heading"); + let now_ms = seed.tick(); + seed.page + .set_block_prop( + "e-collapsed", + "prop:collapsed", + SessionValue::Any(Any::True), + now_ms, + ) + .expect("collapse"); + + let long_word = format!( + "https://example.com/{}", + "a-very-long-path-segment/".repeat(12) + ); + seed.paragraph("e-long", ParagraphType::Text, &long_word, note) + .expect("paragraph"); + + let marks = "underlined struck highlighted colored plain"; + seed.paragraph("e-marks", ParagraphType::Text, marks, note) + .expect("paragraph"); + seed.mark("e-marks", marks, "underlined", "underline", Any::True) + .expect("mark"); + seed.mark("e-marks", marks, "struck", "strike", Any::True) + .expect("mark"); + seed.mark( + "e-marks", + marks, + "highlighted", + "background", + Any::String("var(--affine-text-highlight-orange)".to_string()), + ) + .expect("mark"); + seed.mark( + "e-marks", + marks, + "colored", + "color", + Any::String("var(--affine-text-highlight-foreground-blue)".to_string()), + ) + .expect("mark"); + + seed.paragraph("e-break", ParagraphType::Text, "line one\nline two", note) + .expect("paragraph"); + for (id, source) in [ + ("e-image-missing", "missing-blob"), + ("e-image-broken", "broken"), + ] { + seed.add( + id, + BlockSpec::Image { + source_id: source.to_string(), + caption: String::new(), + width: 300.0, + height: 120.0, + xywh: None, + }, + Some(note), + ) + .expect("image"); + } + seed.add( + "e-bookmark", + BlockSpec::Bookmark { + url: "https://example.org/some/path".to_string(), + title: None, + description: None, + }, + Some(note), + ) + .expect("bookmark"); + seed.add( + "e-code", + BlockSpec::Code { + text: String::new(), + language: None, + caption: "Empty listing".to_string(), + }, + Some(note), + ) + .expect("code"); + + seed.add( + "e-edgeless-note", + BlockSpec::Note { xywh: None }, + Some("e-page"), + ) + .expect("note"); + seed.paragraph( + "e-edgeless-text", + ParagraphType::Text, + "Only on the canvas", + "e-edgeless-note", + ) + .expect("paragraph"); + let now_ms = seed.tick(); + seed.page + .set_block_prop( + "e-edgeless-note", + "prop:displayMode", + SessionValue::Any(Any::String("edgeless".to_string())), + now_ms, + ) + .expect("display mode"); + seed.add( + "e-second-note", + BlockSpec::Note { xywh: None }, + Some("e-page"), + ) + .expect("note"); + seed.paragraph( + "e-second", + ParagraphType::Text, + "Second note", + "e-second-note", + ) + .expect("paragraph"); + state + } + + #[test] + fn edge_content_wraps_collapses_and_degrades_without_violations() { + for (width, theme) in [ + (1280_u32, PlaygroundTheme::Light), + (390, PlaygroundTheme::Dark), + ] { + let context = format!("{width} {}", theme.as_str()); + let session = open( + width, + 2000, + PlaygroundOptions { + theme, + ..PlaygroundOptions::default() + }, + ); + session.view(|view, cx| view.set_document(edge_document(), cx)); + let (snapshot, _) = session.frame(); + assert_no_violations(&snapshot, &context); + let layout = session.view(|view, _| view.flow_layout().expect("layout")); + let block = |id: &str| layout.block(id).unwrap_or_else(|| panic!("{id} laid out")); + let text_of = |id: &str| { + snapshot.elements[&format!("page.block.{id}")] + .text + .clone() + .unwrap_or_default() + }; + + // An empty title shows its placeholder. + assert_eq!( + snapshot.elements["page.title_block"].text.as_deref(), + Some("Title") + ); + // A collapsed heading hides its own children and what follows up to the next + // heading of its level. + assert!(layout.block("e-hidden-child").is_none(), "{context}"); + assert!(layout.block("e-hidden").is_none(), "{context}"); + let marker_x = snapshot.elements["page.block.e-collapsed"].bounds.x - 20.0; + assert!( + marker_x >= 0.0, + "{context}: collapse marker fits the side padding" + ); + assert!(layout.block("e-hidden-h3").is_none(), "{context}"); + assert_eq!(text_of("e-next"), "Next section"); + assert_eq!(block("e-next").x, 0.0); + assert_eq!( + block("e-next").y - block("e-collapsed").rect().bottom(), + paragraph_spec(ParagraphType::H2).margin_top + ); + + // A word wider than the column breaks inside the word instead of overflowing. + let long = block("e-long"); + let long_text = long.body.text.as_ref().expect("text"); + assert!(long_text.layout.line_count() >= 2, "{context}"); + assert!(long_text.layout.content_width() <= long.body.width + 0.5); + // A hard break starts a new line. + let broken = block("e-break").body.text.as_ref().expect("text"); + assert_eq!(broken.layout.line_count(), 2, "{context}"); + assert_eq!(block("e-marks").body.height, 23.0, "{context}"); + + // Images without usable bytes keep their frame and say why. + assert_eq!(text_of("e-image-missing"), "Loading image"); + assert_eq!(text_of("e-image-broken"), "Image unavailable"); + let frame_width = 300.0_f32.min(long.body.width); + assert_eq!( + block("e-image-missing").body.height, + (120.0 * frame_width / 300.0).round() + ); + // A bookmark without metadata falls back to its host name. + assert_eq!(text_of("e-bookmark"), "example.org"); + // An empty code block still has one line, plus its caption. + assert_eq!( + block("e-code").body.height, + 2.0 * CODE_PADDING.0 + 20.0 + 4.0 + 22.0 + ); + + // The Edgeless-only note is skipped; the next page note starts a fresh flow. + assert!(layout.block("e-edgeless-text").is_none(), "{context}"); + assert_eq!( + block("e-second").y, + block("e-code").rect().bottom() + + block_flow::CARD_BLOCK_MARGIN + + block_flow::TEXT_BLOCK_MARGIN + ); + } + } + + #[test] + fn scrolling_maps_world_space_onto_the_viewport_and_clamps_at_both_ends() { + let session = open(1280, 800, PlaygroundOptions::default()); + let (top, _) = session.frame(); + let scroll = |delta_y: f32| { + let position = point(px(640.0), px(400.0)); + session + .headless + .dispatch_input(ui::PlatformInput::MouseMove(ui::MouseMoveEvent { + position, + pressed_button: None, + modifiers: ui::Modifiers::default(), + })); + session + .headless + .dispatch_input(ui::PlatformInput::Scroll(ScrollEvent { + position, + delta: ui::ScrollDelta::Pixels(point(px(0.0), px(delta_y))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + session.platform.run_until_parked(); + }; + + // Scrolling moves every block by the same amount and nothing sideways. + scroll(-300.0); + let (scrolled, _) = session.frame(); + assert_no_violations(&scrolled, "scrolled"); + let before = top.elements["page.block.showcase-quote"].bounds; + let after = scrolled.elements["page.block.showcase-quote"].bounds; + assert_eq!((after.x, after.y), (before.x, before.y - 300.0)); + assert_eq!((after.width, after.height), (before.width, before.height)); + // Blocks that left the viewport stop recording; blocks that entered start. + assert!(top.elements.contains_key("page.title_block")); + assert!(!scrolled.elements.contains_key("page.title_block")); + assert!(!top.elements.contains_key("page.block.showcase-code")); + assert!(scrolled.elements.contains_key("page.block.showcase-code")); + + // The end of the page stops at the bottom padding. + scroll(-100_000.0); + let (bottom, _) = session.frame(); + assert_no_violations(&bottom, "bottom"); + let last = bottom.elements["page.block.showcase-database"].bounds; + assert_eq!( + last.bottom(), + 800.0 - block_flow::BOTTOM_PADDING - block_flow::CARD_BLOCK_MARGIN + ); + + scroll(100_000.0); + let (back, _) = session.frame(); + assert_eq!( + back.elements["page.title_block"].bounds, + top.elements["page.title_block"].bounds + ); + assert_eq!(back.elements.len(), top.elements.len()); + } + + type Socket = tokio_tungstenite::WebSocketStream< + tokio_tungstenite::MaybeTlsStream, + >; + + /// Run the full `Step1` / `Step2` / reverse `Step2` / `ready` handshake for one document. + async fn peer_sync(socket: &mut Socket, workspace: &mut WorkspaceSession, doc_id: &str) { + let mut state = DocSyncState::new(doc_id); + let step1 = state.begin_pull(workspace.encode_state_vector_v1(doc_id).unwrap()); + socket + .send(WsMessage::Binary( + encode_binary_frame(&step1).unwrap().into(), + )) + .await + .unwrap(); + let hub_sv = loop { + let WsMessage::Binary(bytes) = socket.next().await.unwrap().unwrap() else { + continue; + }; + match decode_binary_frame(&bytes).unwrap() { + RoomBinaryFrame::Doc { + doc_id: id, + message: DocMessage::Step2(diff), + } if id == doc_id => { + if !(diff.is_empty() || diff == [0, 0]) { + if doc_id == workspace.room() { + workspace.apply_root_update_v1(&diff).unwrap(); + } else { + workspace + .ensure_page(doc_id) + .unwrap() + .apply_remote_update_v1(&diff) + .unwrap(); + } + } + if let Some(sv) = state.on_hub_step2() { + break sv; + } + } + RoomBinaryFrame::Doc { + doc_id: id, + message: DocMessage::Step1(sv), + } if id == doc_id => { + if let Some(sv) = state.on_hub_step1(sv) { + break sv; + } + } + _ => {} + } + }; + let diff = workspace.encode_diff_v1(doc_id, &hub_sv).unwrap(); + let reverse = state.build_reverse_step2(diff); + socket + .send(WsMessage::Binary( + encode_binary_frame(&reverse).unwrap().into(), + )) + .await + .unwrap(); + loop { + if let WsMessage::Text(text) = socket.next().await.unwrap().unwrap() + && let Ok(RoomControlFrame::Ready { doc_id: id }) = decode_control_frame(&text) + && id == doc_id + { + break; + } + } + } + + /// Upload a blob to the relay with a bare HTTP/1.1 `PUT`. + async fn put_blob(url: &str, body: &[u8]) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let rest = url.strip_prefix("http://").expect("plain http blob url"); + let (authority, path) = rest.split_at(rest.find('/').expect("blob path")); + let mut stream = tokio::net::TcpStream::connect(authority).await.unwrap(); + let head = format!( + "PUT {path} HTTP/1.1\r\nHost: {authority}\r\nContent-Type: application/octet-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + stream.write_all(head.as_bytes()).await.unwrap(); + stream.write_all(body).await.unwrap(); + let mut response = Vec::new(); + stream.read_to_end(&mut response).await.unwrap(); + let response = String::from_utf8_lossy(&response); + assert!( + response.starts_with("HTTP/1.1 2"), + "blob upload failed: {response}" + ); + } + + /// Start an in-process relay on a free local port. + fn start_relay(runtime: &tokio::runtime::Runtime) -> std::net::SocketAddr { + runtime.block_on(async { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(listener, RoomHub::new().router()) + .await + .unwrap(); + }); + addr + }) + } + + fn relay_runtime() -> tokio::runtime::Runtime { + tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .expect("tokio runtime") + } + + /// A workspace with one page holding a title, a note and one paragraph (`p-1`). + fn relay_page_peer(room: &str, client_id: u64) -> WorkspaceSession { + let mut peer = WorkspaceSession::new(room, client_id).unwrap(); + peer.initialize_meta().unwrap(); + peer.create_page(HOME_PAGE_ID, "Relay Page", 1).unwrap(); + let page = peer.page_mut(HOME_PAGE_ID).unwrap(); + let mut seed = ShowcaseSeed { page, now_ms: 0 }; + seed.add( + "page", + BlockSpec::Page { + title: "Relay Page".to_string(), + }, + None, + ) + .unwrap(); + seed.add("note", BlockSpec::Note { xywh: None }, Some("page")) + .unwrap(); + seed.paragraph("p-1", ParagraphType::Text, "Hello from the relay", "note") + .unwrap(); + peer + } + + /// Connect a peer to the room and publish its root document and home page. + fn join_as_peer( + runtime: &tokio::runtime::Runtime, + addr: std::net::SocketAddr, + room: &str, + peer: &mut WorkspaceSession, + ) -> Socket { + runtime.block_on(async { + let url = format!("ws://{addr}/native-sync/rooms/{room}"); + let (mut socket, _) = connect_async(url.as_str()).await.unwrap(); + tokio::time::timeout(Duration::from_secs(10), async { + peer_sync(&mut socket, peer, room).await; + peer_sync(&mut socket, peer, HOME_PAGE_ID).await; + }) + .await + .expect("peer handshake"); + socket + }) + } + + async fn send_doc_update(socket: &mut Socket, update: Vec) { + let frame = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: HOME_PAGE_ID.to_string(), + message: DocMessage::Update(update), + }) + .unwrap(); + socket.send(WsMessage::Binary(frame.into())).await.unwrap(); + } + + /// Step the headless application until `done`, applying room events as they arrive. + fn wait_for(session: &Session, what: &str, done: impl Fn(&PlaygroundView) -> bool) { + for _ in 0..500 { + session.view(|view, cx| { + view.pump_room(cx); + }); + session.platform.run_until_parked(); + if session.view(|view, _| done(view)) { + return; + } + std::thread::sleep(Duration::from_millis(20)); + } + panic!("timed out waiting for {what}"); + } + + #[test] + fn live_room_sync_updates_the_frame_snapshot_in_light_and_dark() { + let runtime = relay_runtime(); + let addr = start_relay(&runtime); + + // A peer seeds the room over WebSocket before the view joins. + let room = "room-native-view"; + let peer_id = client_id_from_seed(77); + let mut peer = relay_page_peer(room, peer_id); + let mut socket = join_as_peer(&runtime, addr, room, &mut peer); + + let config = RoomConfig::new(room, Some(&format!("ws://{addr}"))); + let session = open( + 1280, + 800, + PlaygroundOptions { + room: Some(config.clone()), + ..PlaygroundOptions::default() + }, + ); + wait_for(&session, "the seeded page", |view| { + view.room_status() == Some(RoomStatus::Live) + && view + .page_snapshot() + .is_some_and(|snapshot| snapshot.block("p-1").is_some()) + }); + let (snapshot, _) = session.frame(); + assert_no_violations(&snapshot, "initial sync"); + assert_eq!( + snapshot.elements["page.title_block"].text.as_deref(), + Some("Relay Page") + ); + assert_eq!( + snapshot.elements["page.block.p-1"].text.as_deref(), + Some("Hello from the relay") + ); + assert!(!snapshot.elements.contains_key("page.block.p-2")); + + // The peer edits the page, uploads a blob, and announces its caret, all live. + let edit = { + let page = peer.page_mut(HOME_PAGE_ID).unwrap(); + let paragraph = page + .add_block( + "p-2", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Synced live edit".to_string(), + }, + Some("note"), + None, + 50_000, + ) + .unwrap() + .expect("paragraph commit"); + let image = page + .add_block( + "img", + BlockSpec::Image { + source_id: "img-1".to_string(), + caption: String::new(), + width: 64.0, + height: 40.0, + xywh: None, + }, + Some("note"), + None, + 51_000, + ) + .unwrap() + .expect("image commit"); + [paragraph.update, image.update] + }; + let mut awareness = RoomAwareness::new(peer_id).unwrap(); + let mut payload = AwarenessPayload::new("Rita", "var(--affine-multi-players-orange)"); + payload + .set_text_selection(HOME_PAGE_ID, TextSelectionState::caret("p-2", 6)) + .unwrap(); + let presence = awareness.set_local_payload(&payload, 0).unwrap(); + runtime.block_on(async { + put_blob(&config.blob_url("img-1"), &showcase_gradient_png()).await; + for update in edit { + send_doc_update(&mut socket, update).await; + } + let frame = encode_binary_frame(&RoomBinaryFrame::Awareness(presence)).unwrap(); + socket.send(WsMessage::Binary(frame.into())).await.unwrap(); + }); + + wait_for(&session, "the live edit, blob and presence", |view| { + view.page_snapshot() + .is_some_and(|snapshot| snapshot.block("img").is_some()) + && view.document().blobs.contains_key("img-1") + && view.document().awareness.get_payload(peer_id).is_some() + }); + let (light, light_image) = session.frame(); + assert_no_violations(&light, "live edit (light)"); + assert_eq!( + light.elements["page.block.p-2"].text.as_deref(), + Some("Synced live edit") + ); + assert_eq!( + light.elements[&format!("chrome.presence.{peer_id}")] + .text + .as_deref(), + Some("Rita") + ); + let caret = light.elements[&format!("page.presence.{peer_id}.caret")].bounds; + let paragraph = light.elements["page.block.p-2"].bounds; + assert!(caret.x > paragraph.x && caret.right() < paragraph.right()); + assert_eq!((caret.y, caret.height), (paragraph.y, paragraph.height)); + // The fetched blob is decoded and painted at the block's size. + let image_block = &light.elements["page.block.img"]; + assert_ne!(image_block.text.as_deref(), Some("Loading image")); + assert_eq!(image_block.bounds.height, 40.0); + + session.view(|view, cx| view.set_theme(PlaygroundTheme::Dark, cx)); + let (dark, dark_image) = session.frame(); + assert_no_violations(&dark, "live edit (dark)"); + assert_eq!( + dark.elements["page.block.p-2"].text.as_deref(), + Some("Synced live edit") + ); + assert_eq!( + light.elements.keys().collect::>(), + dark.elements.keys().collect::>() + ); + assert_ne!(light_image.as_raw(), dark_image.as_raw()); + assert_color( + pixel(&dark_image, 20.0, 600.0), + token_rgb(tokens::DARK_THEME.background_primary), + "dark page background", + ); + } + + #[test] + fn a_blob_uploaded_after_its_image_block_is_fetched_by_capped_retries() { + let runtime = relay_runtime(); + let addr = start_relay(&runtime); + let room = "room-late-blob"; + let source = "late-blob"; + + // The image block reaches the room before any blob does, as when the JavaScript + // editor writes `sourceId` while its upload is still running. + let mut peer = relay_page_peer(room, client_id_from_seed(91)); + peer.page_mut(HOME_PAGE_ID) + .unwrap() + .add_block( + "img", + BlockSpec::Image { + source_id: source.to_string(), + caption: String::new(), + width: 320.0, + height: 200.0, + xywh: None, + }, + Some("note"), + None, + 40_000, + ) + .unwrap(); + let mut socket = join_as_peer(&runtime, addr, room, &mut peer); + + let config = RoomConfig::new(room, Some(&format!("ws://{addr}"))); + let session = open( + 1280, + 800, + PlaygroundOptions { + room: Some(config.clone()), + ..PlaygroundOptions::default() + }, + ); + let fetch = |view: &PlaygroundView| view.blob_fetches.get(source).copied(); + let image_text = || { + let (snapshot, _) = session.frame(); + assert_no_violations(&snapshot, "late blob"); + snapshot.elements["page.block.img"].text.clone() + }; + wait_for(&session, "the first miss", |view| { + fetch(view).is_some_and(|fetch| !fetch.in_flight && fetch.misses == 1) + }); + assert_eq!(image_text().as_deref(), Some("Loading image")); + + // A peer edit re-reads the document without fetching the blob again. + let before = session.view(|view, _| fetch(view)); + let edit = peer + .page_mut(HOME_PAGE_ID) + .unwrap() + .add_block( + "p-2", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Typed while the upload runs".to_string(), + }, + Some("note"), + None, + 41_000, + ) + .unwrap() + .expect("paragraph commit"); + runtime.block_on(send_doc_update(&mut socket, edit.update)); + wait_for(&session, "the peer edit", |view| { + view.page_snapshot() + .is_some_and(|snapshot| snapshot.block("p-2").is_some()) + }); + assert_eq!(session.view(|view, _| fetch(view)), before); + + // Only the scheduler clock drives the retries: the gap doubles up to its cap and + // the fetch never gives up, with no edit or reconnect in between. + let step = |target: &dyn Fn(&PlaygroundView) -> bool, what: &str| { + for _ in 0..40 { + if session.view(|view, _| target(view)) { + return; + } + // One second of scheduler time runs the view's room tick once; a fetch it + // starts is answered by the relay before the clock moves again. + session.platform.advance_clock(Duration::from_secs(1)); + wait_for(&session, what, |view| { + target(view) || fetch(view).is_none_or(|fetch| !fetch.in_flight) + }); + } + panic!("timed out stepping the clock for {what}"); + }; + step( + &|view| fetch(view).is_some_and(|fetch| !fetch.in_flight && fetch.misses >= 3), + "the third miss", + ); + assert_eq!(image_text().as_deref(), Some("Image unavailable")); + step( + &|view| fetch(view).is_some_and(|fetch| !fetch.in_flight && fetch.misses >= 6), + "retries past the backoff cap", + ); + assert_eq!(image_text().as_deref(), Some("Image unavailable")); + assert_eq!( + [1, 2, 3, 4, 5, 6, 60].map(blob_retry_backoff_ms), + [500, 1_000, 2_000, 4_000, 4_000, 4_000, 4_000] + ); + + // The upload finishes late; the next retry picks the blob up and the image shows. + runtime.block_on(put_blob(&config.blob_url(source), &showcase_gradient_png())); + step( + &|view| view.document().blobs.contains_key(source), + "the uploaded blob", + ); + session.view(|view, _| { + assert!(matches!(view.images.get(source), Some(ImageSlot::Ready(_)))); + assert!(view.blob_fetches.is_empty()); + }); + let (snapshot, _) = session.frame(); + assert_no_violations(&snapshot, "late blob ready"); + let image = &snapshot.elements["page.block.img"]; + assert!( + !matches!( + image.text.as_deref(), + Some("Loading image" | "Image unavailable") + ), + "{:?}", + image.text + ); + assert_eq!(image.bounds.height, 200.0); + } + + #[test] + fn corrupt_and_supported_image_bytes_decode_once() { + // PNG is decoded; bytes that are no supported image are rejected for good. + assert!(decode_image(&showcase_gradient_png()).is_some()); + assert!(decode_image(b"not an image").is_none()); + assert!(decode_image(&[]).is_none()); + // Every supported container is recognized by its signature. + let mut image = image::RgbaImage::new(3, 2); + for (x, y, pixel) in image.enumerate_pixels_mut() { + *pixel = image::Rgba([x as u8 * 80, y as u8 * 120, 200, 255]); + } + for format in [ + image::ImageFormat::Png, + image::ImageFormat::Jpeg, + image::ImageFormat::WebP, + image::ImageFormat::Gif, + image::ImageFormat::Bmp, + ] { + let mut bytes = std::io::Cursor::new(Vec::new()); + let encoded = match format { + // JPEG has no alpha channel. + image::ImageFormat::Jpeg => image::DynamicImage::ImageRgba8(image.clone()) + .into_rgb8() + .write_to(&mut bytes, format), + _ => image.write_to(&mut bytes, format), + }; + encoded.unwrap_or_else(|err| panic!("{format:?}: {err}")); + let decoded = + decode_image(bytes.get_ref()).unwrap_or_else(|| panic!("{format:?} decodes")); + let size = decoded.size(0); + assert_eq!((size.width.0, size.height.0), (3, 2), "{format:?}"); + } + // An icon is a real image format, but not one a page image may use. + let mut icon = std::io::Cursor::new(Vec::new()); + image.write_to(&mut icon, image::ImageFormat::Ico).unwrap(); + assert!(decode_image(icon.get_ref()).is_none()); + } + + #[test] + fn reconnecting_presence_outranks_the_relay_tombstone() { + async fn send_frames(socket: &mut Socket, frames: Vec) { + for frame in frames { + let message = match frame { + RoomFrame::Binary(bytes) => WsMessage::Binary(bytes.into()), + RoomFrame::Text(text) => WsMessage::Text(text.into()), + }; + socket.send(message).await.unwrap(); + } + } + + /// Open the protocol on `socket` and run its handshakes until the room is live. + async fn open_protocol( + socket: &mut Socket, + protocol: &mut RoomProtocol, + state: &mut DocState, + ) { + let effects = protocol.on_open(state, 0).unwrap(); + send_frames(socket, effects.outbound).await; + while protocol.status() != RoomStatus::Live { + let frame = match socket.next().await.unwrap().unwrap() { + WsMessage::Binary(bytes) => RoomFrame::Binary(bytes.to_vec()), + WsMessage::Text(text) => RoomFrame::Text(text.to_string()), + _ => continue, + }; + let effects = protocol.on_frame(state, &frame, 0).unwrap(); + send_frames(socket, effects.outbound).await; + } + } + + /// Read awareness frames until `client` is present (or gone) for this observer. + async fn await_presence( + socket: &mut Socket, + awareness: &mut RoomAwareness, + client: u64, + present: bool, + ) { + while awareness.get_payload(client).is_some() != present { + if let WsMessage::Binary(bytes) = socket.next().await.unwrap().unwrap() + && let RoomBinaryFrame::Awareness(update) = decode_binary_frame(&bytes).unwrap() + { + awareness.apply_update(&update, 0).unwrap(); + } + } + } + + let runtime = relay_runtime(); + let addr = start_relay(&runtime); + let room = "room-reconnect"; + let url = format!("ws://{addr}/native-sync/rooms/{room}"); + let native = client_id_from_seed(5); + runtime.block_on(async { + tokio::time::timeout(Duration::from_secs(20), async { + let mut state = DocState::new(room, native).unwrap(); + let mut protocol = RoomProtocol::new(room); + let mut watcher_view = RoomAwareness::new(client_id_from_seed(6)).unwrap(); + let (mut watcher, _) = connect_async(url.as_str()).await.unwrap(); + + let (mut first, _) = connect_async(url.as_str()).await.unwrap(); + open_protocol(&mut first, &mut protocol, &mut state).await; + await_presence(&mut watcher, &mut watcher_view, native, true).await; + + // The connection drops: the relay tombstones the client one clock above + // its presence. + first.close(None).await.unwrap(); + drop(first); + protocol.on_close("connection lost"); + await_presence(&mut watcher, &mut watcher_view, native, false).await; + + // Reconnecting right away announces a presence the relay accepts ... + let (mut second, _) = connect_async(url.as_str()).await.unwrap(); + open_protocol(&mut second, &mut protocol, &mut state).await; + await_presence(&mut watcher, &mut watcher_view, native, true).await; + + // ... so an observer joining before any renewal sees it at once. + let mut fresh_view = RoomAwareness::new(client_id_from_seed(7)).unwrap(); + let (mut fresh, _) = connect_async(url.as_str()).await.unwrap(); + await_presence(&mut fresh, &mut fresh_view, native, true).await; + assert_eq!( + fresh_view.get_payload(native).unwrap().user.name, + room_client::LOCAL_AWARENESS_NAME + ); + }) + .await + .expect("presence after reconnect"); + }); + } + + #[test] + fn remote_selection_reads_only_the_selection_keys_of_the_shown_page() { + let session = open(1280, 800, PlaygroundOptions::default()); + let client = client_id_from_seed(0x05e1); + let mut peer = RoomAwareness::new(client).unwrap(); + let caret_id = format!("page.presence.{client}.caret"); + let mut announce = |keys: &[(&str, &str)]| { + let mut payload = AwarenessPayload::new("Kim", "var(--affine-multi-players-green)"); + for (key, block) in keys { + payload + .set_text_selection(*key, TextSelectionState::caret(*block, 2)) + .unwrap(); + } + let update = peer.set_local_payload(&payload, 0).unwrap(); + session.view(|view, cx| { + view.edit_document(cx, |state| { + state.awareness.apply_update(&update, 0).unwrap() + }); + }); + session.frame().0 + }; + let inside = |snapshot: &FrameSnapshot, block: &str| { + let caret = snapshot.elements[&caret_id].bounds; + let block = snapshot.elements[&format!("page.block.{block}")].bounds; + caret.y >= block.y && caret.bottom() <= block.bottom() + }; + + // Managers of other stores never match, however similar their ids look. + let others = [ + ("doc:aaa:m1", "showcase-h1"), + ("doc:home2:m1", "showcase-h2"), + ("doc:home:archive:m2", "showcase-intro"), + ]; + let snapshot = announce(&others[..]); + assert!( + snapshot + .elements + .contains_key(&format!("chrome.presence.{client}")) + ); + assert!(!snapshot.elements.contains_key(&caret_id)); + + // The manager of the shown page (`:`) is found among them. + let mut keys = others.to_vec(); + keys.push(("doc:home:m3", "showcase-quote")); + let snapshot = announce(keys.as_slice()); + assert!(inside(&snapshot, "showcase-quote")); + + // A bare page id is read as well; an empty manager id is not. + let snapshot = announce(&[("doc:home", "showcase-bullet")][..]); + assert!(inside(&snapshot, "showcase-bullet")); + let snapshot = announce(&[("doc:home:", "showcase-bullet")][..]); + assert!(!snapshot.elements.contains_key(&caret_id)); + } + + /// Right-aligned wrapped text with an inheriting and an overriding child, a centered + /// list item, and the caret of collaborator `peer_id` at the end of the wrapped text. + fn alignment_document(peer_id: u64) -> DocState { + let long = "Right aligned text wraps onto several lines, and every one of its lines \ + ends at the right edge of the column, whatever its length happens to be." + .repeat(2); + let mut state = DocState::new("align", client_id_from_seed(0x0a12)).expect("state"); + state.workspace.initialize_meta().expect("meta"); + state + .workspace + .create_page(HOME_PAGE_ID, "Alignment", 1) + .expect("page"); + { + let page = state.workspace.ensure_page(HOME_PAGE_ID).expect("page"); + let mut seed = ShowcaseSeed { page, now_ms: 0 }; + seed.add( + "a-page", + BlockSpec::Page { + title: "Alignment".to_string(), + }, + None, + ) + .expect("page block"); + seed.add("a-note", BlockSpec::Note { xywh: None }, Some("a-page")) + .expect("note"); + seed.paragraph("a-right", ParagraphType::Text, &long, "a-note") + .expect("paragraph"); + seed.paragraph("a-child", ParagraphType::Text, "Inherits right", "a-right") + .expect("paragraph"); + seed.paragraph( + "a-child-left", + ParagraphType::Text, + "Explicit left", + "a-right", + ) + .expect("paragraph"); + seed.list( + "a-list", + ListType::Bulleted, + "Centered item", + false, + "a-note", + ) + .expect("list"); + seed.paragraph("a-plain", ParagraphType::Text, "Default left", "a-note") + .expect("paragraph"); + for (id, align) in [ + ("a-right", "right"), + ("a-child-left", "left"), + ("a-list", "center"), + ] { + let now_ms = seed.tick(); + seed.page + .set_block_prop( + id, + "prop:textAlign", + SessionValue::Any(Any::String(align.to_string())), + now_ms, + ) + .expect("text align"); + } + } + // A collaborator's caret sits at the end of the right-aligned paragraph. + let mut payload = AwarenessPayload::new("Rita", "var(--affine-multi-players-orange)"); + payload + .set_text_selection( + HOME_PAGE_ID, + TextSelectionState::caret("a-right", long.encode_utf16().count() as u64), + ) + .expect("selection"); + let update = RoomAwareness::new(peer_id) + .expect("peer") + .set_local_payload(&payload, 0) + .expect("payload"); + state.awareness.apply_update(&update, 0).expect("presence"); + state + } + + #[test] + fn text_alignment_moves_wrapped_lines_and_carets_and_is_inherited_by_children() { + let peer_id = client_id_from_seed(0x0a11); + let session = open(800, 900, PlaygroundOptions::default()); + session.view(|view, cx| view.set_document(alignment_document(peer_id), cx)); + let (snapshot, _) = session.frame(); + assert_no_violations(&snapshot, "aligned text"); + let layout = session.view(|view, _| view.flow_layout().expect("layout")); + // `(left edge, right edge)` of every line of a block's text, in column coordinates. + let lines = |id: &str| -> Vec<(f32, f32)> { + let block = layout.block(id).unwrap_or_else(|| panic!("{id} laid out")); + let text = block.body.text.as_ref().expect("text"); + let FlowTextLayout::Rich(rich) = &text.layout else { + panic!("{id} is rich text"); + }; + rich.lines() + .iter() + .map(|line| { + let left = block.x + text.x + f32::from(line.x); + (left, left + f32::from(line.width)) + }) + .collect() + }; + let column = layout.width; + let ends_right = |right: f32| right <= column && column - right < 1.0; + + let right = lines("a-right"); + assert!(right.len() >= 3, "{right:?}"); + assert!( + right.iter().all(|(_, right)| ends_right(*right)), + "{right:?}" + ); + assert!(right.iter().any(|(left, _)| *left > 40.0), "{right:?}"); + + // Children inherit the alignment unless they set their own. + assert_eq!(layout.block("a-child").expect("child").x, CHILD_INDENT); + let child = lines("a-child"); + assert!(ends_right(child[0].1), "{child:?}"); + assert_eq!(lines("a-child-left")[0].0, CHILD_INDENT); + assert_eq!(lines("a-plain")[0].0, 0.0); + + // A list keeps its prefix at the left edge and centers only its text box. + let list = layout.block("a-list").expect("list"); + let prefix = list.body.prefix.expect("prefix"); + assert!(prefix.x + prefix.w <= LIST_PREFIX_WIDTH); + let (left, right) = lines("a-list")[0]; + let free = column - LIST_PREFIX_WIDTH - (right - left); + assert!(free > 100.0); + assert!( + (left - (LIST_PREFIX_WIDTH + free / 2.0)).abs() <= 1.0, + "{left} {right}" + ); + + // The remote caret follows the last right-aligned line to the column's right edge. + let caret = snapshot.elements[&format!("page.presence.{peer_id}.caret")].bounds; + let block = snapshot.elements["page.block.a-right"].bounds; + let line_height = paragraph_spec(ParagraphType::Text).line_height; + assert!((block.right() - caret.right()).abs() <= 2.0, "{caret:?}"); + assert_eq!( + caret.y, + block.y + (right_line_count(&layout) - 1) as f32 * line_height + ); + assert_eq!(caret.height, line_height); + } + + fn right_line_count(layout: &FlowLayout) -> usize { + layout + .block("a-right") + .and_then(|block| block.body.text.as_ref()) + .map_or(0, |text| text.layout.line_count()) + } + + #[test] + fn native_flags_reject_tls_relays() { + let args = |relay: &str| ["--room", "r", "--relay", relay].map(String::from); + for relay in ["wss://relay.example", "https://relay.example"] { + let error = PlaygroundOptions::from_args(args(relay)) + .expect_err("a TLS relay is rejected") + .to_string(); + assert!(error.contains("ws://"), "{error}"); + } + let options = PlaygroundOptions::from_args(args("http://127.0.0.1:9000")).unwrap(); + assert_eq!( + options.room.expect("room").ws_url, + "ws://127.0.0.1:9000/native-sync/rooms/r" + ); } } diff --git a/blocksuite/native-playground/crates/playground/src/main.rs b/blocksuite/native-playground/crates/playground/src/main.rs index ace6ec7996..da90ef03e3 100644 --- a/blocksuite/native-playground/crates/playground/src/main.rs +++ b/blocksuite/native-playground/crates/playground/src/main.rs @@ -2,13 +2,24 @@ fn main() { use ui::prelude::*; + let options = match playground::PlaygroundOptions::from_args(std::env::args().skip(1)) { + Ok(options) => options, + Err(err) => { + eprintln!( + "{err:#}\nusage: native-playground [--theme light|dark] [--mode page|edgeless] \ + [--room [--relay ]]" + ); + std::process::exit(2); + } + }; + let platform = std::rc::Rc::new(ui::MacPlatform::new(false)); - ui::Application::with_platform(platform).run(|cx| { + ui::Application::with_platform(platform).run(move |cx| { if let Err(err) = playground::register_bundled_fonts(cx) { - eprintln!("failed to register bundled Inter font: {err:#}"); + eprintln!("failed to register bundled fonts: {err:#}"); } let _ = cx.open_window(ui::WindowOptions::default(), |_, cx| { - cx.new(playground::PlaygroundView::new) + cx.new(|cx| playground::PlaygroundView::with_options(options, cx)) }); }); } diff --git a/blocksuite/native-playground/crates/playground/src/rich_text.rs b/blocksuite/native-playground/crates/playground/src/rich_text.rs index 0d2e3e3cbf..7faab29455 100644 --- a/blocksuite/native-playground/crates/playground/src/rich_text.rs +++ b/blocksuite/native-playground/crates/playground/src/rich_text.rs @@ -1,16 +1,13 @@ //! Shaped paragraph geometry in document UTF-16 coordinates. use std::{ops::Range, sync::Arc}; +pub use crate::theme::ThemeMode; +use crate::theme::{IconPaint, PlaygroundTheme, tokens as raw_tokens}; use ui::gpui_util::ResultExt as _; use ui::{ App, Bounds, FontStyle, FontWeight, Hsla, IntoElement, Pixels, Point, ShapedLine, SharedString, Size, Styled, TextAlign, TextRun, Window, WindowTextSystem, canvas, fill, point, px, size, }; -#[allow(dead_code)] -mod raw_tokens { - include!("../../../tokens/tokens.rs"); -} -pub use raw_tokens::ThemeMode; use unicode_bidi::BidiInfo; use unicode_linebreak::linebreaks; use unicode_segmentation::UnicodeSegmentation; @@ -107,6 +104,10 @@ pub struct InlineMarkSet { pub code: bool, pub link: Option, pub reference: Option, + /// Text color as stored in the document (`var(--token)` or a hex color). + pub color: Option, + /// Highlight color as stored in the document (`var(--token)` or a hex color). + pub background: Option, } fn string_attr(value: Option<&Any>) -> Option { @@ -137,6 +138,8 @@ impl InlineMarkSet { code: enabled("code"), link: string_attr(attrs.get("link")), reference, + color: string_attr(attrs.get("color")), + background: string_attr(attrs.get("background")), } } } @@ -281,6 +284,8 @@ const PAGE_PREFIX: &str = "▤ "; #[derive(Clone, Debug)] pub struct RichParagraphStyle { + /// Theme that resolves `color` and `background` marks. + pub theme: PlaygroundTheme, pub font_family: SharedString, pub code_font_family: SharedString, pub font_size: f32, @@ -289,6 +294,8 @@ pub struct RichParagraphStyle { /// Measured alphabetic baseline within the line box. Defaults to centered font metrics. pub baseline_offset: Option, pub letter_spacing: f32, + /// Where each line sits inside the layout width. + pub align: TextAlign, pub text_color: Hsla, pub link_color: Hsla, pub code_bg: Hsla, @@ -313,7 +320,9 @@ impl Default for RichParagraphStyle { } } -#[derive(Clone, Copy)] +/// Inline code box as measured in the browser (`inline_formats.inline_code` of +/// `tokens/style-oracle.json`); a test keeps these constants equal to the oracle. +#[derive(Clone, Copy, Debug, PartialEq)] struct CodeBoxMetrics { baseline: f32, descent: f32, @@ -324,36 +333,28 @@ struct CodeBoxMetrics { } impl CodeBoxMetrics { - fn from_oracle(mode: ThemeMode) -> Self { - static BOXES: std::sync::OnceLock<[CodeBoxMetrics; 2]> = std::sync::OnceLock::new(); - let boxes = BOXES.get_or_init(|| { - let oracle: serde_json::Value = - serde_json::from_str(include_str!("../../../tokens/style-oracle.json")) - .expect("valid bundled style oracle"); - ["light", "dark"].map(|name| { - let node = &oracle["themes"][name]["inline_formats"]["inline_code"]; - let css = |property: &str| -> f32 { - node["computed"][property] - .as_str() - .and_then(|s| s.strip_suffix("px")) - .and_then(|v| v.parse().ok()) - .expect("pixel measure in inline code oracle") - }; - let baseline = node["baseline_offset_px"].as_f64().unwrap() as f32; - let height = node["rect"]["height"].as_f64().unwrap() as f32; - let border = css("border_top_width"); - let padding_bottom = css("padding_bottom"); - Self { - baseline, - descent: height - baseline - padding_bottom - border, - border, - radius: css("border_radius"), - padding_x: css("padding_left"), - padding_bottom, - } - }) - }); - boxes[usize::from(mode == ThemeMode::Dark)] + const LIGHT: Self = Self { + baseline: 12.0, + descent: 3.0, + border: 1.0, + radius: 4.0, + padding_x: 4.0, + padding_bottom: 2.0, + }; + const DARK: Self = Self { + baseline: 13.0, + descent: 3.0, + border: 1.0, + radius: 4.0, + padding_x: 4.0, + padding_bottom: 2.0, + }; + + fn for_theme(mode: ThemeMode) -> Self { + match mode { + ThemeMode::Light => Self::LIGHT, + ThemeMode::Dark => Self::DARK, + } } } @@ -365,8 +366,9 @@ impl RichParagraphStyle { let family = |stack: &'static str| { SharedString::from(stack.split(',').next().unwrap().trim_matches('"')) }; - let metrics = CodeBoxMetrics::from_oracle(mode); + let metrics = CodeBoxMetrics::for_theme(mode); Self { + theme: mode.into(), font_family: family(typography.font_family), code_font_family: family(typography.font_code_family), font_size: typography.font_base_px, @@ -374,6 +376,7 @@ impl RichParagraphStyle { line_height: typography.line_height_base_px, baseline_offset: None, letter_spacing: 0., + align: TextAlign::Left, text_color: color(theme.text_primary), link_color: color(theme.link), code_bg: color(theme.background_code_block), @@ -415,6 +418,8 @@ pub enum DecorationKind { Underline, Strikethrough, Link(String), + /// Background of a highlighted run, painted behind its glyphs. + Highlight, } #[derive(Clone, Debug)] @@ -434,6 +439,9 @@ struct Fragment { #[derive(Debug)] pub struct LaidOutRichLine { pub source_utf16: Range, + /// Left edge of the line inside the layout width (non-zero for centered and + /// right-aligned text). + pub x: Pixels, pub width: Pixels, pub baseline_y: Pixels, pub top: Pixels, @@ -476,7 +484,7 @@ impl LaidOutRichLine { .get(self.cells.partition_point(|c| c.source.end <= offset)) .map(|c| c.leading) .or_else(|| self.cells.last().map(|c| c.trailing)) - .unwrap_or(Pixels::ZERO) + .unwrap_or(self.x) } fn nearest_offset(&self, x: Pixels) -> u64 { @@ -485,7 +493,7 @@ impl LaidOutRichLine { .map(|c| (c.source.start, c.leading)) .chain(std::iter::once(( self.source_utf16.end, - self.cells.last().map_or(Pixels::ZERO, |c| c.trailing), + self.cells.last().map_or(self.x, |c| c.trailing), ))) .min_by_key(|(_, pos)| (*pos - x).abs()) .unwrap() @@ -610,6 +618,23 @@ impl StyledFragment<'_> { } } +/// Ink of a span: reference and link colors win, then code, then a custom `color` mark. +fn span_color(style: &RichParagraphStyle, span: &RichSpan) -> Hsla { + if span.chip { + style.chip_fg + } else if span.marks.link.is_some() { + style.link_color + } else if span.marks.code { + style.code_fg + } else { + span.marks + .color + .as_deref() + .and_then(|color| style.theme.css_color(color)) + .unwrap_or(style.text_color) + } +} + impl ParagraphLayout<'_> { fn fragments(&self, from: usize, to: usize) -> impl Iterator> { let p = self.paragraph; @@ -658,23 +683,18 @@ impl ParagraphLayout<'_> { } else { &style.font_family }); - font.weight = if s.marks.bold { + // CSS `bolder`: regular and medium text step to 700, heavier text to 900. + font.weight = if !s.marks.bold { + style.base_weight + } else if style.base_weight.0 <= 500.0 { FontWeight::BOLD } else { - style.base_weight + FontWeight::BLACK }; if s.marks.italic { font.style = FontStyle::Italic; } - let color = if s.chip { - style.chip_fg - } else if s.marks.link.is_some() { - style.link_color - } else if is_code { - style.code_fg - } else { - style.text_color - }; + let color = span_color(style, s); let len = if s.chip { text.len() } else { @@ -755,6 +775,7 @@ impl ParagraphLayout<'_> { ) -> LaidOutRichLine { let index = &self.paragraph.index; let baseline_y = top + self.baseline; + let first_decoration = decorations.len(); let mut x = Pixels::ZERO; let mut fragments = Vec::new(); let mut cells = Vec::new(); @@ -783,13 +804,20 @@ impl ParagraphLayout<'_> { }) }; let style = self.style; - let color = if span.marks.link.is_some() { - style.link_color - } else if span.marks.code { - style.code_fg - } else { - style.text_color - }; + let color = span_color(style, span); + if !span.chip + && let Some(highlight) = span + .marks + .background + .as_deref() + .and_then(|background| style.theme.css_color(background)) + { + decorate( + DecorationKind::Highlight, + rect(top, self.line_height), + highlight, + ); + } if span.chip && let Some(reference) = &span.marks.reference { @@ -798,12 +826,15 @@ impl ParagraphLayout<'_> { rect(top, self.line_height), style.chip_bg, ); - let icon_size = px(style.font_size * 0.8).min(width); + let icon_size = px(style.font_size).min(width); decorate( DecorationKind::PageGlyph, Bounds::new( - point(visual.start, baseline_y - icon_size), - size(icon_size * 0.8, icon_size), + point( + visual.start, + (top + (self.line_height - icon_size) * 0.5).floor(), + ), + size(icon_size, icon_size), ), style.icon_color, ); @@ -866,8 +897,29 @@ impl ParagraphLayout<'_> { }); x = right; } + // The line was laid out from the left edge; move it to its aligned position. An + // empty line keeps its caret there too. + let free = (self.limit - x).max(Pixels::ZERO); + let offset = match self.style.align { + TextAlign::Left => Pixels::ZERO, + TextAlign::Center => (free * 0.5).floor(), + TextAlign::Right => free.floor(), + }; + if offset > Pixels::ZERO { + for fragment in &mut fragments { + fragment.x += offset; + } + for cell in &mut cells { + cell.leading += offset; + cell.trailing += offset; + } + for decoration in &mut decorations[first_decoration..] { + decoration.bounds.origin.x += offset; + } + } LaidOutRichLine { source_utf16: index.graphemes[start].utf16..index.graphemes[end].utf16, + x: offset, width: x, baseline_y, top, @@ -878,6 +930,28 @@ impl ParagraphLayout<'_> { } impl RichParagraph { + /// Byte offsets into `source` where a line may end. A reference breaks like an inline + /// object (UAX #14 class CB) rather than like the space that stands for it in the + /// document, so the words before it stay on their line when only the reference wraps. + fn break_opportunities(&self) -> Vec { + const OBJECT: char = '\u{fffc}'; + let mut text = String::with_capacity(self.source.len()); + let mut references = Vec::new(); + for span in &self.spans { + if span.chip { + references.push(text.len()); + text.push(OBJECT); + } else { + text.push_str(&self.source[span.source_bytes.clone()]); + } + } + // Every reference is one source byte but `OBJECT.len_utf8()` bytes of `text`. + let extra = OBJECT.len_utf8() - 1; + linebreaks(&text) + .map(|(byte, _)| byte - extra * references.partition_point(|&at| at < byte)) + .collect() + } + pub fn layout( &self, ts: &WindowTextSystem, @@ -901,7 +975,7 @@ impl RichParagraph { .map(px) .unwrap_or_else(|| ((line_height + ascent - descent) / 2.).round()), }; - let breaks: Vec = linebreaks(&self.source).map(|(byte, _)| byte).collect(); + let breaks = self.break_opportunities(); let mut lines = Vec::new(); let mut decorations = Vec::new(); let mut width = Pixels::ZERO; @@ -909,7 +983,7 @@ impl RichParagraph { let mut start = 0; let mut append = |a, b| { let line = layout.line(a, b, top, &mut decorations); - width = width.max(line.width); + width = width.max(line.x + line.width); lines.push(line); top += line_height; }; @@ -959,7 +1033,12 @@ impl LaidOutRichParagraph { &self.decorations } - pub fn caret_rect(&self, position: CaretPosition) -> Bounds { + pub fn line_height(&self) -> Pixels { + self.line_height + } + + /// Index of the line holding `position` and the caret's x on that line. + pub fn caret_line_and_x(&self, position: CaretPosition) -> (usize, Pixels) { let offset = position.utf16_offset; let i = match position.affinity { WrapAffinity::Upstream => self.lines.partition_point(|l| l.source_utf16.end < offset), @@ -968,13 +1047,109 @@ impl LaidOutRichParagraph { .partition_point(|l| l.source_utf16.start <= offset) .saturating_sub(1), }; - let line = &self.lines[i.min(self.lines.len() - 1)]; + let i = i.min(self.lines.len() - 1); + (i, self.lines[i].x_for_offset(offset)) + } + + pub fn caret_rect(&self, position: CaretPosition) -> Bounds { + let (line, x) = self.caret_line_and_x(position); Bounds::new( - point(line.x_for_offset(offset), line.top), + point(x, self.lines[line].top), size(px(1.), self.line_height), ) } + /// Paint the paragraph with its top-left corner at `origin`: decorations, the given + /// selection fills, glyphs, strokes, then the given carets. + pub fn paint_at( + &self, + origin: Point, + selections: &[(Range, Hsla)], + carets: &[(CaretPosition, Hsla)], + hovered_link: Option<&Range>, + window: &mut Window, + cx: &mut App, + ) { + static PAGE_ICON: std::sync::OnceLock = std::sync::OnceLock::new(); + let translated = |b: Bounds| Bounds::new(origin + b.origin, b.size); + let style = &self.style; + for d in &self.decorations { + let bounds = translated(d.bounds); + match &d.kind { + DecorationKind::Highlight | DecorationKind::ReferenceChip(_) => { + window.paint_quad(fill(bounds, d.color)); + } + DecorationKind::CodePill => window.paint_quad( + fill(bounds, d.color) + .corner_radii(px(style.code_radius)) + .border_widths(px(style.code_border_width)) + .border_color(style.code_border), + ), + DecorationKind::PageGlyph => PAGE_ICON + .get_or_init(|| IconPaint::named("LinkedPageIcon")) + .paint(bounds, d.color, window, cx), + _ => {} + } + } + for (range, color) in selections { + for rect in self.selection_rects(range.start, range.end) { + window.paint_quad(fill(translated(rect), *color)); + } + } + for line in &self.lines { + for fragment in &line.fragments { + let shaped = &fragment.shaped; + let glyph_origin = origin + point(fragment.x, line.baseline_y - shaped.ascent); + shaped + .paint( + glyph_origin, + shaped.ascent + shaped.descent, + TextAlign::Left, + None, + window, + cx, + ) + .log_err(); + } + } + for d in &self.decorations { + if matches!( + d.kind, + DecorationKind::Underline + | DecorationKind::Strikethrough + | DecorationKind::ReferenceDivider + ) { + window.paint_quad(fill(translated(d.bounds), d.color)); + } else if matches!(d.kind, DecorationKind::Link(_)) + && hovered_link + .is_some_and(|r| r.start < d.source_utf16.end && d.source_utf16.start < r.end) + { + let line = &self.lines[self + .lines + .partition_point(|line| line.top < d.bounds.origin.y)]; + let stroke = Bounds::new( + point(d.bounds.origin.x, line.baseline_y + px(1.)), + size(d.bounds.size.width, px(1.)), + ); + window.paint_quad(fill(translated(stroke), d.color)); + } + } + self.paint_carets(origin, carets, window); + } + + /// Paint only the carets, for callers that clip the paragraph but not its carets. + pub fn paint_carets( + &self, + origin: Point, + carets: &[(CaretPosition, Hsla)], + window: &mut Window, + ) { + for (position, color) in carets { + let rect = self.caret_rect(*position); + window.paint_quad(fill(Bounds::new(origin + rect.origin, rect.size), *color)); + } + } + pub fn hit_test(&self, local_point: Point) -> CaretPosition { let i = self .lines @@ -1037,84 +1212,18 @@ impl RichParagraphElement { fn paint(self, bounds: Bounds, window: &mut Window, cx: &mut App) { let layout = &self.layout; - let translated = |b: Bounds| Bounds::new(bounds.origin + b.origin, b.size); + // Glyphs and decorations stay inside the element; carets may sit on its edge. window.with_content_mask(Some(ui::ContentMask { bounds }), |window| { - for d in layout.inline_decorations() { - let bounds = translated(d.bounds); - let style = &layout.style; - match &d.kind { - DecorationKind::CodePill => window.paint_quad( - fill(bounds, d.color) - .corner_radii(px(style.code_radius)) - .border_widths(px(style.code_border_width)) - .border_color(style.code_border), - ), - DecorationKind::ReferenceChip(_) => window.paint_quad(fill(bounds, d.color)), - DecorationKind::PageGlyph => { - window.paint_quad( - ui::outline(bounds, d.color, ui::BorderStyle::Solid) - .corner_radii(px(1.)), - ); - for dy in [0.38, 0.63] { - let origin = bounds.origin - + point(bounds.size.width * 0.22, bounds.size.height * dy); - window.paint_quad(fill( - Bounds::new(origin, size(bounds.size.width * 0.56, px(0.8))), - d.color, - )); - } - } - _ => {} - } - } - for (range, color) in &self.selections { - for rect in layout.selection_rects(range.start, range.end) { - window.paint_quad(fill(translated(rect), *color)); - } - } - for line in layout.lines() { - for fragment in &line.fragments { - let shaped = &fragment.shaped; - let origin = bounds.origin + point(fragment.x, line.baseline_y - shaped.ascent); - shaped - .paint( - origin, - shaped.ascent + shaped.descent, - TextAlign::Left, - None, - window, - cx, - ) - .log_err(); - } - } - for d in layout.inline_decorations() { - if matches!( - d.kind, - DecorationKind::Underline - | DecorationKind::Strikethrough - | DecorationKind::ReferenceDivider - ) { - window.paint_quad(fill(translated(d.bounds), d.color)); - } else if matches!(d.kind, DecorationKind::Link(_)) - && self.hovered_link.as_ref().is_some_and(|r| { - r.start < d.source_utf16.end && d.source_utf16.start < r.end - }) - { - let line = &layout.lines[layout - .lines - .partition_point(|line| line.top < d.bounds.origin.y)]; - let stroke = Bounds::new( - point(d.bounds.origin.x, line.baseline_y + px(1.)), - size(d.bounds.size.width, px(1.)), - ); - window.paint_quad(fill(translated(stroke), d.color)); - } - } + layout.paint_at( + bounds.origin, + &self.selections, + &[], + self.hovered_link.as_ref(), + window, + cx, + ); }); - for (pos, color) in self.carets { - window.paint_quad(fill(translated(layout.caret_rect(pos)), color)); - } + layout.paint_carets(bounds.origin, &self.carets, window); } } @@ -1454,6 +1563,117 @@ 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(); + for (mode, name) in [(ThemeMode::Light, "light"), (ThemeMode::Dark, "dark")] { + let node = &oracle["themes"][name]["inline_formats"]["inline_code"]; + let css = |property: &str| -> f32 { + node["computed"][property] + .as_str() + .and_then(|s| s.strip_suffix("px")) + .and_then(|v| v.parse().ok()) + .unwrap_or_else(|| panic!("{name} inline code {property} is a pixel measure")) + }; + let baseline = node["baseline_offset_px"].as_f64().unwrap() as f32; + let height = node["rect"]["height"].as_f64().unwrap() as f32; + let border = css("border_top_width"); + let padding_bottom = css("padding_bottom"); + assert_eq!( + CodeBoxMetrics::for_theme(mode), + CodeBoxMetrics { + baseline, + descent: height - baseline - padding_bottom - border, + border, + radius: css("border_radius"), + padding_x: css("padding_left"), + padding_bottom, + }, + "{name} inline code box" + ); + } + } + + #[test] + fn marks_resolve_colors_highlights_and_css_bolder() { + let platform = HeadlessPlatform::new(64, 64, 1.); + let app = Application::with_platform(platform) + .run_embedded(|cx| crate::register_bundled_fonts(cx).unwrap()); + app.update(|cx| { + let ts = WindowTextSystem::new(cx.text_system().clone()); + let style = RichParagraphStyle::default(); + let colored = |key: &str, value: &str| { + insert( + "mark", + Some([(key.into(), Any::String(value.into()))].into()), + ) + }; + let para = RichParagraph::from_delta(vec![ + colored("background", "var(--affine-text-highlight-orange)"), + insert(" ", None), + colored("color", "var(--affine-text-highlight-foreground-blue)"), + insert(" ", None), + colored("background", "not-a-color"), + ]) + .unwrap(); + assert_eq!( + para.spans()[0].marks.background.as_deref(), + Some("var(--affine-text-highlight-orange)") + ); + let layout = para.layout(&ts, &style, 300.); + let highlights: Vec<_> = layout + .inline_decorations() + .iter() + .filter(|d| d.kind == DecorationKind::Highlight) + .collect(); + // Only a color the theme can resolve becomes a highlight. + assert_eq!(highlights.len(), 1); + assert_eq!(highlights[0].source_utf16, 0..4); + assert_eq!( + Some(highlights[0].color), + style.theme.css_var("--affine-text-highlight-orange") + ); + assert_eq!(highlights[0].bounds.size.height, layout.line_height()); + assert_eq!( + span_color(&style, ¶.spans()[2]), + style + .theme + .css_var("--affine-text-highlight-foreground-blue") + .unwrap() + ); + assert_eq!(span_color(&style, ¶.spans()[0]), style.text_color); + + // `bolder` widens regular text to 700 and heading weights to 900. + let bold = RichParagraph::from_delta(vec![insert( + "Bolder", + Some([("bold".into(), Any::True)].into()), + )]) + .unwrap(); + let width = |base_weight| { + let style = RichParagraphStyle { + base_weight, + ..RichParagraphStyle::default() + }; + bold.layout(&ts, &style, 300.).size().width + }; + let mut font = ui::font("Inter"); + let mut plain_width = |weight| { + font.weight = weight; + let run = TextRun { + len: 6, + font: font.clone(), + color: style.text_color, + ..Default::default() + }; + ts.shape_line("Bolder".into(), px(style.font_size), &[run], None) + .width() + }; + assert_eq!(width(FontWeight::NORMAL), plain_width(FontWeight::BOLD)); + assert_eq!(width(FontWeight::SEMIBOLD), plain_width(FontWeight::BLACK)); + }); + } + #[test] fn reference_title_resolution_preserves_document_identity() { let reference = |title: Option<&str>| { @@ -1494,6 +1714,118 @@ mod tests { } } + #[test] + fn a_wrapping_reference_leaves_the_words_before_it_on_their_line() { + let platform = HeadlessPlatform::new(64, 64, 1.); + let app = Application::with_platform(platform) + .run_embedded(|cx| crate::register_bundled_fonts(cx).unwrap()); + app.update(|cx| { + let ts = WindowTextSystem::new(cx.text_system().clone()); + let style = RichParagraphStyle::default(); + let reference = Any::Object(Box::new( + [ + ("type".into(), Any::String("LinkedPage".into())), + ("pageId".into(), Any::String("doc:abc".into())), + ("title".into(), Any::String("Edgeless notes".into())), + ] + .into_iter() + .collect(), + )); + let prefix = "Reference such as "; + let at = prefix.len() as u64; + let para = RichParagraph::from_delta(vec![ + insert(prefix, None), + insert(" ", Some([("reference".into(), reference)].into())), + insert(". Next", None), + ]) + .unwrap(); + let chip = para.layout(&ts, &style, 2000.).selection_rects(at, at + 1)[0]; + // Wide enough for the words or for the reference, but not for both. + let width = f32::from(chip.origin.x + chip.size.width * 0.5); + let layout = para.layout(&ts, &style, width); + let lines = layout.lines(); + assert_eq!(lines[0].source_utf16, 0..at); + // The reference starts the next line and keeps its closing punctuation. + assert_eq!(lines[1].source_utf16.start, at); + assert!(lines[1].source_utf16.end > at + 1); + }); + } + + #[test] + fn centered_and_right_aligned_lines_move_glyphs_carets_and_decorations_together() { + let platform = HeadlessPlatform::new(64, 64, 1.); + let app = Application::with_platform(platform) + .run_embedded(|cx| crate::register_bundled_fonts(cx).unwrap()); + app.update(|cx| { + let ts = WindowTextSystem::new(cx.text_system().clone()); + let limit = 120.; + let para = RichParagraph::from_delta(vec![ + insert("Aligned ", None), + insert("code", Some([("code".into(), Any::True)].into())), + insert(" wraps over several lines", None), + ]) + .unwrap(); + let left = para.layout(&ts, &RichParagraphStyle::default(), limit); + assert!(left.lines().len() > 2); + for align in [TextAlign::Center, TextAlign::Right] { + let style = RichParagraphStyle { + align, + ..RichParagraphStyle::default() + }; + let layout = para.layout(&ts, &style, limit); + assert_eq!(layout.lines().len(), left.lines().len()); + for (line, reference) in layout.lines().iter().zip(left.lines()) { + assert_eq!(line.source_utf16, reference.source_utf16); + assert_eq!(line.width, reference.width); + let free = px(limit) - line.width; + let expected = match align { + TextAlign::Right => free.floor(), + _ => (free * 0.5).floor(), + }; + assert_eq!(line.x, expected); + assert!(line.x + line.width <= px(limit)); + // Carets, selections and hit testing follow the moved line. + let start = CaretPosition { + utf16_offset: line.source_utf16.start, + affinity: WrapAffinity::Downstream, + }; + assert_eq!(layout.caret_rect(start).origin.x, line.x); + let hit = layout.hit_test(point(line.x, line.top + px(1.))); + assert_eq!(hit.utf16_offset, line.source_utf16.start); + } + let pill = |layout: &LaidOutRichParagraph| { + layout + .inline_decorations() + .iter() + .find(|d| d.kind == DecorationKind::CodePill) + .unwrap() + .bounds + }; + assert_eq!( + pill(&layout).origin.x, + pill(&left).origin.x + layout.lines()[0].x + ); + assert_eq!(layout.size().width.max(px(limit)), px(limit)); + + // An empty paragraph keeps its caret at the aligned edge. + let empty = RichParagraph::from_delta(Vec::new()) + .unwrap() + .layout(&ts, &style, limit); + let caret = empty.caret_rect(CaretPosition { + utf16_offset: 0, + affinity: WrapAffinity::Downstream, + }); + assert_eq!( + caret.origin.x, + match align { + TextAlign::Right => px(limit), + _ => px(limit * 0.5), + } + ); + } + }); + } + #[test] fn paint_only_marks_keep_av_kerning_and_carets() { let platform = HeadlessPlatform::new(64, 64, 1.); diff --git a/blocksuite/native-playground/crates/playground/src/room_client.rs b/blocksuite/native-playground/crates/playground/src/room_client.rs new file mode 100644 index 0000000000..d44afa45f8 --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/room_client.rs @@ -0,0 +1,1193 @@ +//! Live room sync for the playground view. +//! +//! [`RoomProtocol`] is the sans-I/O client side of the relay's binary room protocol +//! (`SyncStep1` / `SyncStep2` / `Update` document frames and awareness frames from +//! `blocksuite_playground_doc::wire`): it turns incoming frames into document and +//! awareness changes on a [`DocState`] and says which frames to send back. +//! +//! [`connect`] opens the transport that carries those frames: a `tokio-tungstenite` +//! socket on a background thread on native targets, a browser `WebSocket` on the Web. +//! Both deliver [`RoomEvent`]s through a channel read on the UI thread and fetch image +//! blobs over HTTP from the relay's blob endpoint (a bare HTTP/1.1 `GET` natively, `fetch` +//! on the Web). + +use std::{ + collections::{BTreeMap, HashMap}, + sync::Arc, +}; + +use blocksuite_playground_doc::{ + DocResult, + awareness::{AwarenessPayload, RoomAwareness}, + session::WorkspaceSession, + wire::{ + DocMessage, DocSyncPhase, DocSyncState, RoomBinaryFrame, RoomControlFrame, + decode_binary_frame, decode_control_frame, encode_binary_frame, + }, +}; + +/// Relay address used when a room is requested without one. +pub const DEFAULT_RELAY: &str = "ws://127.0.0.1:8788"; + +/// Name the native playground announces in room awareness. +pub const LOCAL_AWARENESS_NAME: &str = "Native Playground"; +/// Color the native playground announces in room awareness. +pub const LOCAL_AWARENESS_COLOR: &str = "var(--affine-multi-players-blue)"; + +/// Document, presence and blob state shown by the playground view. +pub struct DocState { + pub workspace: WorkspaceSession, + pub awareness: RoomAwareness, + /// Blob bytes by `sourceId`. + pub blobs: HashMap>>, +} + +impl DocState { + /// Empty state for `room`, authored by `client_id`. + pub fn new(room: &str, client_id: u64) -> DocResult { + Ok(Self { + workspace: WorkspaceSession::new(room, client_id)?, + awareness: RoomAwareness::new(client_id)?, + blobs: HashMap::new(), + }) + } +} + +/// Where a live room is reached. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RoomConfig { + pub room: String, + /// WebSocket URL of the room (`…/native-sync/rooms/`). + pub ws_url: String, + /// HTTP origin of the relay serving `/api/collection//blob/`. + pub http_origin: String, +} + +impl RoomConfig { + /// Resolve a room against a relay address. `relay` may be a relay origin + /// (`ws://host:port`, `http://host:port`) or the full room WebSocket URL; + /// [`DEFAULT_RELAY`] is used when it is absent. + pub fn new(room: &str, relay: Option<&str>) -> Self { + let relay = relay + .map(str::trim) + .filter(|relay| !relay.is_empty()) + .unwrap_or(DEFAULT_RELAY); + let relay = if let Some(rest) = relay.strip_prefix("http://") { + format!("ws://{rest}") + } else if let Some(rest) = relay.strip_prefix("https://") { + format!("wss://{rest}") + } else { + relay.to_string() + }; + let ws_url = if relay.contains("/native-sync/rooms/") { + relay + } else { + format!( + "{}/native-sync/rooms/{}", + relay.trim_end_matches('/'), + percent_encode(room) + ) + }; + let (scheme, rest) = ws_url.split_once("://").unwrap_or(("ws", ws_url.as_str())); + let authority = rest.split('/').next().unwrap_or(rest); + let http_scheme = if scheme == "wss" { "https" } else { "http" }; + Self { + room: room.to_string(), + http_origin: format!("{http_scheme}://{authority}"), + ws_url, + } + } + + /// Check that a native transport can reach this room. Native targets speak plain + /// `ws://` and `http://` only (no TLS stack is linked); `wss://` and `https://` relays + /// work on the Web, where the browser handles TLS. + pub fn validate_native(&self) -> anyhow::Result<()> { + anyhow::ensure!( + self.ws_url.starts_with("ws://") && self.http_origin.starts_with("http://"), + "the native playground reaches relays over plain ws:// and http:// only, not {}", + self.ws_url + ); + Ok(()) + } + + /// URL of a blob of this room on the relay. + pub fn blob_url(&self, source_id: &str) -> String { + format!( + "{}/api/collection/{}/blob/{}", + self.http_origin, + percent_encode(&self.room), + percent_encode(source_id) + ) + } +} + +fn percent_encode(value: &str) -> String { + let mut out = String::with_capacity(value.len()); + for byte in value.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + out.push(char::from(byte)); + } + other => out.push_str(&format!("%{other:02X}")), + } + } + out +} + +/// A WebSocket frame of the room protocol. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RoomFrame { + Binary(Vec), + Text(String), +} + +/// Something the transport reports to the UI thread. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RoomEvent { + /// The socket is open; the handshake can start. + Opened, + Frame(RoomFrame), + /// The socket closed or failed to open; the transport reconnects on its own. + Closed(String), + /// A blob fetch finished; `bytes` is `None` when the relay does not have it. + Blob { + source_id: String, + bytes: Option>, + }, +} + +/// Something the UI thread asks of the transport. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RoomCommand { + Send(RoomFrame), + FetchBlob(String), + Close, +} + +/// Connection state of a live room, as shown to the user. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RoomStatus { + Connecting, + /// Connected; `pending` documents have not finished their handshake. + Syncing { + pending: usize, + }, + Live, + Offline(String), +} + +/// What handling an event changed and which frames must be sent in response. +#[derive(Debug, Default)] +pub struct RoomEffects { + pub outbound: Vec, + pub doc_changed: bool, + pub awareness_changed: bool, +} + +/// Sans-I/O client of the relay's room protocol for one room. +pub struct RoomProtocol { + room: String, + sync: BTreeMap, + ready: BTreeMap, + status: RoomStatus, + /// Whether a socket was open before: the next open is a reconnect. + has_opened: bool, +} + +impl RoomProtocol { + pub fn new(room: impl Into) -> Self { + Self { + room: room.into(), + sync: BTreeMap::new(), + ready: BTreeMap::new(), + status: RoomStatus::Connecting, + has_opened: false, + } + } + + pub fn room(&self) -> &str { + &self.room + } + + pub fn status(&self) -> RoomStatus { + match &self.status { + RoomStatus::Syncing { .. } => { + let pending = self.ready.values().filter(|ready| !**ready).count(); + if pending == 0 { + RoomStatus::Live + } else { + RoomStatus::Syncing { pending } + } + } + other => other.clone(), + } + } + + /// The socket opened: announce local presence and pull the root document and every + /// page known so far. + pub fn on_open(&mut self, state: &mut DocState, now_ms: u64) -> DocResult { + let mut effects = RoomEffects::default(); + self.status = RoomStatus::Syncing { pending: 0 }; + self.sync.clear(); + self.ready.clear(); + + let payload = AwarenessPayload::new(LOCAL_AWARENESS_NAME, LOCAL_AWARENESS_COLOR); + // On a reconnect the relay holds a tombstone for this client that the presence + // has to outrank. + let awareness = if std::mem::replace(&mut self.has_opened, true) { + state.awareness.reannounce_local_payload(&payload, now_ms)? + } else { + state.awareness.set_local_payload(&payload, now_ms)? + }; + effects + .outbound + .push(binary(&RoomBinaryFrame::Awareness(awareness))?); + + let room = self.room.clone(); + self.begin_pull(state, &room, &mut effects)?; + self.pull_known_pages(state, &mut effects)?; + Ok(effects) + } + + /// The socket closed: every handshake restarts on the next open. + pub fn on_close(&mut self, reason: impl Into) -> RoomEffects { + for sync in self.sync.values_mut() { + sync.on_disconnect(); + } + self.ready.clear(); + self.status = RoomStatus::Offline(reason.into()); + RoomEffects::default() + } + + /// Apply one frame from the relay. + pub fn on_frame( + &mut self, + state: &mut DocState, + frame: &RoomFrame, + now_ms: u64, + ) -> DocResult { + let mut effects = RoomEffects::default(); + match frame { + RoomFrame::Text(text) => { + if let Ok(RoomControlFrame::Ready { doc_id }) = decode_control_frame(text) { + self.ready.insert(doc_id, true); + } + } + RoomFrame::Binary(bytes) => match decode_binary_frame(bytes)? { + RoomBinaryFrame::Awareness(payload) => { + let event = state.awareness.apply_update(&payload, now_ms)?; + effects.awareness_changed = !event.added().is_empty() + || !event.updated().is_empty() + || !event.removed().is_empty(); + } + RoomBinaryFrame::Doc { doc_id, message } => match message { + DocMessage::Step2(diff) => { + self.apply(state, &doc_id, &diff, &mut effects)?; + let remote_sv = self + .sync + .get_mut(&doc_id) + .and_then(DocSyncState::on_hub_step2); + self.finish_handshake(state, &doc_id, remote_sv, &mut effects)?; + } + DocMessage::Step1(remote_sv) => { + let remote_sv = self + .sync + .get_mut(&doc_id) + .and_then(|sync| sync.on_hub_step1(remote_sv)); + self.finish_handshake(state, &doc_id, remote_sv, &mut effects)?; + } + DocMessage::Update(update) => { + self.apply(state, &doc_id, &update, &mut effects)?; + } + }, + }, + } + Ok(effects) + } + + /// Advance awareness to `now_ms`: renew local presence and expire silent peers. + pub fn tick(&mut self, state: &mut DocState, now_ms: u64) -> DocResult { + let mut effects = RoomEffects::default(); + let tick = state.awareness.tick(now_ms)?; + effects.awareness_changed = !tick.expired_clients.is_empty(); + if let Some(update) = tick.outbound_update + && !matches!(self.status, RoomStatus::Connecting | RoomStatus::Offline(_)) + { + effects + .outbound + .push(binary(&RoomBinaryFrame::Awareness(update))?); + } + Ok(effects) + } + + fn begin_pull( + &mut self, + state: &mut DocState, + doc_id: &str, + effects: &mut RoomEffects, + ) -> DocResult { + if doc_id != self.room { + state.workspace.ensure_page(doc_id)?; + } + let state_vector = state.workspace.encode_state_vector_v1(doc_id)?; + let sync = self + .sync + .entry(doc_id.to_string()) + .or_insert_with(|| DocSyncState::new(doc_id)); + effects + .outbound + .push(binary(&sync.begin_pull(state_vector))?); + self.ready.insert(doc_id.to_string(), false); + Ok(()) + } + + /// Start the handshake of every page listed in the root document that has none yet. + fn pull_known_pages(&mut self, state: &mut DocState, effects: &mut RoomEffects) -> DocResult { + let page_ids: Vec = state + .workspace + .list_pages()? + .into_iter() + .map(|page| page.id) + .filter(|id| { + self.sync + .get(id) + .is_none_or(|sync| sync.phase() == DocSyncPhase::Idle) + }) + .collect(); + for page_id in page_ids { + self.begin_pull(state, &page_id, effects)?; + } + Ok(()) + } + + fn apply( + &mut self, + state: &mut DocState, + doc_id: &str, + update: &[u8], + effects: &mut RoomEffects, + ) -> DocResult { + if update.is_empty() || update == [0, 0] { + return Ok(()); + } + let cleanup = if doc_id == self.room { + let result = state.workspace.apply_root_update_v1(update)?; + result.outbound_updates + } else { + let page = state.workspace.ensure_page(doc_id)?; + page.apply_remote_update_v1(update)?.outbound_updates + }; + effects.doc_changed = true; + // Formatting cleanups produced while integrating must reach the other peers. + for update in cleanup { + effects.outbound.push(binary(&RoomBinaryFrame::Doc { + doc_id: doc_id.to_string(), + message: DocMessage::Update(update), + })?); + } + if doc_id == self.room { + self.pull_known_pages(state, effects)?; + } + Ok(()) + } + + /// Once the hub's `Step2` and reverse `Step1` both arrived, answer with what the hub + /// is missing (always sent, even when empty, so the hub acknowledges with `ready`). + fn finish_handshake( + &mut self, + state: &mut DocState, + doc_id: &str, + remote_sv: Option>, + effects: &mut RoomEffects, + ) -> DocResult { + let Some(remote_sv) = remote_sv else { + return Ok(()); + }; + let diff = state.workspace.encode_diff_v1(doc_id, &remote_sv)?; + if let Some(sync) = self.sync.get(doc_id) { + effects + .outbound + .push(binary(&sync.build_reverse_step2(diff))?); + } + Ok(()) + } +} + +fn binary(frame: &RoomBinaryFrame) -> DocResult { + Ok(RoomFrame::Binary(encode_binary_frame(frame)?)) +} + +/// Handle to a room transport, owned by the UI thread. +pub struct RoomLink { + events: async_channel::Receiver, + commands: Box, +} + +impl RoomLink { + /// Build a link from an event channel and a command sink (the seam transports and + /// in-process loopbacks plug into). + pub fn from_parts( + events: async_channel::Receiver, + commands: impl Fn(RoomCommand) + 'static, + ) -> Self { + Self { + events, + commands: Box::new(commands), + } + } + + /// Events reported by the transport, in order. + pub fn events(&self) -> &async_channel::Receiver { + &self.events + } + + pub fn send(&self, command: RoomCommand) { + (self.commands)(command); + } +} + +impl Drop for RoomLink { + fn drop(&mut self) { + (self.commands)(RoomCommand::Close); + } +} + +#[cfg(not(target_family = "wasm"))] +pub use native::connect; +#[cfg(target_family = "wasm")] +pub use web::connect; + +#[cfg(not(target_family = "wasm"))] +mod native { + use std::time::Duration; + + use futures_util::{SinkExt, StreamExt}; + use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpStream, + sync::mpsc, + time::timeout, + }; + use tokio_tungstenite::{connect_async, tungstenite::Message}; + + use super::{RoomCommand, RoomConfig, RoomEvent, RoomFrame, RoomLink}; + + const RECONNECT_MIN: Duration = Duration::from_millis(250); + const RECONNECT_MAX: Duration = Duration::from_secs(5); + + /// Connect to the room on a background thread running a single-threaded `tokio` + /// runtime. The transport reconnects with backoff until the link is dropped. + pub fn connect(config: RoomConfig) -> RoomLink { + let (events_tx, events_rx) = async_channel::unbounded(); + if let Err(err) = config.validate_native() { + // Nothing to retry: report the reason once and stay closed. + let _ = events_tx.try_send(RoomEvent::Closed(err.to_string())); + return RoomLink::from_parts(events_rx, |_| {}); + } + let (commands_tx, commands_rx) = mpsc::unbounded_channel(); + let failure_tx = events_tx.clone(); + let spawned = std::thread::Builder::new() + .name("room-sync".to_string()) + .spawn(move || { + match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime.block_on(run(config, events_tx, commands_rx)), + Err(err) => { + let _ = events_tx.try_send(RoomEvent::Closed(format!( + "room sync runtime failed to start: {err}" + ))); + } + } + }); + if let Err(err) = spawned { + let _ = failure_tx.try_send(RoomEvent::Closed(format!( + "room sync thread failed to start: {err}" + ))); + } + RoomLink::from_parts(events_rx, move |command| { + let _ = commands_tx.send(command); + }) + } + + /// Largest blob body accepted from the relay. + const MAX_BLOB_BYTES: usize = 64 * 1024 * 1024; + /// Longest wait for the relay to connect, finish a handshake, accept a request or send + /// more bytes. + const HTTP_TIMEOUT: Duration = Duration::from_secs(5); + + /// Fetch a blob with a plain HTTP/1.1 `GET` over TCP (`http://host[:port]/path`). + /// `None` when the URL is not plain HTTP, the relay does not answer `2xx` in time, or + /// the body is malformed or larger than [`MAX_BLOB_BYTES`]. + async fn fetch_blob(url: String) -> Option> { + let rest = url.strip_prefix("http://")?; + let (authority, path) = match rest.find('/') { + Some(slash) => rest.split_at(slash), + None => (rest, "/"), + }; + let has_port = authority + .rsplit_once(':') + .is_some_and(|(_, port)| !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit())); + let address = if has_port { + authority.to_string() + } else { + format!("{authority}:80") + }; + let mut stream = timeout(HTTP_TIMEOUT, TcpStream::connect(address)) + .await + .ok()? + .ok()?; + let request = format!( + "GET {path} HTTP/1.1\r\nHost: {authority}\r\nAccept: */*\r\nConnection: close\r\n\r\n" + ); + timeout(HTTP_TIMEOUT, stream.write_all(request.as_bytes())) + .await + .ok()? + .ok()?; + + // `Connection: close` makes the end of the stream the end of the response. + let mut response = Vec::new(); + let mut chunk = [0_u8; 16 * 1024]; + loop { + let read = timeout(HTTP_TIMEOUT, stream.read(&mut chunk)) + .await + .ok()? + .ok()?; + if read == 0 { + break; + } + response.extend_from_slice(&chunk[..read]); + if response.len() > MAX_BLOB_BYTES + chunk.len() { + return None; + } + } + parse_http_response(&response) + } + + /// Body of a complete HTTP/1.1 response with a `2xx` status, honoring `Content-Length` + /// and chunked framing; without either the body runs to the end of the stream. + pub(super) fn parse_http_response(response: &[u8]) -> Option> { + let header_end = response.windows(4).position(|w| w == b"\r\n\r\n")?; + let head = std::str::from_utf8(&response[..header_end]).ok()?; + let body = &response[header_end + 4..]; + let mut lines = head.split("\r\n"); + let status = lines.next()?.split(' ').nth(1)?; + if status.len() != 3 || !status.starts_with('2') { + return None; + } + let mut content_length = None; + let mut chunked = false; + for line in lines { + let (name, value) = line.split_once(':')?; + let value = value.trim(); + if name.eq_ignore_ascii_case("content-length") { + content_length = Some(value.parse::().ok()?); + } else if name.eq_ignore_ascii_case("transfer-encoding") { + chunked = value.to_ascii_lowercase().contains("chunked"); + } + } + let body = if chunked { + decode_chunked(body)? + } else if let Some(length) = content_length { + body.get(..length)?.to_vec() + } else { + body.to_vec() + }; + (body.len() <= MAX_BLOB_BYTES).then_some(body) + } + + fn decode_chunked(mut body: &[u8]) -> Option> { + let mut decoded = Vec::new(); + loop { + let line_end = body.windows(2).position(|w| w == b"\r\n")?; + let size_line = std::str::from_utf8(&body[..line_end]).ok()?; + let size = usize::from_str_radix(size_line.split(';').next()?.trim(), 16).ok()?; + body = &body[line_end + 2..]; + if size == 0 { + return Some(decoded); + } + if decoded.len().checked_add(size)? > MAX_BLOB_BYTES { + return None; + } + decoded.extend_from_slice(body.get(..size)?); + // Each chunk is followed by its own line break. + let rest = &body[size..]; + if rest.get(..2) != Some(b"\r\n".as_slice()) { + return None; + } + body = &rest[2..]; + } + } + + fn spawn_fetch( + config: &RoomConfig, + events: &async_channel::Sender, + source_id: String, + ) { + let url = config.blob_url(&source_id); + let events = events.clone(); + tokio::spawn(async move { + let bytes = fetch_blob(url).await; + let _ = events.try_send(RoomEvent::Blob { source_id, bytes }); + }); + } + + /// Serve a command while no socket is open; `false` once the link is gone. + fn serve_unconnected( + command: Option, + config: &RoomConfig, + events: &async_channel::Sender, + ) -> bool { + match command { + Some(RoomCommand::FetchBlob(source_id)) => { + spawn_fetch(config, events, source_id); + true + } + // Frames addressed to a closed socket are dropped: the next handshake resends + // whatever the relay is missing. + Some(RoomCommand::Send(_)) => true, + Some(RoomCommand::Close) | None => false, + } + } + + async fn run( + config: RoomConfig, + events: async_channel::Sender, + mut commands: mpsc::UnboundedReceiver, + ) { + let mut backoff = RECONNECT_MIN; + loop { + // A pending connect never holds up blob fetches or shutdown. + let connecting = timeout(HTTP_TIMEOUT, connect_async(config.ws_url.as_str())); + tokio::pin!(connecting); + let connected = loop { + tokio::select! { + result = &mut connecting => break result, + command = commands.recv() => { + if !serve_unconnected(command, &config, &events) { + return; + } + } + } + }; + let reason = match connected { + Ok(Ok((stream, _))) => { + backoff = RECONNECT_MIN; + if events.try_send(RoomEvent::Opened).is_err() { + return; + } + let (mut sink, mut source) = stream.split(); + loop { + tokio::select! { + message = source.next() => match message { + Some(Ok(Message::Binary(bytes))) => { + let frame = RoomFrame::Binary(bytes.to_vec()); + if events.try_send(RoomEvent::Frame(frame)).is_err() { + return; + } + } + Some(Ok(Message::Text(text))) => { + let frame = RoomFrame::Text(text.to_string()); + if events.try_send(RoomEvent::Frame(frame)).is_err() { + return; + } + } + Some(Ok(Message::Close(_))) | None => { + break "connection closed by relay".to_string(); + } + Some(Ok(_)) => {} + Some(Err(err)) => break format!("connection lost: {err}"), + }, + command = commands.recv() => match command { + Some(RoomCommand::Send(RoomFrame::Binary(bytes))) => { + if let Err(err) = sink.send(Message::Binary(bytes.into())).await { + break format!("send failed: {err}"); + } + } + Some(RoomCommand::Send(RoomFrame::Text(text))) => { + if let Err(err) = sink.send(Message::Text(text.into())).await { + break format!("send failed: {err}"); + } + } + Some(RoomCommand::FetchBlob(source_id)) => { + spawn_fetch(&config, &events, source_id); + } + Some(RoomCommand::Close) | None => { + let _ = sink.close().await; + return; + } + }, + } + } + } + Ok(Err(err)) => format!("cannot reach {}: {err}", config.ws_url), + Err(_) => format!("cannot reach {}: the connection timed out", config.ws_url), + }; + if events.try_send(RoomEvent::Closed(reason)).is_err() { + return; + } + + // Wait out the backoff while still serving blob fetches and shutdown. + let retry = tokio::time::sleep(backoff); + tokio::pin!(retry); + loop { + tokio::select! { + () = &mut retry => break, + command = commands.recv() => { + if !serve_unconnected(command, &config, &events) { + return; + } + } + } + } + backoff = (backoff * 2).min(RECONNECT_MAX); + } + } +} + +#[cfg(target_family = "wasm")] +mod web { + use std::{cell::RefCell, rc::Rc}; + + use wasm_bindgen::{JsCast, closure::Closure}; + use web_sys::{BinaryType, CloseEvent, MessageEvent, WebSocket}; + + use super::{RoomCommand, RoomConfig, RoomEvent, RoomFrame, RoomLink}; + + const RECONNECT_MIN_MS: i32 = 250; + const RECONNECT_MAX_MS: i32 = 5_000; + + struct WebTransport { + config: RoomConfig, + events: async_channel::Sender, + socket: RefCell>, + backoff_ms: RefCell, + closed: RefCell, + } + + /// Connect to the room with a browser `WebSocket` carrying binary `ArrayBuffer` + /// frames. The transport reconnects with backoff until the link is dropped. + pub fn connect(config: RoomConfig) -> RoomLink { + let (events_tx, events_rx) = async_channel::unbounded(); + let transport = Rc::new(WebTransport { + config, + events: events_tx, + socket: RefCell::new(None), + backoff_ms: RefCell::new(RECONNECT_MIN_MS), + closed: RefCell::new(false), + }); + open(&transport); + RoomLink::from_parts(events_rx, move |command| match command { + RoomCommand::Send(frame) => { + if let Some(socket) = transport.socket.borrow().as_ref() + && socket.ready_state() == WebSocket::OPEN + { + let _ = match &frame { + RoomFrame::Binary(bytes) => socket.send_with_u8_array(bytes), + RoomFrame::Text(text) => socket.send_with_str(text), + }; + } + } + RoomCommand::FetchBlob(source_id) => fetch_blob(&transport, source_id), + RoomCommand::Close => { + *transport.closed.borrow_mut() = true; + let socket = transport.socket.borrow_mut().take(); + if let Some(socket) = socket { + let _ = socket.close(); + } + } + }) + } + + fn open(transport: &Rc) { + if *transport.closed.borrow() { + return; + } + let socket = match WebSocket::new(&transport.config.ws_url) { + Ok(socket) => socket, + Err(err) => { + let _ = transport + .events + .try_send(RoomEvent::Closed(format!("cannot open WebSocket: {err:?}"))); + schedule_reconnect(transport); + return; + } + }; + socket.set_binary_type(BinaryType::Arraybuffer); + + let on_open = { + let transport = transport.clone(); + Closure::::new(move || { + *transport.backoff_ms.borrow_mut() = RECONNECT_MIN_MS; + let _ = transport.events.try_send(RoomEvent::Opened); + }) + }; + socket.set_onopen(Some(on_open.as_ref().unchecked_ref())); + on_open.forget(); + + let on_message = { + let transport = transport.clone(); + Closure::::new(move |event: MessageEvent| { + let data = event.data(); + let frame = if let Some(text) = data.as_string() { + RoomFrame::Text(text) + } else if data.is_instance_of::() { + RoomFrame::Binary(js_sys::Uint8Array::new(&data).to_vec()) + } else { + return; + }; + let _ = transport.events.try_send(RoomEvent::Frame(frame)); + }) + }; + socket.set_onmessage(Some(on_message.as_ref().unchecked_ref())); + on_message.forget(); + + let on_close = { + let transport = transport.clone(); + Closure::::new(move |event: CloseEvent| { + transport.socket.borrow_mut().take(); + if *transport.closed.borrow() { + return; + } + let reason = match event.reason() { + reason if reason.is_empty() => format!("connection closed ({})", event.code()), + reason => reason, + }; + let _ = transport.events.try_send(RoomEvent::Closed(reason)); + schedule_reconnect(&transport); + }) + }; + socket.set_onclose(Some(on_close.as_ref().unchecked_ref())); + on_close.forget(); + + *transport.socket.borrow_mut() = Some(socket); + } + + fn schedule_reconnect(transport: &Rc) { + let Some(window) = web_sys::window() else { + return; + }; + let delay = *transport.backoff_ms.borrow(); + *transport.backoff_ms.borrow_mut() = (delay * 2).min(RECONNECT_MAX_MS); + let transport = transport.clone(); + let retry = Closure::once_into_js(move || open(&transport)); + let _ = window + .set_timeout_with_callback_and_timeout_and_arguments_0(retry.unchecked_ref(), delay); + } + + fn fetch_blob(transport: &Rc, source_id: String) { + let url = transport.config.blob_url(&source_id); + let events = transport.events.clone(); + wasm_bindgen_futures::spawn_local(async move { + let bytes = fetch_bytes(&url).await; + let _ = events.try_send(RoomEvent::Blob { source_id, bytes }); + }); + } + + async fn fetch_bytes(url: &str) -> Option> { + let window = web_sys::window()?; + let response = wasm_bindgen_futures::JsFuture::from(window.fetch_with_str(url)) + .await + .ok()? + .dyn_into::() + .ok()?; + if !response.ok() { + return None; + } + let buffer = wasm_bindgen_futures::JsFuture::from(response.array_buffer().ok()?) + .await + .ok()?; + Some(js_sys::Uint8Array::new(&buffer).to_vec()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use blocksuite_playground_doc::{ + client_id_from_seed, + schema::{BlockSpec, ParagraphType}, + }; + + #[test] + fn room_config_resolves_relay_origins_and_full_room_urls() { + let default = RoomConfig::new("demo", None); + assert_eq!(default.ws_url, "ws://127.0.0.1:8788/native-sync/rooms/demo"); + assert_eq!(default.http_origin, "http://127.0.0.1:8788"); + assert_eq!( + default.blob_url("img 1.png"), + "http://127.0.0.1:8788/api/collection/demo/blob/img%201.png" + ); + + let origin = RoomConfig::new("my room", Some("https://relay.example.com/")); + assert_eq!( + origin.ws_url, + "wss://relay.example.com/native-sync/rooms/my%20room" + ); + assert_eq!(origin.http_origin, "https://relay.example.com"); + + let full = RoomConfig::new("demo", Some("ws://localhost:9000/native-sync/rooms/demo")); + assert_eq!(full.ws_url, "ws://localhost:9000/native-sync/rooms/demo"); + assert_eq!(full.http_origin, "http://localhost:9000"); + } + + #[test] + fn http_response_bodies_follow_length_chunked_and_close_framing() { + use super::native::parse_http_response; + + assert_eq!( + parse_http_response( + b"HTTP/1.1 200 OK\r\ncontent-type: image/png\r\nContent-Length: 3\r\n\r\nabcTRAILING" + ), + Some(b"abc".to_vec()) + ); + assert_eq!( + parse_http_response( + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nWiki\r\n5;x=1\r\npedia\r\n0\r\n\r\n" + ), + Some(b"Wikipedia".to_vec()) + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 204 No Content\r\n\r\n"), + Some(Vec::new()) + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 200 OK\r\n\r\nuntil close"), + Some(b"until close".to_vec()) + ); + // Anything but a complete 2xx response is no blob. + assert_eq!( + parse_http_response(b"HTTP/1.1 404 Not Found\r\n\r\nmissing"), + None + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nshort"), + None + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nWi"), + None + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 200 OK\r\nContent-Length: 3"), + None + ); + // A chunk must end with its own line break and declare a size that fits. + assert_eq!( + parse_http_response( + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nWikiXX0\r\n\r\n" + ), + None + ); + assert_eq!( + parse_http_response( + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nffffffffffffffff\r\nWiki\r\n0\r\n\r\n" + ), + None + ); + } + + #[test] + fn native_transport_rejects_tls_relays_up_front() { + for relay in ["wss://relay.example", "https://relay.example"] { + let config = RoomConfig::new("room", Some(relay)); + assert_eq!(config.ws_url, "wss://relay.example/native-sync/rooms/room"); + assert_eq!(config.http_origin, "https://relay.example"); + let error = config.validate_native().unwrap_err().to_string(); + assert!(error.contains("ws://") && error.contains("wss://relay.example")); + + // The transport reports the reason once and never starts a reconnect loop. + let link = connect(config); + assert_eq!(link.events().try_recv(), Ok(RoomEvent::Closed(error))); + assert!(link.events().is_closed()); + } + for relay in [ + None, + Some("ws://127.0.0.1:8788"), + Some("http://relay.local:9000"), + ] { + assert!(RoomConfig::new("room", relay).validate_native().is_ok()); + } + } + + #[test] + fn closing_the_link_ends_a_pending_connect() { + // A listener that never answers the WebSocket handshake keeps the connect pending. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let relay = format!("ws://{}", listener.local_addr().unwrap()); + let link = connect(RoomConfig::new("room", Some(&relay))); + let events = link.events().clone(); + // A frame for the unopened socket is dropped without ending the transport. + link.send(RoomCommand::Send(RoomFrame::Text("early".to_string()))); + drop(link); + for _ in 0..300 { + if events.is_closed() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!( + events.is_closed(), + "the transport kept connecting after its link was dropped" + ); + assert!(events.try_recv().is_err()); + } + + /// Minimal in-memory hub: answers a `Step1` the way the relay does, from a seeded peer. + fn hub_reply(hub: &mut DocState, room: &str, frame: &RoomFrame) -> Vec { + let RoomFrame::Binary(bytes) = frame else { + return Vec::new(); + }; + match decode_binary_frame(bytes).unwrap() { + RoomBinaryFrame::Doc { + doc_id, + message: DocMessage::Step1(client_sv), + } => { + if doc_id != room { + hub.workspace.ensure_page(&doc_id).unwrap(); + } + let diff = hub.workspace.encode_diff_v1(&doc_id, &client_sv).unwrap(); + let hub_sv = hub.workspace.encode_state_vector_v1(&doc_id).unwrap(); + vec![ + binary(&RoomBinaryFrame::Doc { + doc_id: doc_id.clone(), + message: DocMessage::Step2(diff), + }) + .unwrap(), + binary(&RoomBinaryFrame::Doc { + doc_id, + message: DocMessage::Step1(hub_sv), + }) + .unwrap(), + ] + } + RoomBinaryFrame::Doc { + doc_id, + message: DocMessage::Step2(_), + } => vec![RoomFrame::Text( + serde_json::json!({ "type": "ready", "docId": doc_id }).to_string(), + )], + _ => Vec::new(), + } + } + + #[test] + fn protocol_pulls_root_then_discovered_pages_and_applies_live_updates() { + let room = "room-protocol"; + let mut hub = DocState::new(room, client_id_from_seed(1)).unwrap(); + hub.workspace.initialize_meta().unwrap(); + hub.workspace.create_page("doc:home", "Home", 1).unwrap(); + { + let page = hub.workspace.page_mut("doc:home").unwrap(); + page.add_block( + "page", + BlockSpec::Page { + title: "Home".to_string(), + }, + None, + None, + 10, + ) + .unwrap(); + page.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("page"), + None, + 20, + ) + .unwrap(); + } + + let mut client = DocState::new(room, client_id_from_seed(2)).unwrap(); + let mut protocol = RoomProtocol::new(room); + assert_eq!(protocol.status(), RoomStatus::Connecting); + + // Drive the handshake to a fixed point through the in-memory hub. + let mut outbound = protocol.on_open(&mut client, 0).unwrap().outbound; + let mut doc_changed = false; + let mut rounds = 0; + while !outbound.is_empty() { + rounds += 1; + assert!(rounds < 16, "handshake did not settle"); + let mut next = Vec::new(); + for frame in &outbound { + for reply in hub_reply(&mut hub, room, frame) { + let effects = protocol.on_frame(&mut client, &reply, 5).unwrap(); + doc_changed |= effects.doc_changed; + next.extend(effects.outbound); + } + } + outbound = next; + } + assert!(doc_changed); + assert_eq!(protocol.status(), RoomStatus::Live); + assert_eq!(client.workspace.list_pages().unwrap()[0].id, "doc:home"); + let snapshot = client + .workspace + .page("doc:home") + .unwrap() + .read_page_snapshot() + .unwrap(); + assert_eq!(snapshot.title(), "Home"); + assert_eq!(snapshot.block_count(), 2); + + // A live update from another peer lands in the client document. + let commit = hub + .workspace + .page_mut("doc:home") + .unwrap() + .add_block( + "p-live", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "typed remotely".to_string(), + }, + Some("note"), + None, + 30, + ) + .unwrap() + .expect("commit"); + let update = binary(&RoomBinaryFrame::Doc { + doc_id: "doc:home".to_string(), + message: DocMessage::Update(commit.update), + }) + .unwrap(); + let effects = protocol.on_frame(&mut client, &update, 10).unwrap(); + assert!(effects.doc_changed); + assert!(effects.outbound.is_empty()); + let snapshot = client + .workspace + .page("doc:home") + .unwrap() + .read_page_snapshot() + .unwrap(); + assert!(snapshot.block("p-live").is_some()); + + // Remote presence arrives, then expires after the awareness timeout. + let mut peer = RoomAwareness::new(client_id_from_seed(3)).unwrap(); + let presence = peer + .set_local_payload(&AwarenessPayload::new("Peer", "#ff8a00"), 0) + .unwrap(); + let effects = protocol + .on_frame( + &mut client, + &binary(&RoomBinaryFrame::Awareness(presence)).unwrap(), + 100, + ) + .unwrap(); + assert!(effects.awareness_changed); + assert_eq!(client.awareness.active_remote_clients().len(), 1); + let effects = protocol.tick(&mut client, 100 + 30_000).unwrap(); + assert!(effects.awareness_changed); + assert!(client.awareness.active_remote_clients().is_empty()); + + protocol.on_close("relay stopped"); + assert_eq!( + protocol.status(), + RoomStatus::Offline("relay stopped".to_string()) + ); + } +} diff --git a/blocksuite/native-playground/crates/playground/src/theme.rs b/blocksuite/native-playground/crates/playground/src/theme.rs new file mode 100644 index 0000000000..1eed7af0c9 --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/theme.rs @@ -0,0 +1,384 @@ +//! 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 +//! so `rustfmt` never rewrites the generated sources. + +use std::{borrow::Cow, sync::Arc}; + +use ui::{App, Bounds, Hsla, Pixels, SharedString, TransformationMatrix, Window}; + +#[allow(dead_code, clippy::all)] +pub mod tokens { + include!("../../../tokens/tokens.rs"); +} + +#[allow(dead_code, clippy::all)] +pub mod icons { + include!("../../../tokens/icons.rs"); +} + +pub use icons::{IconDef, icon_by_name}; +pub use tokens::{DARK_THEME, LIGHT_THEME, TYPOGRAPHY, ThemeMode, ThemeTokens}; + +/// Base UI and document font family. +pub const FONT_SANS: &str = "Inter"; +/// Code and inline-code font family. +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" +); +const IBM_PLEX_MONO_REGULAR_TTF: &[u8] = include_bytes!( + "../../../../../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" +); +const IBM_PLEX_MONO_ITALIC_TTF: &[u8] = include_bytes!( + "../../../../../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" +); + +/// Registers the tracked repository fonts (`Inter` and `IBM Plex Mono`) into the active +/// `TextSystem`. +/// +/// Must be called before opening any window across macOS, Linux headless, and Web Wasm. +pub fn register_bundled_fonts(cx: &App) -> anyhow::Result<()> { + cx.text_system().add_fonts(vec![ + Cow::Borrowed(INTER_VARIABLE_TTF), + Cow::Borrowed(IBM_PLEX_MONO_REGULAR_TTF), + Cow::Borrowed(IBM_PLEX_MONO_BOLD_TTF), + Cow::Borrowed(IBM_PLEX_MONO_ITALIC_TTF), + Cow::Borrowed(IBM_PLEX_MONO_BOLD_ITALIC_TTF), + ]) +} + +/// Color theme of the playground chrome and document. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum PlaygroundTheme { + #[default] + Light, + Dark, +} + +impl PlaygroundTheme { + pub fn as_str(self) -> &'static str { + match self { + Self::Light => "light", + Self::Dark => "dark", + } + } + + pub fn parse(value: &str) -> Option { + match value { + "light" => Some(Self::Light), + "dark" => Some(Self::Dark), + _ => None, + } + } + + pub fn toggled(self) -> Self { + match self { + Self::Light => Self::Dark, + Self::Dark => Self::Light, + } + } + + /// The generated tokens' name for this theme. + pub fn mode(self) -> ThemeMode { + match self { + Self::Light => ThemeMode::Light, + Self::Dark => ThemeMode::Dark, + } + } + + /// Generated token set of this theme. + pub fn tokens(self) -> &'static ThemeTokens { + match self { + Self::Light => &LIGHT_THEME, + Self::Dark => &DARK_THEME, + } + } + + /// Resolved colors used by the chrome and the page renderer. + pub fn palette(self) -> Palette { + Palette::new(self) + } + + /// Color of a `--affine-*` CSS variable in this theme. + pub fn css_var(self, name: &str) -> Option { + self.tokens().color(name).map(hsla) + } + + /// Resolve a CSS color as stored in documents and awareness payloads: `var(--name)`, + /// `var(--name, fallback)`, `#rgb`, `#rrggbb` or `#rrggbbaa`. + pub fn css_color(self, value: &str) -> Option { + let value = value.trim(); + if let Some(inner) = value + .strip_prefix("var(") + .and_then(|rest| rest.strip_suffix(')')) + { + let (name, fallback) = match inner.split_once(',') { + Some((name, fallback)) => (name.trim(), Some(fallback)), + None => (inner.trim(), None), + }; + return self + .css_var(name) + .or_else(|| fallback.and_then(|fallback| self.css_color(fallback))); + } + parse_hex_color(value) + } +} + +impl From for PlaygroundTheme { + fn from(mode: ThemeMode) -> Self { + match mode { + ThemeMode::Light => Self::Light, + ThemeMode::Dark => Self::Dark, + } + } +} + +/// Convert a generated token color into a UI color. +pub fn hsla(color: tokens::Rgba) -> Hsla { + let [r, g, b, a] = color.to_f32(); + ui::Rgba { r, g, b, a }.into() +} + +fn parse_hex_color(value: &str) -> Option { + let hex = value.strip_prefix('#')?; + if !hex.is_ascii() { + return None; + } + let channel = |index: usize, width: usize| -> Option { + let digits = hex.get(index * width..(index + 1) * width)?; + let value = u8::from_str_radix(digits, 16).ok()?; + let value = if width == 1 { value * 17 } else { value }; + Some(f32::from(value) / 255.0) + }; + let (width, has_alpha) = match hex.len() { + 3 => (1, false), + 4 => (1, true), + 6 => (2, false), + 8 => (2, true), + _ => return None, + }; + Some( + ui::Rgba { + r: channel(0, width)?, + g: channel(1, width)?, + b: channel(2, width)?, + a: if has_alpha { channel(3, width)? } else { 1.0 }, + } + .into(), + ) +} + +/// Theme colors resolved once per frame from the generated tokens. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Palette { + pub theme: PlaygroundTheme, + /// `--affine-background-primary-color` + pub background: Hsla, + /// `--affine-background-secondary-color` + pub background_secondary: Hsla, + /// `--affine-background-overlay-panel-color` + pub panel: Hsla, + /// `--affine-background-code-block` + pub code_background: Hsla, + /// `--affine-text-primary-color` + pub text_primary: Hsla, + /// `--affine-text-secondary-color` + pub text_secondary: Hsla, + /// `--affine-placeholder-color` + pub placeholder: Hsla, + /// `--affine-border-color` + pub border: Hsla, + /// `--affine-divider-color` + pub divider: Hsla, + /// `--affine-quote-color` + pub quote: Hsla, + /// `--affine-link-color` + pub link: Hsla, + /// `--affine-icon-color` + pub icon: Hsla, + /// `--affine-blue-700`, the list prefix color. + pub list_marker: Hsla, + /// `--affine-brand-color`, the checked to-do box. + pub brand: Hsla, + /// `--affine-hover-color` + pub hover: Hsla, + /// `--affine-v2-layer-background-tertiary`, the embed card border. + pub card_border: Hsla, + /// `--affine-edgeless-grid-color` + pub edgeless_grid: Hsla, + /// `--affine-pure-white`, ink on saturated presence colors. + pub on_accent: Hsla, +} + +impl Palette { + pub fn new(theme: PlaygroundTheme) -> Self { + let tokens = theme.tokens(); + let var = |name: &str, fallback: tokens::Rgba| hsla(tokens.color(name).unwrap_or(fallback)); + Self { + theme, + background: hsla(tokens.background_primary), + background_secondary: hsla(tokens.background_secondary), + panel: hsla(tokens.background_overlay_panel), + code_background: hsla(tokens.background_code_block), + text_primary: hsla(tokens.text_primary), + text_secondary: hsla(tokens.text_secondary), + placeholder: hsla(tokens.placeholder), + border: hsla(tokens.border), + divider: hsla(tokens.divider), + quote: hsla(tokens.quote), + link: hsla(tokens.link), + icon: hsla(tokens.icon), + list_marker: var("--affine-blue-700", tokens.primary), + brand: hsla(tokens.brand), + hover: hsla(tokens.hover), + card_border: var("--affine-v2-layer-background-tertiary", tokens.border), + edgeless_grid: hsla(tokens.edgeless_grid), + on_accent: var("--affine-pure-white", tokens::Rgba::new(255, 255, 255, 255)), + } + } +} + +/// Serialize an icon definition as a standalone monochrome SVG document for the SVG renderer. +pub fn icon_svg(icon: &IconDef) -> String { + let mut svg = format!( + r#""#, + icon.view_box + ); + for path in icon.paths { + svg.push_str(r#" "#000", + other => other, + }, + ); + attr("fill-rule", path.fill_rule); + attr("clip-rule", path.clip_rule); + attr( + "stroke", + match path.stroke { + "currentColor" => "#000", + other => other, + }, + ); + attr("stroke-linecap", path.stroke_linecap); + attr("stroke-linejoin", path.stroke_linejoin); + if path.stroke_width > 0.0 { + svg.push_str(&format!(r#" stroke-width="{}""#, path.stroke_width)); + } + svg.push_str("/>"); + } + svg.push_str(""); + svg +} + +/// An icon ready to paint through the monochrome SVG renderer. +#[derive(Clone)] +pub struct IconPaint { + key: SharedString, + svg: Arc, +} + +impl IconPaint { + pub fn new(icon: &IconDef) -> Self { + Self { + key: SharedString::from(format!("playground-icon:{}", icon.name)), + svg: Arc::from(icon_svg(icon)), + } + } + + /// Look a generated icon up by name; an unknown name paints nothing. + pub fn named(name: &str) -> Self { + match icon_by_name(name) { + Some(icon) => Self::new(icon), + None => Self { + key: SharedString::from(format!("playground-icon:missing:{name}")), + svg: Arc::from(""), + }, + } + } + + /// Paint the icon into `bounds`, tinted with `color`. + pub fn paint(&self, bounds: Bounds, color: Hsla, window: &mut Window, cx: &mut App) { + if self.svg.is_empty() { + return; + } + let _ = window.paint_svg( + bounds, + self.key.clone(), + Some(self.svg.as_bytes()), + TransformationMatrix::unit(), + color, + cx, + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn css_colors_resolve_variables_fallbacks_and_hex() { + let light = PlaygroundTheme::Light; + let dark = PlaygroundTheme::Dark; + + assert_eq!( + light.css_var("--affine-text-primary-color"), + Some(hsla(LIGHT_THEME.text_primary)) + ); + assert_eq!( + dark.css_color("var(--affine-multi-players-purple)"), + dark.css_var("--affine-multi-players-purple") + ); + assert!(dark.css_var("--affine-multi-players-purple").is_some()); + assert_eq!( + light.css_color("var(--affine-not-a-token, #ff8a00)"), + light.css_color("#ff8a00") + ); + assert_eq!(light.css_color("#fff"), light.css_color("#ffffffff")); + assert_eq!(light.css_color("#12"), None); + assert_eq!(light.css_color("rebeccapurple"), None); + assert_eq!(PlaygroundTheme::parse("dark"), Some(dark)); + assert_eq!(dark.toggled(), light); + assert_eq!(light.palette().theme, light); + assert_ne!(light.palette().background, dark.palette().background); + } + + #[test] + fn icons_serialize_to_parseable_monochrome_svg() { + for name in [ + "CheckBoxCheckSolidIcon", + "CheckBoxUnIcon", + "ToggleDownIcon", + "ToggleRightIcon", + "LinkIcon", + "LinkedPageIcon", + ] { + let icon = icon_by_name(name).unwrap_or_else(|| panic!("icon {name} is generated")); + let svg = icon_svg(icon); + assert!(svg.starts_with(""), "{svg}"); + assert_eq!(svg.matches("10%) -> ADVISORY_SLOWDOWN, must exit 0 under --fail-on-regression @@ -313,6 +316,8 @@ test('deterministic hard gate vs advisory shared-runner timings and --fail-on-re timingOnlyPath, '--baseline', basePath, + '--accepted', + noAcceptedPath, '--json-out', jsonOut, '--fail-on-regression', @@ -340,6 +345,8 @@ test('deterministic hard gate vs advisory shared-runner timings and --fail-on-re bytesRegPath, '--baseline', basePath, + '--accepted', + noAcceptedPath, '--json-out', jsonOut, '--fail-on-regression', diff --git a/blocksuite/native-playground/scripts/web-smoke.mjs b/blocksuite/native-playground/scripts/web-smoke.mjs index 9402ee9ebe..b01599e5a6 100755 --- a/blocksuite/native-playground/scripts/web-smoke.mjs +++ b/blocksuite/native-playground/scripts/web-smoke.mjs @@ -9,6 +9,11 @@ * the title and mode-switcher pill regions. * 3. Clicking the `"Edgeless"` button on the `` triggers an observable * visual state transition to Edgeless mode. + * + * `--query ` loads the page with a query string (for example a live room, + * `room=&ws=`), and `--min-title-ink ` raises the amount of ink + * the title/body region must show before the page is captured, so a page that arrives + * over the network is captured after it rendered. */ import { spawn } from 'node:child_process'; @@ -26,12 +31,23 @@ function parseArgs(argv) { const args = { outPage: path.join(ROOT, 'artifacts', 'wasm-chromium.png'), outEdgeless: path.join(ROOT, 'artifacts', 'wasm-chromium-edgeless.png'), + // Query string appended to the page URL, e.g. `room=&ws=`. + query: '', + // Dark ink pixels required in the title/body region before the page is captured. + minTitleInk: 200, }; for (let i = 2; i < argv.length; i += 1) { if (argv[i] === '--out' && argv[i + 1]) { args.outPage = path.resolve(argv[++i]); } else if (argv[i] === '--out-edgeless' && argv[i + 1]) { args.outEdgeless = path.resolve(argv[++i]); + } else if (argv[i] === '--query' && argv[i + 1]) { + args.query = argv[++i].replace(/^\?/, ''); + } else if (argv[i] === '--min-title-ink' && argv[i + 1]) { + args.minTitleInk = Number(argv[++i]); + if (!Number.isFinite(args.minTitleInk) || args.minTitleInk < 0) { + throw new Error('--min-title-ink requires a non-negative number'); + } } } return args; @@ -328,7 +344,8 @@ async function main() { } }); - await cdp.send('Page.navigate', { url: `http://127.0.0.1:${port}/` }); + const pageUrl = `http://127.0.0.1:${port}/${args.query ? `?${args.query}` : ''}`; + await cdp.send('Page.navigate', { url: pageUrl }); // Wait for wasm init + graphics init + ResizeObserver sizing canvas to 1280x800 let ready = false; @@ -385,7 +402,7 @@ async function main() { img1 = decodePngRgba(png1); pillDark = countDarkInkPixels(img1, 547, 8, 733, 44); titleDark = countDarkInkPixels(img1, 168, 100, 900, 260); - if (pillDark >= 40 && titleDark >= 200) { + if (pillDark >= 40 && titleDark >= args.minTitleInk) { break; } } @@ -399,9 +416,9 @@ async function main() { `Expected rendered glyph pixels inside mode-switcher pill (>=40), got ${pillDark}. state=${JSON.stringify(lastState)} logs=${consoleLogs.join(' | ')}`, ); } - if (titleDark < 200) { + if (titleDark < args.minTitleInk) { throw new Error( - `Expected rendered glyph pixels inside title/body region (>=200), got ${titleDark}. state=${JSON.stringify(lastState)} logs=${consoleLogs.join(' | ')}`, + `Expected rendered glyph pixels inside title/body region (>=${args.minTitleInk}), got ${titleDark}. state=${JSON.stringify(lastState)} logs=${consoleLogs.join(' | ')}`, ); } 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 0cfe8a6fa0..8cb936c4fc 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 @@ -11,10 +11,12 @@ import { MemoryBlobSource } from '@blocksuite/affine/sync'; import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import * as Y from 'yjs'; +import { empty } from '../../../../starter/data/empty.js'; import { MockServerBlobSource } from '../../blob/mock-server.js'; import { hasUsablePageRoot, initRoomDocWithSeed, + reusePartialSeedDoc, RoomWebSocketClient, } from '../index.js'; @@ -819,28 +821,7 @@ describe('Rust bs-relay + WorkspaceSession <-> JS BlockSuite TestWorkspace', () const existing = ws.getDoc('doc:home'); const targetWs = existing && !hasUsablePageRoot(existing) - ? (() => { - let claimed = false; - return new Proxy(ws, { - get(target, prop, receiver) { - if (prop === 'getDoc') { - return (id: string) => - id === 'doc:home' && !claimed ? null : target.getDoc(id); - } - if (prop === 'createDoc') { - return (id?: string) => { - if (id === 'doc:home' && !claimed) { - claimed = true; - return existing; - } - return target.createDoc(id); - }; - } - const val = Reflect.get(target, prop, receiver); - return typeof val === 'function' ? val.bind(target) : val; - }, - }); - })() + ? reusePartialSeedDoc(ws, 'doc:home', existing) : ws; // Exact preset.ts pattern: checks hasDoc before populating blocks @@ -915,6 +896,184 @@ describe('Rust bs-relay + WorkspaceSession <-> JS BlockSuite TestWorkspace', () observerClient.close(); }); + it('reusePartialSeedDoc runs the initializer once, on the first load(initFn), even after a bare load()', () => { + const underlyingLoads: boolean[] = []; + const existing = { + load(initFn?: () => void) { + underlyingLoads.push(initFn !== undefined); + }, + }; + const collection: { + getDoc(id: string): typeof existing | null; + createDoc(id?: string): typeof existing; + } = { + getDoc: id => (id === 'doc:home' ? existing : null), + createDoc: () => existing, + }; + const view = reusePartialSeedDoc(collection, 'doc:home', existing); + expect(view.getDoc('doc:home')).toBeNull(); + const doc = view.createDoc('doc:home'); + expect(view.getDoc('doc:home')).toBe(doc); + + let initRuns = 0; + doc.load(); + expect(initRuns).toBe(0); + doc.load(() => { + initRuns += 1; + }); + doc.load(() => { + initRuns += 1; + }); + expect(initRuns).toBe(1); + // The already loaded doc is only ever loaded bare; the view runs the initializer. + expect(underlyingLoads).toEqual([false, false, false]); + }); + + it('Promoted partial-seed winner runs an empty-style doc.load(initFn) initializer in place while a waiting observer converges', async () => { + const room = 'room-partial-seed-load-callback'; + const makePeer = () => { + const client = new RoomWebSocketClient( + `${relayWsBase}/native-sync/rooms/${room}` + ); + const workspace = new TestWorkspace({ + id: room, + docSources: { main: client.createDocSource() }, + awarenessSources: [client.createAwarenessSource()], + blobSources: { main: new MemoryBlobSource() }, + }); + workspace.storeExtensions = AffineSchemas.map(s => + BlockSchemaExtension(s) + ); + workspace.start(); + return { client, workspace }; + }; + + const { client: winnerClient, workspace: winnerWs } = makePeer(); + const { client: survivorClient, workspace: survivorWs } = makePeer(); + const { client: observerClient, workspace: observerWs } = makePeer(); + + await Promise.all([ + winnerWs.waitForSynced(), + survivorWs.waitForSynced(), + observerWs.waitForSynced(), + ]); + + // The winner pushes only the meta.pages entry for doc:home, then disappears. + expect(await winnerClient.claimSeed('seed:doc:home')).toBe(true); + winnerWs.meta.initialize(); + winnerWs.createDoc('doc:home'); + await winnerWs.waitForSynced(); + await vi.waitFor( + () => { + expect(survivorWs.getDoc('doc:home')).not.toBeNull(); + expect(observerWs.getDoc('doc:home')).not.toBeNull(); + }, + { timeout: 5_000 } + ); + + // Starter wiring with the real `empty` initializer, which adds its blocks inside + // `doc.load(() => { ... })`. initRoomDocWithSeed has already loaded the partial + // doc by the time the seed runs, so the callback must still fire through the + // reused doc. + let seedRuns = 0; + const emptyStyleSeed = (ws: TestWorkspace) => { + const existing = ws.getDoc('doc:home'); + const seedCollection = + existing && !hasUsablePageRoot(existing) + ? reusePartialSeedDoc(ws, 'doc:home', existing) + : ws; + seedRuns += 1; + return empty(seedCollection, 'doc:home'); + }; + + const survivorInitPromise = initRoomDocWithSeed({ + collection: survivorWs, + roomClient: survivorClient, + docId: 'doc:home', + seedKey: 'seed:doc:home', + seed: () => emptyStyleSeed(survivorWs), + }); + await new Promise(resolve => setTimeout(resolve, 60)); + const observerInitPromise = initRoomDocWithSeed({ + collection: observerWs, + roomClient: observerClient, + docId: 'doc:home', + seedKey: 'seed:doc:home', + seed: () => emptyStyleSeed(observerWs), + }); + + await new Promise(resolve => setTimeout(resolve, 100)); + winnerWs.forceStop(); + winnerWs.dispose(); + winnerClient.close(); + + const [survivorResult, observerResult] = await Promise.all([ + survivorInitPromise, + observerInitPromise, + ]); + expect(survivorResult).toEqual({ seeded: true, offlineFallback: false }); + expect(observerResult).toEqual({ seeded: false, offlineFallback: false }); + expect(seedRuns).toBe(1); + + // Both peers hold the single page root the empty initializer builds: + // affine:page + affine:surface + affine:note + affine:paragraph. + for (const ws of [survivorWs, observerWs]) { + await ws.waitForSynced(); + expect(ws.meta.docMetas.length).toBe(1); + const seededDoc = ws.getDoc('doc:home')!; + expect(hasUsablePageRoot(seededDoc)).toBe(true); + const blocks = seededDoc.spaceDoc.getMap('blocks'); + const flavours = Array.from(blocks.values()) + .map(b => String((b as Y.Map).get('sys:flavour'))) + .sort((a, b) => a.localeCompare(b)); + expect(flavours).toEqual([ + 'affine:note', + 'affine:page', + 'affine:paragraph', + 'affine:surface', + ]); + } + + // A winner whose seed leaves no page root is rejected instead of reporting success. + const { client: brokenClient, workspace: brokenWs } = (() => { + const client = new RoomWebSocketClient( + `${relayWsBase}/native-sync/rooms/room-seed-without-root` + ); + const workspace = new TestWorkspace({ + id: 'room-seed-without-root', + docSources: { main: client.createDocSource() }, + awarenessSources: [client.createAwarenessSource()], + blobSources: { main: new MemoryBlobSource() }, + }); + workspace.storeExtensions = AffineSchemas.map(s => + BlockSchemaExtension(s) + ); + workspace.start(); + return { client, workspace }; + })(); + await expect( + initRoomDocWithSeed({ + collection: brokenWs, + roomClient: brokenClient, + docId: 'doc:home', + seedKey: 'seed:doc:home', + seed: () => { + brokenWs.createDoc('doc:home'); + }, + }) + ).rejects.toThrow('finished without an affine:page root block'); + + for (const { ws, client } of [ + { ws: survivorWs, client: survivorClient }, + { ws: observerWs, client: observerClient }, + { ws: brokenWs, client: brokenClient }, + ]) { + ws.forceStop(); + ws.dispose(); + client.close(); + } + }); + it('JS dropConnection() mid-edit reconnects with L0 convergence and live bidirectional awareness', async () => { const room = 'room-js-drop-reconnect'; const rustClientId = 2 ** 44 + 11; diff --git a/blocksuite/playground/apps/_common/sync/room/index.ts b/blocksuite/playground/apps/_common/sync/room/index.ts index a24a155480..f8e06b1c35 100644 --- a/blocksuite/playground/apps/_common/sync/room/index.ts +++ b/blocksuite/playground/apps/_common/sync/room/index.ts @@ -562,6 +562,69 @@ export function hasUsablePageRoot(doc: RoomSeedDocHandle | null): boolean { return false; } +/** + * Collection view for seeding a document that already exists without a page root (a + * previous seed winner pushed its `meta.pages` entry and left before adding blocks). + * + * Initializers start with `collection.getDoc(id) ?? collection.createDoc(id)` and then + * either branch on "did the doc exist" or populate it inside `doc.load(() => { ... })`. + * Through this view the first `getDoc(docId)` answers `null` and `createDoc(docId)` hands + * back the existing doc, so the initializer fills it in place; `removeDoc` is never + * needed, which would destroy `spaces[docId]` on the other peers. The doc handed back + * runs the first `load` callback it is given once, even though the underlying doc has + * been loaded already. + */ +export function reusePartialSeedDoc< + Doc extends { load(initFn?: () => void): unknown }, + Collection extends { + getDoc(id: string): Doc | null; + createDoc(id?: string): Doc; + }, +>(collection: Collection, docId: string, existing: Doc): Collection { + let claimed = false; + let initialized = false; + const seedDoc: Doc = new Proxy(existing, { + get(target, prop) { + if (prop === 'load') { + return (initFn?: () => void) => { + target.load(); + // A bare `load()` leaves the initializer for the `load(initFn)` that follows. + if (initFn && !initialized) { + initialized = true; + initFn(); + } + return seedDoc; + }; + } + const value = Reflect.get(target, prop, target); + return typeof value === 'function' ? value.bind(target) : value; + }, + }); + return new Proxy(collection, { + get(target, prop) { + if (prop === 'getDoc') { + return (id: string) => { + if (id === docId) { + return claimed ? seedDoc : null; + } + return target.getDoc(id); + }; + } + if (prop === 'createDoc') { + return (id?: string) => { + if (id === docId) { + claimed = true; + return seedDoc; + } + return target.createDoc(id); + }; + } + const value = Reflect.get(target, prop, target); + return typeof value === 'function' ? value.bind(target) : value; + }, + }); +} + async function waitForUsablePageRoot(doc: RoomSeedDocHandle): Promise { if (hasUsablePageRoot(doc)) return; const spaceDoc = doc.spaceDoc; @@ -623,8 +686,9 @@ async function waitForDocArrival( * WebSocket connection itself fails (`allowOfflineFallback: true`). * - Once connected, waits for initial sync (never timing out into local seeding). * - If `docId` already exists with a usable `affine:page` root, loads it without re-seeding. - * - Otherwise claims `seedKey` over WebSocket: only the single winner seeds `docId`, - * while non-winners wait for `docId` to arrive and load it. + * - Otherwise claims `seedKey` over WebSocket: only the single winner seeds `docId` + * (and must leave it with an `affine:page` root, or this rejects), while non-winners + * wait for `docId` to arrive and load it. */ export async function initRoomDocWithSeed({ collection, @@ -677,6 +741,12 @@ export async function initRoomDocWithSeed({ if (doc && !doc.loaded) { doc.load(); } + // The winner is the only peer that seeds: the waiters block on this page root. + if (!hasUsablePageRoot(doc)) { + throw new Error( + `Seeding "${docId}" finished without an affine:page root block` + ); + } await collection.waitForSynced(); return { seeded: true, offlineFallback: false }; } diff --git a/blocksuite/playground/apps/starter/utils/collection.ts b/blocksuite/playground/apps/starter/utils/collection.ts index c78aba8980..24a631999e 100644 --- a/blocksuite/playground/apps/starter/utils/collection.ts +++ b/blocksuite/playground/apps/starter/utils/collection.ts @@ -20,6 +20,7 @@ import { MockServerBlobSource } from '../../_common/sync/blob/mock-server.js'; import { hasUsablePageRoot, initRoomDocWithSeed, + reusePartialSeedDoc, RoomWebSocketClient, } from '../../_common/sync/room/index.js'; import type { InitFn } from '../data/utils.js'; @@ -162,38 +163,13 @@ export async function initStarterDocCollection(collection: TestWorkspace) { seedKey: 'seed:doc:home', seed: async () => { // If a previous winner pushed meta.pages for doc:home and disconnected - // before seeding doc:home's blocks, reuse the existing doc:home in-place - // without calling removeDoc (which would destroy spaces['doc:home'] on other peers). + // before seeding doc:home's blocks, populate the existing doc:home in place. const existing = collection.getDoc('doc:home'); - if (existing && !hasUsablePageRoot(existing)) { - let claimedExisting = false; - const seedCollection = new Proxy(collection, { - get(target, prop, receiver) { - if (prop === 'getDoc') { - return (id: string) => { - if (id === 'doc:home' && !claimedExisting) { - return null; - } - return target.getDoc(id); - }; - } - if (prop === 'createDoc') { - return (id?: string) => { - if (id === 'doc:home' && !claimedExisting) { - claimedExisting = true; - return existing; - } - return target.createDoc(id); - }; - } - const val = Reflect.get(target, prop, receiver); - return typeof val === 'function' ? val.bind(target) : val; - }, - }); - await initFn?.(seedCollection, 'doc:home'); - } else { - await initFn?.(collection, 'doc:home'); - } + const seedCollection = + existing && !hasUsablePageRoot(existing) + ? reusePartialSeedDoc(collection, 'doc:home', existing) + : collection; + await initFn?.(seedCollection, 'doc:home'); }, allowOfflineFallback: !explicitRelayWs, onOfflineFallback: () => {