mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
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.
This commit is contained in:
1 parent
25a35c83b8
commit
bdad4ecff5
24 files changed
+9471
-471
No files matched your search
@@ -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:<docId>`), `?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:<docId>`), 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.<blockId>`, `page.presence.<clientId>.caret|label`, `chrome.theme_toggle`, `chrome.presence.<clientId>`. 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 <room> [--relay <ws_url>]`), a browser `WebSocket` on the Web (`?room=<room>&ws=<ws_url>`), 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 `<pageId>` or `<pageId>:<managerId>` (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 `<svg fill>` and stroke attributes), and `fonts.lock` (SHA-256 font asset manifest + `CommunityCanvasTextFonts` descriptors), with `--check` and `rustc --edition 2024 --test` enforced on every push in CI. `style-oracle.json` is regenerated via Vitest Browser (`extract-style-oracle.spec.ts`, `isolate: false` reusable iframe) whenever BlockSuite styles or themes change (until its browser CI job lands).
|
||||
|
||||
### 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
|
||||
|
||||
Generated
+7
@@ -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",
|
||||
]
|
||||
|
||||
@@ -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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
self.inner.clear_local_state();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<TextDeltaOp>,
|
||||
}
|
||||
|
||||
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<Self> {
|
||||
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<TextAlign>,
|
||||
},
|
||||
List {
|
||||
kind: ListType,
|
||||
checked: bool,
|
||||
collapsed: bool,
|
||||
text: RichText,
|
||||
/// Raw `prop:order` as stored by BlockSuite.
|
||||
order: Option<i64>,
|
||||
/// 1-based position inside its run of consecutive numbered siblings
|
||||
/// (`None` unless `kind` is [`ListType::Numbered`]).
|
||||
numbered_index: Option<u32>,
|
||||
/// `prop:textAlign`, when the block sets one.
|
||||
text_align: Option<TextAlign>,
|
||||
},
|
||||
Divider,
|
||||
Code {
|
||||
language: String,
|
||||
wrap: bool,
|
||||
text: String,
|
||||
caption: String,
|
||||
},
|
||||
Image {
|
||||
source_id: String,
|
||||
width: Option<f64>,
|
||||
height: Option<f64>,
|
||||
caption: String,
|
||||
},
|
||||
Bookmark {
|
||||
url: String,
|
||||
title: Option<String>,
|
||||
description: Option<String>,
|
||||
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<i64>,
|
||||
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<String, JsonValue>,
|
||||
pub children: Vec<BlockNode>,
|
||||
}
|
||||
|
||||
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<Item = &BlockNode> {
|
||||
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<BlockNode>,
|
||||
/// Blocks present in `blocks` but not reachable from `root`, as subtrees ordered by id.
|
||||
pub detached: Vec<BlockNode>,
|
||||
}
|
||||
|
||||
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<i64>,
|
||||
children: Vec<String>,
|
||||
entries: BTreeMap<String, SessionReadValue>,
|
||||
}
|
||||
|
||||
struct SnapshotReader<'a> {
|
||||
page: &'a PageDocSession,
|
||||
raw: BTreeMap<String, RawBlock>,
|
||||
visited: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl PageDocSession {
|
||||
/// Read the whole `blocks` tree into a typed, ordered [`PageSnapshot`].
|
||||
pub fn read_page_snapshot(&self) -> DocResult<PageSnapshot> {
|
||||
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<String> = reader
|
||||
.raw
|
||||
.values()
|
||||
.flat_map(|block| block.children.iter().cloned())
|
||||
.collect();
|
||||
let ids: Vec<String> = 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<Option<BlockNode>> {
|
||||
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<BlockContent> {
|
||||
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<RichText> {
|
||||
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<usize> {
|
||||
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<TextDeltaOp>) -> RichText {
|
||||
let mut plain = String::new();
|
||||
let mut delta: Vec<TextDeltaOp> = 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<u32> = 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<f64> {
|
||||
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<String> {
|
||||
match value {
|
||||
Some(SessionReadValue::Any(Any::String(s))) => Some(s.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn text_align(value: Option<&SessionReadValue>) -> Option<TextAlign> {
|
||||
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<f64> {
|
||||
match value {
|
||||
Some(SessionReadValue::Any(any)) => any_as_f64(any).filter(|v| v.is_finite()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -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<u64> = 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();
|
||||
|
||||
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
|
||||
@@ -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<SelectionSnapshot> {
|
||||
&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<u64>,
|
||||
now_ms: u64,
|
||||
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
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<String>,
|
||||
flavour: &str,
|
||||
version: i32,
|
||||
props: Vec<(String, SessionValue)>,
|
||||
parent_id: Option<&str>,
|
||||
index: Option<u64>,
|
||||
now_ms: u64,
|
||||
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
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<u64>,
|
||||
now_ms: u64,
|
||||
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
|
||||
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<JsonValue> {
|
||||
pub(crate) fn export_y_value(&self, value: &SessionReadValue) -> DocResult<JsonValue> {
|
||||
match value {
|
||||
SessionReadValue::Any(any) => Ok(any_to_normalized_json(any)),
|
||||
SessionReadValue::Map(id) => {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<i32>) -> 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<u32> {
|
||||
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::<Vec<_>>(),
|
||||
["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::<Vec<_>>(),
|
||||
[
|
||||
"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<String>)> = 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::<Vec<_>>(),
|
||||
["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());
|
||||
}
|
||||
@@ -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",
|
||||
] }
|
||||
@@ -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<HeadlessSession> {
|
||||
fn start_headless_session(
|
||||
width: u32,
|
||||
height: u32,
|
||||
options: PlaygroundOptions,
|
||||
) -> Result<HeadlessSession> {
|
||||
let platform = HeadlessPlatform::new(width, height, 1.0);
|
||||
let init_cell: Rc<RefCell<Option<Result<WindowHandle<PlaygroundView>>>>> =
|
||||
Rc::new(RefCell::new(None));
|
||||
@@ -84,7 +90,7 @@ fn start_headless_session(width: u32, height: u32) -> Result<HeadlessSession> {
|
||||
|
||||
let app = Application::with_platform(platform.clone()).run_embedded(move |cx| {
|
||||
let res = (|| -> Result<WindowHandle<PlaygroundView>> {
|
||||
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<HeadlessSession> {
|
||||
))),
|
||||
..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" => {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -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 <room> [--relay <ws_url>]]"
|
||||
);
|
||||
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))
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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<String>,
|
||||
pub reference: Option<InlineReference>,
|
||||
/// Text color as stored in the document (`var(--token)` or a hex color).
|
||||
pub color: Option<String>,
|
||||
/// Highlight color as stored in the document (`var(--token)` or a hex color).
|
||||
pub background: Option<String>,
|
||||
}
|
||||
|
||||
fn string_attr(value: Option<&Any>) -> Option<String> {
|
||||
@@ -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<f32>,
|
||||
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<u64>,
|
||||
/// 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<Item = StyledFragment<'_>> {
|
||||
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<usize> {
|
||||
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<usize> = 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<Pixels> {
|
||||
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<Pixels> {
|
||||
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<Pixels>,
|
||||
selections: &[(Range<u64>, Hsla)],
|
||||
carets: &[(CaretPosition, Hsla)],
|
||||
hovered_link: Option<&Range<u64>>,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
static PAGE_ICON: std::sync::OnceLock<IconPaint> = std::sync::OnceLock::new();
|
||||
let translated = |b: Bounds<Pixels>| 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<Pixels>,
|
||||
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<Pixels>) -> CaretPosition {
|
||||
let i = self
|
||||
.lines
|
||||
@@ -1037,84 +1212,18 @@ impl RichParagraphElement {
|
||||
|
||||
fn paint(self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) {
|
||||
let layout = &self.layout;
|
||||
let translated = |b: Bounds<Pixels>| 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.);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<Self> {
|
||||
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<Hsla> {
|
||||
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<Hsla> {
|
||||
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<ThemeMode> 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<Hsla> {
|
||||
let hex = value.strip_prefix('#')?;
|
||||
if !hex.is_ascii() {
|
||||
return None;
|
||||
}
|
||||
let channel = |index: usize, width: usize| -> Option<f32> {
|
||||
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#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="{}" fill="none">"#,
|
||||
icon.view_box
|
||||
);
|
||||
for path in icon.paths {
|
||||
svg.push_str(r#"<path d=""#);
|
||||
svg.push_str(path.d);
|
||||
svg.push('"');
|
||||
let mut attr = |name: &str, value: &str| {
|
||||
if !value.is_empty() {
|
||||
svg.push_str(&format!(r#" {name}="{value}""#));
|
||||
}
|
||||
};
|
||||
attr(
|
||||
"fill",
|
||||
match path.fill {
|
||||
"" | "currentColor" => "#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>");
|
||||
svg
|
||||
}
|
||||
|
||||
/// An icon ready to paint through the monochrome SVG renderer.
|
||||
#[derive(Clone)]
|
||||
pub struct IconPaint {
|
||||
key: SharedString,
|
||||
svg: Arc<str>,
|
||||
}
|
||||
|
||||
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<Pixels>, 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 "), "{svg}");
|
||||
assert!(svg.ends_with("</svg>"), "{svg}");
|
||||
assert_eq!(svg.matches("<path ").count(), icon.paths.len());
|
||||
assert!(!svg.contains("currentColor"), "{svg}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1 +1,17 @@
|
||||
[]
|
||||
[
|
||||
{
|
||||
"metric": "artifacts_bytes.web_wasm_raw",
|
||||
"accepted_value": 14831945,
|
||||
"reason": "Links blocksuite-playground-doc, 4 IBM Plex Mono faces, image decoders, RichParagraph, BlockFlow, and native/Web room sync client into playground"
|
||||
},
|
||||
{
|
||||
"metric": "artifacts_bytes.web_wasm_gzip",
|
||||
"accepted_value": 5016905,
|
||||
"reason": "Links blocksuite-playground-doc, 4 IBM Plex Mono faces, image decoders, RichParagraph, BlockFlow, and native/Web room sync client into playground"
|
||||
},
|
||||
{
|
||||
"metric": "artifacts_bytes.headless_bin",
|
||||
"accepted_value": 92078597,
|
||||
"reason": "Links blocksuite-playground-doc, 4 IBM Plex Mono faces, image decoders, RichParagraph, BlockFlow, and native/Web room sync client into playground"
|
||||
}
|
||||
]
|
||||
@@ -273,6 +273,9 @@ test('deterministic hard gate vs advisory shared-runner timings and --fail-on-re
|
||||
const timingOnlyPath = path.join(dir, 'timing-only.json');
|
||||
const bytesRegPath = path.join(dir, 'bytes-reg.json');
|
||||
const jsonOut = path.join(dir, 'verdict.json');
|
||||
// The gate itself is under test: no ceiling from the repository's perf/accepted.json applies.
|
||||
const noAcceptedPath = path.join(dir, 'accepted.json');
|
||||
fs.writeFileSync(noAcceptedPath, '[]');
|
||||
|
||||
fs.writeFileSync(basePath, JSON.stringify(makeMetrics('1'.repeat(40))));
|
||||
// Only *_ms timings slowed down (>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',
|
||||
|
||||
@@ -9,6 +9,11 @@
|
||||
* the title and mode-switcher pill regions.
|
||||
* 3. Clicking the `"Edgeless"` button on the `<canvas>` triggers an observable
|
||||
* visual state transition to Edgeless mode.
|
||||
*
|
||||
* `--query <string>` loads the page with a query string (for example a live room,
|
||||
* `room=<room>&ws=<ws_url>`), and `--min-title-ink <pixels>` 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=<room>&ws=<ws_url>`.
|
||||
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(' | ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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<unknown>).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;
|
||||
|
||||
@@ -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<void> {
|
||||
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 };
|
||||
}
|
||||
|
||||
@@ -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: () => {
|
||||
|
||||
Reference in new issue
Block a user