fix(editor,ui,doc,mobile): resolve real-corpus layout fidelity, legacy numeric cells, and touch cold-start keyboard

This commit is contained in:
DarkSky committed 2026-11-29 05:35:31 +09:00
1 parent 59af2bcbe1
commit 2612b7ec8a
45 files changed
+1624 -579

No files matched your search

+1 -1
View File
@@ -20,7 +20,7 @@ These crates belong to the client Cargo workspace rooted at `packages/frontend/C
- **First-line prefixes**: List bullets, numbers, checkboxes and toggles are placed against the first line of the item's text, and a numbered prefix sits on that line's baseline. Single-style labels (title, code, captions, cards) use the plain `InlineLayout`.
- **Snapshot ids**: `page.title_block`, `page.local_caret`, `page.selection`, `page.block.<blockId>`, `page.presence.<clientId>.caret|label`, `chrome.theme_toggle`, `chrome.presence.<clientId>`; block controls and overlays are listed under *Overlays and block controls*. A block, a control or a marker records its element snapshot only while it lies completely inside the page viewport; one cut by the fold is clipped on purpose.
- **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.
- **Images and blobs**: A blob present in the document state is decoded once (PNG, JPEG, WebP, GIF, BMP); bytes that are no such image (or missing blobs in offline mode without a live room) stay `Image loading failed.` in a full-width 78 px error card 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 loading failed.` 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.
### Page editing
+34 -2
View File
@@ -64,12 +64,25 @@ pub enum DatabaseCellValue {
Json(JsonValue),
}
fn parse_finite_number_str(s: &str) -> Option<f64> {
let trimmed = s.trim();
if trimmed.is_empty() {
return None;
}
trimmed.parse::<f64>().ok().filter(|n| n.is_finite())
}
impl DatabaseCellValue {
pub fn as_f64(&self) -> Option<f64> {
match self {
Self::Number(n) if n.is_finite() => Some(*n),
Self::Integer(n) => Some(*n as f64),
Self::Json(v) => v.as_f64().filter(|n| n.is_finite()),
Self::Text(s) => parse_finite_number_str(s),
Self::RichText(rt) => parse_finite_number_str(&rt.plain),
Self::Json(v) => v
.as_f64()
.filter(|n| n.is_finite())
.or_else(|| v.as_str().and_then(parse_finite_number_str)),
_ => None,
}
}
@@ -78,9 +91,28 @@ impl DatabaseCellValue {
match self {
Self::Integer(n) => Some(*n),
Self::Number(n) if n.is_finite() => Some(*n as i64),
Self::Text(s) => {
let trimmed = s.trim();
trimmed
.parse::<i64>()
.ok()
.or_else(|| parse_finite_number_str(trimmed).map(|n| n as i64))
}
Self::RichText(rt) => {
let trimmed = rt.plain.trim();
trimmed
.parse::<i64>()
.ok()
.or_else(|| parse_finite_number_str(trimmed).map(|n| n as i64))
}
Self::Json(v) => v
.as_i64()
.or_else(|| v.as_f64().filter(|n| n.is_finite()).map(|n| n as i64)),
.or_else(|| v.as_f64().filter(|n| n.is_finite()).map(|n| n as i64))
.or_else(|| {
v.as_str()
.and_then(parse_finite_number_str)
.map(|n| n as i64)
}),
_ => None,
}
}
+4
View File
@@ -237,6 +237,10 @@ impl PageDocSession {
})
}
pub(super) fn session(&self) -> &DocSession<SelectionSnapshot> {
&self.session
}
/// Monotonically increasing revision bumped on every applied local or remote mutation,
/// including delete-only updates that leave the Yjs state vector unchanged.
pub fn revision(&self) -> u64 {
+122 -1
View File
@@ -238,7 +238,17 @@ impl WorkspaceSession {
}
Ok(None)
}
/// List active (non-trashed) pages in `meta.pages`.
pub fn list_pages(&self) -> DocResult<Vec<PageMeta>> {
self.list_pages_filtered(false)
}
/// List all pages in `meta.pages`, including trashed (`trash: true`) entries.
pub fn list_all_pages(&self) -> DocResult<Vec<PageMeta>> {
self.list_pages_filtered(true)
}
fn list_pages_filtered(&self, include_trash: bool) -> DocResult<Vec<PageMeta>> {
let Some(meta_id) = self.root.resolve_path(&TypePath::root("meta")) else {
return Ok(Vec::new());
};
@@ -269,6 +279,7 @@ impl WorkspaceSession {
let mut create_date = 0i64;
let mut updated_date = None;
let mut tags = Vec::new();
let mut trash = false;
for (k, v) in entries {
match k.as_str() {
"id" => {
@@ -304,10 +315,15 @@ impl WorkspaceSession {
}
}
}
"trash" => {
if matches!(v, SessionReadValue::Any(Any::True)) {
trash = true;
}
}
_ => {}
}
}
if !id.is_empty() {
if !id.is_empty() && (include_trash || !trash) {
result.push(PageMeta {
id,
title,
@@ -321,6 +337,43 @@ impl WorkspaceSession {
Ok(result)
}
/// Return the set of page ids configured with `pageWidth = "fullWidth"` in `db$docProperties`
/// when that subdoc is present in this workspace session (`None` when the subdoc is absent).
pub fn full_width_pages(&self) -> Option<std::collections::BTreeSet<String>> {
let props_doc = self.pages.get("db$docProperties")?;
let mut out = std::collections::BTreeSet::new();
let session = props_doc.session();
let Some(table_id) = session.resolve_path(&TypePath::root("docProperties")) else {
return Some(out);
};
let Ok(rows) = session.read_map(&TypeTarget::Identity(table_id)) else {
return Some(out);
};
for (row_id, val) in rows {
let SessionReadValue::Map(row_map_id) = val else {
continue;
};
let Ok(fields) = session.read_map(&TypeTarget::Identity(row_map_id)) else {
continue;
};
let mut deleted = false;
let mut is_full_width = false;
for (k, v) in fields {
if k == "$$DELETED" && matches!(v, SessionReadValue::Any(Any::True)) {
deleted = true;
} else if k == "pageWidth"
&& matches!(v, SessionReadValue::Any(Any::String(s)) if s == "fullWidth")
{
is_full_width = true;
}
}
if !deleted && is_full_width {
out.insert(row_id);
}
}
Some(out)
}
/// Encode state vector for either the root workspace doc (`doc_id == room`) or a page subdoc.
pub fn encode_state_vector_v1(&self, doc_id: &str) -> DocResult<Vec<u8>> {
if doc_id == self.room {
@@ -369,4 +422,72 @@ mod tests {
"corrupted meta.pages = 42 must return Err, not Ok(vec![])"
);
}
#[test]
fn list_pages_filters_trashed_and_reads_full_width_doc_properties() {
let mut ws = WorkspaceSession::new("ws-trash-and-width", 102).expect("ws");
ws.initialize_meta().expect("init meta");
ws.create_page("doc:active", "Active Doc", 1000)
.expect("active");
ws.create_page("doc:trashed", "Trashed Doc", 2000)
.expect("trashed");
// Mark `doc:trashed` with `trash: true` in `meta.pages`.
let pages_target = TypeTarget::Path(TypePath::root("meta").key("pages"));
for item in ws.root().read_array(&pages_target).expect("read pages") {
if let SessionReadValue::Map(map_id) = item {
let target = TypeTarget::Identity(map_id);
if matches!(
ws.root().get_map_value(&target, "id").expect("id"),
Some(SessionReadValue::Any(Any::String(s))) if s == "doc:trashed"
) {
ws.root_mut()
.map_set(&target, "trash".into(), SessionValue::Any(Any::True))
.expect("set trash");
}
}
}
let active = ws.list_pages().expect("list active");
assert_eq!(active.len(), 1);
assert_eq!(active[0].id, "doc:active");
let all = ws.list_all_pages().expect("list all");
assert_eq!(all.len(), 2);
assert!(ws.full_width_pages().is_none());
// Load a synthetic `db$docProperties` subdoc with `pageWidth = "fullWidth"`.
let props_doc = ws.ensure_page("db$docProperties").expect("docProps");
let table_id = props_doc
.session
.ensure_root("docProperties", YTypeKind::Map)
.expect("table");
props_doc
.session
.map_set(
&TypeTarget::Identity(table_id.clone()),
"doc:active".into(),
SessionValue::Map(vec![(
"pageWidth".into(),
SessionValue::Any(Any::String("fullWidth".into())),
)]),
)
.expect("set fullWidth");
let full_width = ws.full_width_pages().expect("present");
assert!(full_width.contains("doc:active"));
assert!(!full_width.contains("doc:trashed"));
// Switching back to standard must yield Some(empty set) rather than None.
ws.ensure_page("db$docProperties")
.unwrap()
.session
.map_set(
&TypeTarget::Identity(table_id),
"doc:active".into(),
SessionValue::Map(vec![(
"pageWidth".into(),
SessionValue::Any(Any::String("standard".into())),
)]),
)
.expect("set standard");
assert!(ws.full_width_pages().expect("present").is_empty());
}
}
+90 -136
View File
@@ -453,38 +453,90 @@ impl FlowPass<'_> {
}
_ => None,
};
// Explicit block dimensions win; otherwise the image's own size, then a 16:9 frame.
let (mut w, mut h) = match (image_width, image_height, natural) {
(Some(w), Some(h), _) => (w as f32, h as f32),
(Some(w), None, Some((nw, nh))) if nw > 0.0 => (w as f32, w as f32 * nh / nw),
(_, _, Some(natural)) => natural,
_ => (480.0, 270.0),
};
if w > width && w > 0.0 {
h *= width / w;
w = width;
}
let (w, h) = (w.round().max(1.0), h.round().max(1.0));
let x = ((width - w) / 2.0).floor().max(0.0);
let mut prims = Vec::new();
let plain;
let (w, h);
match slot {
Some(ImageSlot::Ready(image)) => {
let (mut rw, mut rh) = match (image_width, image_height, natural) {
(Some(w), Some(h), _) => (w as f32, h as f32),
(Some(w), None, Some((nw, nh))) if nw > 0.0 => (w as f32, w as f32 * nh / nw),
(_, _, Some(natural)) => natural,
_ => (480.0, 270.0),
};
if rw > width && rw > 0.0 {
rh *= width / rw;
rw = width;
}
w = rw.round().max(1.0);
h = rh.round().max(1.0);
let x = ((width - w) / 2.0).floor().max(0.0);
plain = caption.to_string();
prims.push(Prim::Image {
rect: FlowRect::new(x, 0.0, w, h),
image: image.clone(),
});
}
other => {
// Media frame shown until the blob arrives (or when it cannot be shown).
// Longest wording first; a small frame falls back to a shorter one.
let wordings: &[&str] = if matches!(other, Some(ImageSlot::Unavailable)) {
&["Image unavailable", "Unavailable", "No image"]
} else {
&["Loading image", "Loading"]
Some(ImageSlot::Unavailable) => {
// Match Web `image-block-fallback.ts`: full-width compact error card (78px tall),
// no raw `sourceId` hash exposed.
w = width;
h = 78.0;
let msg = "Image loading failed.";
plain = msg.to_string();
prims.push(Prim::Quad {
rect: FlowRect::new(0.0, 0.0, w, h),
fill: Some(self.palette.background_secondary),
border: Some(self.palette.border),
radius: 8.0,
dashed: false,
});
let icon_color = self
.input
.theme
.css_var("--affine-error-color")
.unwrap_or(self.palette.text_secondary);
let pad_x = 16.0;
let icon_size = 16.0;
let icon_y = ((h - icon_size) / 2.0).floor();
prims.push(Prim::Icon {
rect: FlowRect::new(pad_x, icon_y, icon_size, icon_size),
icon: IconPaint::named("WarningIcon"),
color: icon_color,
});
let text_x = pad_x + icon_size + 8.0;
let inner = (w - text_x - pad_x).max(1.0);
let style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_sm_px,
500.0,
self.palette.text_secondary,
);
let line_h = 22.0;
let shaped = truncate_to_width(self.window, msg, &style, inner);
let layout =
self.plain_inline(&shaped.text, style, inner, line_h, InlineAlign::Left);
prims.push(Prim::Text {
x: text_x,
y: ((h - line_h) / 2.0).floor(),
layout,
clip: None,
});
}
None | Some(ImageSlot::Loading) => {
// Pending remote fetch: keep explicit dimensions or 16:9 placeholder until blob arrives.
let (mut rw, mut rh) = match (image_width, image_height) {
(Some(w), Some(h)) => (w as f32, h as f32),
_ => (480.0, 270.0),
};
if rw > width && rw > 0.0 {
rh *= width / rw;
rw = width;
}
w = rw.round().max(1.0);
h = rh.round().max(1.0);
let x = ((width - w) / 2.0).floor().max(0.0);
let wordings: &[&str] = &["Loading image", "Loading"];
let status = wordings[0];
plain = status.to_string();
prims.push(Prim::Quad {
@@ -507,49 +559,25 @@ impl FlowPass<'_> {
f32::from(shape(self.window, wording, &status_style).width()) <= inner
})
.unwrap_or(&status);
let lines = [
(fitting.to_string(), status_style, 22.0),
(
format!("{} \u{00d7} {}", w as i64, h as i64),
InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_xs_px,
400.0,
self.palette.text_secondary,
),
20.0,
),
(
source_id.to_string(),
InlineStyle::new(
FONT_CODE,
TYPOGRAPHY.font_xs_px,
400.0,
self.palette.text_secondary,
),
20.0,
),
];
let total: f32 = lines.iter().map(|(_, _, line_height)| line_height).sum();
let mut y = ((h - total) / 2.0).floor().max(0.0);
for (text, style, line_height) in lines {
if y + line_height > h {
break;
}
let shaped = truncate_to_width(self.window, &text, &style, inner);
let text = shaped.text.to_string();
let layout =
self.plain_inline(&text, style, inner, line_height, InlineAlign::Center);
prims.push(Prim::Text {
x: x + 12.0,
y,
layout,
clip: None,
});
y += line_height;
}
let line_h = 22.0;
let y = ((h - line_h) / 2.0).floor().max(0.0);
let shaped = truncate_to_width(self.window, fitting, &status_style, inner);
let layout = self.plain_inline(
&shaped.text,
status_style,
inner,
line_h,
InlineAlign::Center,
);
prims.push(Prim::Text {
x: x + 12.0,
y,
layout,
clip: None,
});
}
}
let _ = (w, source_id);
let mut body = BlockBody {
kind: FlowKind::Image,
@@ -681,80 +709,6 @@ impl FlowPass<'_> {
body
}
pub(super) fn database_body(
&mut self,
block_id: &str,
data: &blocksuite_playground_doc::read::DatabaseData,
width: f32,
) -> BlockBody {
let ui_state = self.database_state.state_for(block_id);
let offset_at = |ms: i64| self.input.utc_offset_for(ms);
let output = crate::database::layout_database_block(
data,
&ui_state,
width,
self.input.theme,
self.direction,
self.input.form_factor,
self.database_state.mobile_readonly,
self.database_state.clock_ms,
&offset_at,
self.window,
);
self.database_hits.insert(block_id.to_string(), output.hits);
self.database_view_tabs_max_scroll.insert(
block_id.to_string(),
(output.view_tabs_scroll_px, output.view_tabs_max_scroll_px),
);
let prims = output
.prims
.into_iter()
.map(|p| match p {
crate::database::DatabasePrim::Quad {
rect,
fill,
border,
radius,
dashed,
} => Prim::Quad {
rect,
fill,
border,
radius,
dashed,
},
crate::database::DatabasePrim::Text { x, y, layout, clip } => {
Prim::Text { x, y, layout, clip }
}
crate::database::DatabasePrim::Icon { rect, icon, color } => {
Prim::Icon { rect, icon, color }
}
crate::database::DatabasePrim::Chevron {
rect,
collapsed,
color,
} => Prim::Chevron {
rect,
collapsed,
color,
},
})
.collect();
BlockBody {
kind: FlowKind::Database,
width,
height: output.height,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: output.plain,
prims,
text: None,
prefix: None,
code_scroll: output.code_scroll,
pdf_controls: None,
table_cells: Vec::new(),
}
}
}
/// Host of a URL without scheme, credentials, port or path; the input itself if it has none.
@@ -66,7 +66,7 @@ fn extract_snapshot_snippet(snapshot: &PageSnapshot) -> String {
_ => "",
};
if !text.is_empty() {
parts.push(text);
parts.push(text.replace("\r\n", " ").replace(['\r', '\n'], " "));
if parts.len() >= 2 {
break;
}
@@ -691,4 +691,89 @@ mod tests {
Some("Updated 2026-11-26 09:30")
);
}
#[test]
fn embed_linked_doc_with_multiline_title_and_snippet_lays_out_without_panic() {
let mut dir = crate::directory::InMemoryDocDirectory::with_namespace("test");
let target_id = EditorDocId::from("doc:multiline");
dir.upsert_preview(
target_id,
crate::directory::EditorDocPreview {
title: "Service Contract\nLine Two".into(),
snippet: "First line\r\nSecond line\nThird line".into(),
updated_at_ms: 1_795_703_400_000,
revision: 1,
},
);
let embed = BlockNode {
id: "embed-1".into(),
flavour: "affine:embed-linked-doc".into(),
version: Some(1),
props: std::collections::BTreeMap::new(),
content: BlockContent::EmbedLinkedDoc {
page_id: "doc:multiline".into(),
style: "horizontal".into(),
caption: String::new(),
},
children: Vec::new(),
};
let note = BlockNode {
id: "note-1".into(),
flavour: "affine:note".into(),
version: Some(1),
props: std::collections::BTreeMap::new(),
content: BlockContent::Note {
display_mode: blocksuite_playground_doc::read::NoteDisplayMode::Both,
xywh: "[0,0,800,100]".into(),
background: serde_json::Value::Null,
hidden: false,
},
children: vec![embed],
};
let snap = PageSnapshot {
doc_id: "doc:host".into(),
root: Some(BlockNode {
id: "page-1".into(),
flavour: "affine:page".into(),
version: Some(2),
props: std::collections::BTreeMap::new(),
content: BlockContent::Page {
title: blocksuite_playground_doc::read::RichText::default(),
},
children: vec![note],
}),
detached: Vec::new(),
};
let platform = ui::HeadlessPlatform::new(800, 400, 1.0);
let _ = ui::Application::with_platform(platform).run_embedded(move |cx| {
use ui::AppContext as _;
crate::register_bundled_fonts(cx).unwrap();
let window = cx
.open_window(ui::WindowOptions::default(), |_, cx| cx.new(|_| ui::Empty))
.unwrap();
let _ = window.update(cx, |_, window, _| {
let mut flow = super::super::BlockFlow::new();
let titles = std::collections::BTreeMap::new();
let images = std::collections::HashMap::new();
let input = super::super::FlowInput {
snapshot: &snap,
width: 600.0,
theme: crate::theme::PlaygroundTheme::Light,
page_titles: &titles,
images: &images,
pdf_previews: None,
doc_directory: Some(&dir),
equation_draft: None,
env_rev: 1,
direction: ui::Direction::Ltr,
form_factor: crate::capabilities::FormFactor::Desktop,
utc_offset_minutes: 0,
utc_offset_at: None,
};
let layout = flow.layout(&input, window);
let blk = layout.block("embed-1").expect("embed block");
assert!(blk.body.height >= 52.0);
});
});
}
}
@@ -369,6 +369,30 @@ pub(super) fn inline_segments(text: &str) -> Vec<Option<&str>> {
segments
}
/// Collapse hard line breaks (`\r\n`, `\n`, `\r`) into spaces for single-line text shaping.
pub(super) fn sanitize_single_line(text: &str) -> std::borrow::Cow<'_, str> {
if !text.contains(['\n', '\r']) {
return std::borrow::Cow::Borrowed(text);
}
let mut out = String::with_capacity(text.len());
let mut prev_cr = false;
for ch in text.chars() {
if ch == '\r' {
out.push(' ');
prev_cr = true;
} else if ch == '\n' {
if !prev_cr {
out.push(' ');
}
prev_cr = false;
} else {
out.push(ch);
prev_cr = false;
}
}
std::borrow::Cow::Owned(out)
}
/// Shorten `text` with a trailing ellipsis until it fits `max_width`.
pub(super) fn truncate_to_width(
window: &Window,
@@ -376,7 +400,8 @@ pub(super) fn truncate_to_width(
style: &InlineStyle,
max_width: f32,
) -> ShapedLine {
let shaped = shape(window, text, style);
let text = sanitize_single_line(text);
let shaped = shape(window, &text, style);
if f32::from(shaped.width()) <= max_width {
return shaped;
}
@@ -529,9 +529,24 @@ impl<'a> FlowPass<'a> {
align: BlockAlign,
) -> FlowTextLayout {
let width = width.max(1.0);
let paragraph = RichParagraph::from_delta_with_resolver(text.delta.clone(), |page_id| {
self.input.page_titles.get(page_id).cloned()
});
let has_workspace_index =
!self.input.page_titles.is_empty() || self.input.doc_directory.is_some();
let paragraph =
RichParagraph::from_delta_with_reference_resolver(text.delta.clone(), |page_id| {
if let Some(title) = self.input.page_titles.get(page_id) {
crate::rich_text::ReferenceResolution::Found(title.clone())
} else if let Some(preview) = self
.input
.doc_directory
.and_then(|dir| dir.doc_preview(&crate::directory::EditorDocId::from(page_id)))
{
crate::rich_text::ReferenceResolution::Found(preview.title)
} else if has_workspace_index {
crate::rich_text::ReferenceResolution::Deleted
} else {
crate::rich_text::ReferenceResolution::Unknown
}
});
match paragraph {
Ok(paragraph) => {
let mut style = RichParagraphStyle::from_theme(self.input.theme.mode());
+41 -7
View File
@@ -71,6 +71,8 @@ use crate::theme::TYPOGRAPHY;
pub const EDITOR_WIDTH: f32 = TYPOGRAPHY.editor_width_px;
/// Side padding of the page container on regular viewports.
pub const SIDE_PADDING: f32 = 96.0;
/// Side padding of the page container when `pageWidth = "fullWidth"` (matching Web `72px`).
pub const FULL_WIDTH_SIDE_PADDING: f32 = 72.0;
/// Side padding of the page container on viewports up to [`NARROW_VIEWPORT`] wide.
pub const SIDE_PADDING_NARROW: f32 = 24.0;
/// Viewport width at or below which the narrow side padding applies.
@@ -264,15 +266,24 @@ pub struct PageGeometry {
pub column_width: f32,
}
/// Resolve the page container for a viewport width: at most [`EDITOR_WIDTH`] wide,
/// centered, with side padding that narrows on small viewports.
pub fn page_geometry(viewport_width: f32) -> PageGeometry {
/// Resolve the page container for a viewport width: at most [`EDITOR_WIDTH`] wide when
/// `full_width` is `false`, or full viewport width with [`FULL_WIDTH_SIDE_PADDING`] when `true`.
pub fn page_geometry_with_full_width(viewport_width: f32, full_width: bool) -> PageGeometry {
let viewport_width = viewport_width.max(0.0).floor();
let container_width = viewport_width.min(EDITOR_WIDTH);
let side_padding = if viewport_width <= NARROW_VIEWPORT {
SIDE_PADDING_NARROW
let (container_width, side_padding) = if full_width {
let pad = if viewport_width <= NARROW_VIEWPORT {
SIDE_PADDING_NARROW
} else {
FULL_WIDTH_SIDE_PADDING
};
(viewport_width, pad)
} else {
SIDE_PADDING
let pad = if viewport_width <= NARROW_VIEWPORT {
SIDE_PADDING_NARROW
} else {
SIDE_PADDING
};
(viewport_width.min(EDITOR_WIDTH), pad)
};
let column_width = (container_width - 2.0 * side_padding).max(0.0);
let container_x = ((viewport_width - container_width) / 2.0).floor();
@@ -284,6 +295,12 @@ pub fn page_geometry(viewport_width: f32) -> PageGeometry {
}
}
/// Resolve the page container for a viewport width: at most [`EDITOR_WIDTH`] wide,
/// centered, with side padding that narrows on small viewports.
pub fn page_geometry(viewport_width: f32) -> PageGeometry {
page_geometry_with_full_width(viewport_width, false)
}
/// Axis-aligned rectangle in flow units (logical pixels).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FlowRect {
@@ -692,4 +709,21 @@ mod tests {
assert_eq!(b_rtl.body.text.as_ref().unwrap().x, 0.0);
}
}
#[test]
fn full_width_page_geometry_and_multiline_embed_card_sanitize_newlines() {
let normal = page_geometry_with_full_width(1280.0, false);
assert_eq!(normal.column_width, 752.0);
let full = page_geometry_with_full_width(1280.0, true);
assert_eq!(full.side_padding, FULL_WIDTH_SIDE_PADDING);
assert_eq!(full.column_width, 1136.0);
assert_eq!(full.column_x, 72.0);
let narrow_full = page_geometry_with_full_width(390.0, true);
assert_eq!(narrow_full.side_padding, SIDE_PADDING_NARROW);
assert_eq!(narrow_full.column_width, 342.0);
let sanitized = inline::sanitize_single_line("Line 1\r\nLine 2\nLine 3\rLine 4");
assert_eq!(sanitized.as_ref(), "Line 1 Line 2 Line 3 Line 4");
assert!(!sanitized.contains(['\r', '\n']));
}
}
@@ -195,4 +195,79 @@ impl FlowPass<'_> {
table_cells,
}
}
pub(super) fn database_body(
&mut self,
block_id: &str,
data: &blocksuite_playground_doc::read::DatabaseData,
width: f32,
) -> BlockBody {
let ui_state = self.database_state.state_for(block_id);
let offset_at = |ms: i64| self.input.utc_offset_for(ms);
let output = crate::database::layout_database_block(
data,
&ui_state,
width,
self.input.theme,
self.direction,
self.input.form_factor,
self.database_state.mobile_readonly,
self.database_state.clock_ms,
&offset_at,
self.window,
);
self.database_hits.insert(block_id.to_string(), output.hits);
self.database_view_tabs_max_scroll.insert(
block_id.to_string(),
(output.view_tabs_scroll_px, output.view_tabs_max_scroll_px),
);
let prims = output
.prims
.into_iter()
.map(|p| match p {
crate::database::DatabasePrim::Quad {
rect,
fill,
border,
radius,
dashed,
} => Prim::Quad {
rect,
fill,
border,
radius,
dashed,
},
crate::database::DatabasePrim::Text { x, y, layout, clip } => {
Prim::Text { x, y, layout, clip }
}
crate::database::DatabasePrim::Icon { rect, icon, color } => {
Prim::Icon { rect, icon, color }
}
crate::database::DatabasePrim::Chevron {
rect,
collapsed,
color,
} => Prim::Chevron {
rect,
collapsed,
color,
},
})
.collect();
BlockBody {
kind: FlowKind::Database,
width,
height: output.height,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: output.plain,
prims,
text: None,
prefix: None,
code_scroll: output.code_scroll,
pdf_controls: None,
table_cells: Vec::new(),
}
}
}
+226 -3
View File
@@ -93,12 +93,28 @@ pub struct EdgelessCanvasState {
pub(super) surfaces: Option<CachedSurfaces>,
pub(super) note_flows: HashMap<String, CachedNoteFlow>,
pub(super) text_flows: HashMap<String, CachedNoteFlow>,
pub(super) surface_block_flows: HashMap<String, CachedNoteFlow>,
/// Number of block bodies laid out during the most recent Edgeless frame.
pub last_frame_relayouts: u64,
}
/// Collect spatial blocks (`Frame`, Edgeless-visible `Note`, `EdgelessText`) from `root.children`
/// and any `BlockContent::Surface`'s children in document order.
pub(super) fn is_spatial_surface_block(node: &BlockNode) -> bool {
matches!(
&node.content,
BlockContent::Image { .. }
| BlockContent::EmbedLinkedDoc { .. }
| BlockContent::EmbedSyncedDoc { .. }
| BlockContent::ExternalEmbed { .. }
) && node
.props
.get("prop:xywh")
.and_then(JsonValue::as_str)
.and_then(parse_xywh)
.is_some()
}
/// Collect spatial blocks (`Frame`, Edgeless-visible `Note`, `EdgelessText`, and positioned
/// surface embed/image blocks) from `root.children` and any `BlockContent::Surface`'s children.
pub fn spatial_blocks(root: &BlockNode) -> Vec<&BlockNode> {
let mut out = Vec::new();
for child in &root.children {
@@ -125,7 +141,7 @@ fn is_spatial_block(node: &BlockNode) -> bool {
hidden: false,
..
} => *display_mode != NoteDisplayMode::DocOnly,
_ => false,
_ => is_spatial_surface_block(node),
}
}
@@ -327,6 +343,18 @@ impl EdgelessCanvasState {
union = union.union(rotated_bounds(rect, rot));
}
}
_ if is_spatial_surface_block(child) => {
if let Some(rect) = child
.props
.get("prop:xywh")
.and_then(JsonValue::as_str)
.and_then(parse_xywh)
{
let rot = prop_f32(child, "prop:rotate", 0.0);
external.insert(child.id.clone(), world_bounds(rect, rot));
union = union.union(rotated_bounds(rect, rot));
}
}
_ => {}
}
}
@@ -393,6 +421,120 @@ pub(super) struct PaintEdgelessText {
pub(super) layout: Rc<FlowLayout>,
}
/// Resolved surface-parented block (`image`, `embed-linked-doc`, `embed-synced-doc`,
/// `ExternalEmbed`) with its cached `FlowLayout` and rotation/scale.
pub(super) struct PaintSurfaceBlock {
pub(super) world_aabb: WorldRect,
pub(super) id: String,
pub(super) index: String,
pub(super) rect: WorldRect,
pub(super) scale: f32,
pub(super) rotate_deg: f32,
pub(super) layout: Rc<FlowLayout>,
}
pub(super) fn prepare_surface_block(
state: &mut EdgelessCanvasState,
child: &BlockNode,
input: &EdgelessRenderInput<'_>,
live_override: Option<(WorldRect, Option<f32>)>,
window: &ui::Window,
) -> Option<PaintSurfaceBlock> {
let xywh = child.props.get("prop:xywh").and_then(JsonValue::as_str)?;
let mut rect = parse_xywh(xywh)?;
let scale = prop_f32(child, "prop:scale", 1.0).clamp(0.1, 10.0);
let mut rotate_deg = prop_f32(child, "prop:rotate", 0.0);
if let Some((ov_rect, ov_rot)) = live_override {
rect = ov_rect;
if let Some(r) = ov_rot {
rotate_deg = r;
}
}
let inner_width = (rect.w / scale).max(60.0);
let is_rtl = input.direction.is_rtl();
let key = (
input.doc_rev,
inner_width.to_bits(),
scale.to_bits(),
input.theme,
input.env_rev,
input.preview_rev,
input.preedit_nonce,
is_rtl,
input.form_factor,
input.utc_offset_minutes,
);
let layout = match state.surface_block_flows.get_mut(&child.id) {
Some(cached) if cached.key == key => cached.layout.clone(),
_ => {
let flow_input = crate::block_flow::FlowInput {
snapshot: input.snapshot,
width: inner_width,
theme: input.theme,
page_titles: input.page_titles,
images: input.images,
pdf_previews: input.pdf_previews,
doc_directory: input.doc_directory,
equation_draft: None,
env_rev: input.env_rev,
direction: input.direction,
form_factor: input.form_factor,
utc_offset_minutes: input.utc_offset_minutes,
utc_offset_at: input.utc_offset_at,
};
let entry = state
.surface_block_flows
.entry(child.id.clone())
.or_insert_with(|| CachedNoteFlow {
flow: BlockFlow::new(),
key: (
u64::MAX,
0,
0,
input.theme,
0,
0,
0,
!is_rtl,
input.form_factor,
0,
),
layout: Rc::new(FlowLayout {
blocks: Vec::new(),
width: inner_width,
height: 0.0,
direction: input.direction,
stats: Default::default(),
}),
});
let laid_out =
entry
.flow
.layout_nodes(std::slice::from_ref(child), &flow_input, window);
state.last_frame_relayouts += laid_out.stats.laid_out as u64;
let rc = Rc::new(laid_out);
entry.key = key;
entry.layout = rc.clone();
rc
}
};
let index = child
.props
.get("prop:index")
.and_then(JsonValue::as_str)
.unwrap_or("a0")
.to_string();
Some(PaintSurfaceBlock {
world_aabb: rotated_bounds(rect, rotate_deg),
id: child.id.clone(),
index,
rect,
scale,
rotate_deg,
layout,
})
}
/// Resolve a BlockSuite `{ light, dark }` color map or string color token against `theme`.
pub fn resolve_edgeless_color(value: &JsonValue, theme: PlaygroundTheme) -> Option<Hsla> {
let raw = match value {
@@ -451,3 +593,84 @@ pub struct EdgelessRenderInput<'a> {
pub utc_offset_at: Option<&'a dyn Fn(i64) -> i32>,
pub editing_selection: Option<(String, bool, DocumentSelection, DocPoint)>,
}
#[cfg(test)]
mod tests {
use super::*;
use blocksuite_playground_doc::read::{BlockNode, PageSnapshot};
#[test]
fn surface_child_embed_and_image_blocks_are_spatial_and_bounded() {
let mut embed_props = BTreeMap::new();
embed_props.insert(
"prop:xywh".into(),
JsonValue::String("[120,240,360,200]".into()),
);
embed_props.insert("prop:index".into(), JsonValue::String("a1".into()));
let embed_synced = BlockNode {
id: "synced-1".into(),
flavour: "affine:embed-synced-doc".into(),
version: Some(1),
props: embed_props,
content: BlockContent::EmbedSyncedDoc {
page_id: "doc:child".into(),
caption: String::new(),
},
children: Vec::new(),
};
let mut img_props = BTreeMap::new();
img_props.insert(
"prop:xywh".into(),
JsonValue::String("[520,100,240,160]".into()),
);
let img_block = BlockNode {
id: "img-1".into(),
flavour: "affine:image".into(),
version: Some(1),
props: img_props,
content: BlockContent::Image {
source_id: "synthetic-blob".into(),
width: Some(240.0),
height: Some(160.0),
caption: String::new(),
},
children: Vec::new(),
};
let surface = BlockNode {
id: "surface-1".into(),
flavour: "affine:surface".into(),
version: Some(5),
props: BTreeMap::new(),
content: BlockContent::Surface {
element_count: 0,
elements: Vec::new(),
},
children: vec![embed_synced, img_block],
};
let root = BlockNode {
id: "page-1".into(),
flavour: "affine:page".into(),
version: Some(2),
props: BTreeMap::new(),
content: BlockContent::Page {
title: blocksuite_playground_doc::read::RichText::default(),
},
children: vec![surface],
};
let found = spatial_blocks(&root);
let ids: Vec<&str> = found.iter().map(|n| n.id.as_str()).collect();
assert_eq!(ids, vec!["synced-1", "img-1"]);
let snap = PageSnapshot {
doc_id: "doc:board".into(),
root: Some(root),
detached: Vec::new(),
};
let state = EdgelessCanvasState::new();
let bounds = state.scene_world_bounds(&snap);
assert_eq!(bounds.x, 120.0);
assert_eq!(bounds.y, 100.0);
assert_eq!(bounds.right(), 760.0);
assert_eq!(bounds.bottom(), 440.0);
}
}
@@ -27,6 +27,7 @@ pub fn build_edgeless_layer(
frames,
notes,
texts,
surface_blocks,
surfaces,
order,
} = prepare_edgeless_scene(state, input, window);
@@ -113,6 +114,14 @@ pub fn build_edgeless_layer(
None,
);
}
for sb in &surface_blocks {
push_marker(
&mut snapshot_markers,
format!("edgeless.block.{}", sb.id),
sb.world_aabb,
None,
);
}
let frame_border = theme
.css_var("--affine-v2-edgeless-frame-border-default")
@@ -424,6 +433,57 @@ pub fn build_edgeless_layer(
}
});
}
PaintItem::SurfaceBlock(i) => {
let sb = &surface_blocks[i];
if !sb.world_aabb.intersects(cull_world) {
continue;
}
let (cx_w, cy_w) = sb.rect.center();
let scale_from_tl = TransformationMatrix::unit()
.translate(point(
ScaledPixels(sb.rect.x),
ScaledPixels(sb.rect.y),
))
.scale(size(sb.scale, sb.scale))
.translate(point(
ScaledPixels(-sb.rect.x),
ScaledPixels(-sb.rect.y),
));
let rotate_around_center = TransformationMatrix::unit()
.translate(point(ScaledPixels(cx_w), ScaledPixels(cy_w)))
.rotate(ui::radians(sb.rotate_deg.to_radians()))
.translate(point(ScaledPixels(-cx_w), ScaledPixels(-cy_w)));
let local_transform = rotate_around_center.compose(scale_from_tl);
let clip_bounds = Bounds::new(
point(px(sb.rect.x), px(sb.rect.y)),
size(
px((sb.rect.w / sb.scale).max(1.0)),
px((sb.rect.h / sb.scale).max(1.0)),
),
);
window.with_paint_transformation(local_transform, |window| {
window.with_local_paint_mask(
ContentMask {
bounds: clip_bounds,
},
|window| {
for block in &sb.layout.blocks {
let origin = point(
px(sb.rect.x + block.x),
px(sb.rect.y + block.y),
);
block.body.paint(
origin,
BlockPaint::default(),
window,
cx,
);
}
},
);
});
}
}
}
});
@@ -67,6 +67,7 @@ pub enum SpatialItemKind {
Note,
Frame,
EdgelessText,
SurfaceBlock,
Shape,
Connector,
Brush,
@@ -77,15 +78,21 @@ pub enum SpatialItemKind {
impl SpatialItemKind {
pub fn is_block(self) -> bool {
matches!(self, Self::Note | Self::Frame | Self::EdgelessText)
matches!(
self,
Self::Note | Self::Frame | Self::EdgelessText | Self::SurfaceBlock
)
}
pub fn is_rotatable(self) -> bool {
matches!(self, Self::Shape | Self::EdgelessText)
matches!(self, Self::Shape | Self::EdgelessText | Self::SurfaceBlock)
}
pub fn has_gfx_drag_handle(self) -> bool {
matches!(self, Self::Note | Self::Frame | Self::EdgelessText)
matches!(
self,
Self::Note | Self::Frame | Self::EdgelessText | Self::SurfaceBlock
)
}
}
@@ -554,7 +561,8 @@ impl EdgelessAuthoringState {
match item.kind {
SpatialItemKind::Shape
| SpatialItemKind::SurfaceText
| SpatialItemKind::EdgelessText => {
| SpatialItemKind::EdgelessText
| SpatialItemKind::SurfaceBlock => {
if point_in_rotated_rect(world_x, world_y, item.rect, item.rotate_deg) {
return Some(item);
}
+3 -2
View File
@@ -52,6 +52,7 @@ pub use toolbar::{
use canvas::{
CachedNoteFlow, CachedSurfaces, FRAME_RADIUS, FRAME_TITLE_GAP, FRAME_TITLE_HEIGHT,
PaintEdgelessText, PaintFrame, PaintNote, ZOOM_BAR_MARGIN, ZOOM_BAR_PAD, ZOOM_BAR_RADIUS,
ZOOM_BTN_HEIGHT, ZOOM_BTN_RADIUS,
PaintEdgelessText, PaintFrame, PaintNote, PaintSurfaceBlock, ZOOM_BAR_MARGIN, ZOOM_BAR_PAD,
ZOOM_BAR_RADIUS, ZOOM_BTN_HEIGHT, ZOOM_BTN_RADIUS, is_spatial_surface_block,
prepare_surface_block,
};
@@ -7,6 +7,7 @@ pub enum PaintItem {
Frame(usize),
Note(usize),
Text(usize),
SurfaceBlock(usize),
Surface(usize, usize),
}
+49 -4
View File
@@ -16,8 +16,9 @@ use crate::{
use super::{
CachedNoteFlow, CachedSurfaces, EdgelessCanvasState, EdgelessRenderInput, FRAME_TITLE_GAP,
FRAME_TITLE_HEIGHT, Layers, NOTE_CARD_PADDING, PaintEdgelessText, PaintFrame, PaintItem,
PaintNote, SpatialItemInfo, SpatialItemKind, WorldRect, note_border_radius, note_border_style,
note_collapse, note_scale, note_shadow_type, parse_xywh, prop_bool, prop_f32,
PaintNote, PaintSurfaceBlock, SpatialItemInfo, SpatialItemKind, WorldRect,
is_spatial_surface_block, note_border_radius, note_border_style, note_collapse, note_scale,
note_shadow_type, parse_xywh, prepare_surface_block, prop_bool, prop_f32,
resolve_edgeless_color, rotated_bounds, spatial_blocks, world_bounds, world_rect,
};
@@ -39,6 +40,7 @@ pub struct PreparedEdgelessScene {
pub(super) frames: Vec<PaintFrame>,
pub(super) notes: Vec<PaintNote>,
pub(super) texts: Vec<PaintEdgelessText>,
pub(super) surface_blocks: Vec<PaintSurfaceBlock>,
pub(super) surfaces: Rc<[SurfaceLayout]>,
pub(super) order: Rc<[PaintItem]>,
}
@@ -54,13 +56,15 @@ pub fn prepare_edgeless_scene(
let mut frames = Vec::new();
let mut notes = Vec::new();
let mut texts = Vec::new();
// Preserve exact `sys:children` order across Frames, Notes, and EdgelessTexts when merging
// equal-index items into `Layers::merge`.
let mut surface_blocks = Vec::new();
// Preserve exact `sys:children` order across Frames, Notes, EdgelessTexts, and surface blocks
// when merging equal-index items into `Layers::merge`.
let mut spatial_order: Vec<(String, PaintItem)> = Vec::new();
if let Some(root) = &input.snapshot.root {
let mut active_notes = Vec::new();
let mut active_texts = Vec::new();
let mut active_surface_blocks = Vec::new();
for child in spatial_blocks(root) {
match &child.content {
@@ -380,6 +384,17 @@ pub fn prepare_edgeless_scene(
spatial_order.push((child.id.clone(), PaintItem::Text(idx)));
}
}
_ if is_spatial_surface_block(child) => {
let ov = live_overrides
.get(&child.id)
.map(|o| (o.rect, o.rotate_deg));
if let Some(sb) = prepare_surface_block(state, child, input, ov, window) {
active_surface_blocks.push(child.id.clone());
let idx = surface_blocks.len();
surface_blocks.push(sb);
spatial_order.push((child.id.clone(), PaintItem::SurfaceBlock(idx)));
}
}
_ => {}
}
}
@@ -390,6 +405,11 @@ pub fn prepare_edgeless_scene(
if state.text_flows.len() > active_texts.len() {
state.text_flows.retain(|id, _| active_texts.contains(id));
}
if state.surface_block_flows.len() > active_surface_blocks.len() {
state
.surface_block_flows
.retain(|id, _| active_surface_blocks.contains(id));
}
}
let key = (input.doc_rev, input.theme, input.env_rev);
@@ -414,6 +434,11 @@ pub fn prepare_edgeless_scene(
.iter()
.map(|t| (t.id.clone(), world_bounds(t.rect, t.rotate_deg))),
)
.chain(
surface_blocks
.iter()
.map(|b| (b.id.clone(), world_bounds(b.rect, b.rotate_deg))),
)
.collect();
let layouts: Rc<[SurfaceLayout]> = input
.snapshot
@@ -600,6 +625,25 @@ pub fn prepare_edgeless_scene(
title_pill_rect: None,
});
}
PaintItem::SurfaceBlock(i) => {
let b = &surface_blocks[i];
built_items.push(SpatialItemInfo {
id: b.id.clone(),
kind: SpatialItemKind::SurfaceBlock,
shape_type: None,
surface_id: None,
rect: b.rect,
rotate_deg: b.rotate_deg,
index: b.index.clone(),
scale: b.scale,
stroke_width: 1.0,
polyline: Vec::new(),
frame_children: Vec::new(),
group_children: Vec::new(),
parent_group_id: resolve_outermost_group(&b.id),
title_pill_rect: None,
});
}
PaintItem::Surface(l, i) => {
let Some(id) = surfaces_item_id(&layouts, l, i) else {
continue;
@@ -741,6 +785,7 @@ pub fn prepare_edgeless_scene(
frames,
notes,
texts,
surface_blocks,
surfaces,
order,
}
@@ -1,7 +1,7 @@
use std::ops::Range;
use ui::{
Bounds, FontStyle, FontWeight, Hsla, Pixels, Point, ShapedLine, Size, TextAlign, TextRun,
Bounds, FontStyle, FontWeight, Pixels, Point, ShapedLine, Size, TextAlign, TextRun,
WindowTextSystem, point, px, size,
};
use unicode_bidi::BidiInfo;
@@ -9,7 +9,7 @@ use unicode_linebreak::linebreaks;
use super::{
CaretPosition, DecorationKind, InlineDecoration, PAGE_PREFIX, RichParagraph,
RichParagraphStyle, RichSpan, TextBiIndex, WrapAffinity,
RichParagraphStyle, RichSpan, TextBiIndex, WrapAffinity, span_color,
};
#[derive(Debug)]
@@ -214,23 +214,6 @@ 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;
@@ -506,8 +489,18 @@ impl ParagraphLayout<'_> {
style.chip_bg,
);
let icon_size = px(style.font_size).min(width);
let glyph_kind = if reference.is_edgeless() {
DecorationKind::EdgelessGlyph
} else {
DecorationKind::PageGlyph
};
let glyph_color = if span.deleted_reference {
color
} else {
style.icon_color
};
decorate(
DecorationKind::PageGlyph,
glyph_kind,
Bounds::new(
point(
visual.start,
@@ -515,7 +508,7 @@ impl ParagraphLayout<'_> {
),
size(icon_size, icon_size),
),
style.icon_color,
glyph_color,
);
decorate(
DecorationKind::ReferenceDivider,
@@ -568,7 +561,7 @@ impl ParagraphLayout<'_> {
color,
);
}
if span.marks.strike {
if span.marks.strike || span.deleted_reference {
decorate(
DecorationKind::Strikethrough,
stroke(baseline_y - fragment.shaped.ascent * 0.32),
@@ -905,7 +898,7 @@ mod tests {
),
])
.unwrap();
let css_color = |c: Hsla| {
let css_color = |c: ui::Hsla| {
let c: ui::Rgba = c.into();
format!(
"rgb({}, {}, {})",
+174 -16
View File
@@ -33,6 +33,7 @@ pub enum DecorationKind {
ReferenceChip(InlineReference),
ReferenceDivider,
PageGlyph,
EdgelessGlyph,
Underline,
Strikethrough,
Link(String),
@@ -48,11 +49,36 @@ pub struct InlineDecoration {
pub color: Hsla,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct InlineReferenceParams {
pub mode: Option<String>,
pub block_ids: Vec<String>,
pub element_ids: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InlineReference {
pub kind: String,
pub page_id: String,
pub title: Option<String>,
pub params: Option<InlineReferenceParams>,
}
impl InlineReference {
pub fn is_edgeless(&self) -> bool {
self.params
.as_ref()
.and_then(|p| p.mode.as_deref())
.is_some_and(|m| m.eq_ignore_ascii_case("edgeless"))
}
}
/// Resolution outcome for an inline `@reference` target page.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ReferenceResolution {
Found(String),
Deleted,
Unknown,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -78,16 +104,40 @@ fn string_attr(value: Option<&Any>) -> Option<String> {
}
}
fn string_list_attr(value: Option<&Any>) -> Vec<String> {
match value {
Some(Any::Array(items)) => items
.iter()
.filter_map(|v| match v {
Any::String(s) => Some(s.clone()),
_ => None,
})
.collect(),
_ => Vec::new(),
}
}
impl InlineMarkSet {
fn from_attrs(attrs: &TextAttributes) -> Self {
let enabled = |key| attrs.get(key) == Some(&Any::True);
let reference = match attrs.get("reference") {
Some(Any::Object(obj)) => string_attr(obj.get("type"))
.zip(string_attr(obj.get("pageId")))
.map(|(kind, page_id)| InlineReference {
kind,
page_id,
title: string_attr(obj.get("title")),
.map(|(kind, page_id)| {
let params = match obj.get("params") {
Some(Any::Object(p)) => Some(InlineReferenceParams {
mode: string_attr(p.get("mode")),
block_ids: string_list_attr(p.get("blockIds")),
element_ids: string_list_attr(p.get("elementIds")),
}),
_ => None,
};
InlineReference {
kind,
page_id,
title: string_attr(obj.get("title")),
params,
}
}),
_ => None,
};
@@ -113,6 +163,7 @@ pub struct RichSpan {
pub marks: InlineMarkSet,
pub(super) source_bytes: Range<usize>,
pub(super) chip: bool,
pub(super) deleted_reference: bool,
}
/// Owns the original snapshot, including opaque attributes and embedded values.
@@ -126,12 +177,21 @@ pub struct RichParagraph {
impl RichParagraph {
pub fn from_delta(delta: Vec<TextDeltaOp>) -> anyhow::Result<Self> {
Self::from_delta_with_resolver(delta, |_| None)
Self::from_delta_with_reference_resolver(delta, |_| ReferenceResolution::Unknown)
}
pub fn from_delta_with_resolver(
delta: Vec<TextDeltaOp>,
resolve_doc_title: impl Fn(&str) -> Option<String>,
) -> anyhow::Result<Self> {
Self::from_delta_with_reference_resolver(delta, |id| {
resolve_doc_title(id).map_or(ReferenceResolution::Unknown, ReferenceResolution::Found)
})
}
pub fn from_delta_with_reference_resolver(
delta: Vec<TextDeltaOp>,
resolve_reference: impl Fn(&str) -> ReferenceResolution,
) -> anyhow::Result<Self> {
let mut source = String::new();
let mut display = String::new();
@@ -147,7 +207,7 @@ impl RichParagraph {
.as_ref()
.map(InlineMarkSet::from_attrs)
.unwrap_or_default();
let mut append = |text: &str, label: &str, chip: bool| {
let mut append = |text: &str, label: &str, chip: bool, deleted_reference: bool| {
if text.is_empty() {
return;
}
@@ -162,6 +222,7 @@ impl RichParagraph {
display_bytes: display_start..display.len(),
marks: marks.clone(),
chip,
deleted_reference,
});
utf16 = end;
};
@@ -170,16 +231,23 @@ impl RichParagraph {
if marks.reference.is_some() && s.bytes().all(|b| b == b' ') =>
{
let reference = marks.reference.as_ref().unwrap();
let resolved = resolve_doc_title(&reference.page_id);
let title = resolved
.as_deref()
.filter(|s| !s.is_empty())
.or_else(|| reference.title.as_deref().filter(|s| !s.is_empty()))
.unwrap_or("Untitled");
let (title, deleted) = match resolve_reference(&reference.page_id) {
ReferenceResolution::Found(t) if !t.is_empty() => (t, false),
ReferenceResolution::Found(_) | ReferenceResolution::Unknown => (
reference
.title
.as_deref()
.filter(|s| !s.is_empty())
.unwrap_or("Untitled")
.to_string(),
false,
),
ReferenceResolution::Deleted => ("Deleted page".to_string(), true),
};
let label = format!("{PAGE_PREFIX}{}", title.replace(['\r', '\n'], " "));
// Y.Text may coalesce consecutive identically formatted placeholders.
for _ in s.bytes() {
append(" ", &label, true);
append(" ", &label, true, deleted);
}
}
TextInsert::Text(s) if marks.latex.is_some() && s.bytes().all(|b| b == b' ') => {
@@ -190,13 +258,13 @@ impl RichParagraph {
tex.replace(['\r', '\n'], " ")
};
for _ in s.bytes() {
append(" ", &label, true);
append(" ", &label, true, false);
}
}
TextInsert::Text(s) => append(s, s, false),
TextInsert::Text(s) => append(s, s, false, false),
TextInsert::Embed(values) => {
let objects = "\u{fffc}".repeat(values.len());
append(&objects, &objects, false);
append(&objects, &objects, false, false);
}
}
}
@@ -255,6 +323,30 @@ impl RichParagraph {
// paragraph so a platform's font fallback cannot substitute a color emoji.
const PAGE_PREFIX: &str = "▤ ";
/// Ink of a span: reference and link colors win, then code, then a custom `color` mark.
pub(super) fn span_color(style: &RichParagraphStyle, span: &RichSpan) -> Hsla {
if span.chip {
if span.deleted_reference {
style
.theme
.css_var("--affine-text-disable-color")
.unwrap_or(style.icon_color)
} else {
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)
}
}
#[derive(Clone, Debug)]
pub struct RichParagraphStyle {
/// Theme that resolves `color` and `background` marks.
@@ -570,4 +662,70 @@ mod tests {
assert_eq!(p.delta(), delta);
}
}
#[test]
fn reference_params_edgeless_icon_and_deleted_page_strikethrough() {
let edgeless_ref = Any::Object(Box::new(
[
("type".into(), Any::String("LinkedPage".into())),
("pageId".into(), Any::String("doc:board".into())),
(
"params".into(),
Any::Object(Box::new(
[("mode".into(), Any::String("edgeless".into()))]
.into_iter()
.collect(),
)),
),
]
.into_iter()
.collect(),
));
let deleted_ref = Any::Object(Box::new(
[
("type".into(), Any::String("LinkedPage".into())),
("pageId".into(), Any::String("doc:gone".into())),
]
.into_iter()
.collect(),
));
let delta = vec![
TextDeltaOp::Insert {
insert: TextInsert::Text(" ".into()),
format: Some([("reference".into(), edgeless_ref)].into()),
},
TextDeltaOp::Insert {
insert: TextInsert::Text(" ".into()),
format: Some([("reference".into(), deleted_ref)].into()),
},
];
let p = RichParagraph::from_delta_with_reference_resolver(delta, |id| match id {
"doc:board" => ReferenceResolution::Found("Architecture Board".into()),
_ => ReferenceResolution::Deleted,
})
.unwrap();
assert!(p.spans()[0].marks.reference.as_ref().unwrap().is_edgeless());
assert!(!p.spans()[0].deleted_reference);
assert!(p.spans()[1].deleted_reference);
assert!(p.display_text().contains("Architecture Board"));
assert!(p.display_text().contains("Deleted page"));
let platform = ui::HeadlessPlatform::new(400, 80, 1.0);
let _ = ui::Application::with_platform(platform).run_embedded(move |cx| {
crate::register_bundled_fonts(cx).unwrap();
let ts = ui::WindowTextSystem::new(cx.text_system().clone());
let layout = p.layout(&ts, &RichParagraphStyle::default(), 400.0);
let decos = layout.inline_decorations();
assert!(
decos
.iter()
.any(|d| d.kind == DecorationKind::EdgelessGlyph)
);
assert!(
decos
.iter()
.any(|d| d.kind == DecorationKind::Strikethrough)
);
});
}
}
@@ -21,6 +21,7 @@ impl LaidOutRichParagraph {
cx: &mut App,
) {
static PAGE_ICON: std::sync::OnceLock<IconPaint> = std::sync::OnceLock::new();
static EDGELESS_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 {
@@ -39,6 +40,9 @@ impl LaidOutRichParagraph {
DecorationKind::PageGlyph => PAGE_ICON
.get_or_init(|| IconPaint::named("LinkedPageIcon"))
.paint(bounds, d.color, window, cx),
DecorationKind::EdgelessGlyph => EDGELESS_ICON
.get_or_init(|| IconPaint::named("EdgelessIcon"))
.paint(bounds, d.color, window, cx),
_ => {}
}
}
@@ -93,14 +93,17 @@ fn endpoints(
) -> Option<(Port, Port)> {
let pinned = |e: &ConnectorEndpoint, t: Option<Target>| {
let [x, y] = e.position?;
Some(t.map_or(
Port {
if let Some(t) = t {
Some(t.port(P(x, y), false))
} else if e.id.is_none() {
Some(Port {
p: P(x, y),
normal: P::default(),
bound: None,
},
|t| t.port(P(x, y), false),
))
})
} else {
None
}
};
match (pinned(&c.source, start), pinned(&c.target, end)) {
(Some(a), Some(b)) => Some((a, b)),
@@ -453,4 +456,33 @@ mod tests {
assert_eq!(route.point_at_distance(c.mode, 0.25), expected);
}
}
#[test]
fn dangling_bound_endpoint_is_skipped_instead_of_routing_to_origin() {
let mut bounds = BTreeMap::new();
bounds.insert(
"frame-1".into(),
WorldBounds {
xywh: [400., 200., 200., 160.],
rotate: 0.,
},
);
let e = SurfaceElement::from_properties(
"conn-dangling".into(),
json!({
"type": "connector",
"mode": 2,
"source": { "id": "missing-embed", "position": [1.0, 0.5] },
"target": { "id": "frame-1", "position": [0.0, 0.5] }
}),
RichText::default(),
);
let SurfaceElementKind::Connector(c) = e.kind else {
unreachable!()
};
assert!(
route(&c, &bounds, &BTreeMap::new()).is_none(),
"missing bound target must not interpret normalized [1.0, 0.5] as world pixels"
);
}
}
@@ -348,6 +348,26 @@ impl Contour {
}
}
pub(super) fn parse_css_font_stack(raw: &str) -> (String, Vec<String>) {
let stripped = raw.trim().trim_start_matches("blocksuite:surface:");
let mut families: Vec<String> = stripped
.split(',')
.map(|s| s.trim().trim_matches(['\'', '"']).trim())
.filter(|s| !s.is_empty())
.map(|s| match s.to_ascii_lowercase().as_str() {
"sans-serif" | "cursive" | "system-ui" => crate::theme::FONT_SANS.to_string(),
"monospace" => crate::theme::FONT_CODE.to_string(),
_ => s.to_string(),
})
.collect();
let primary = if families.is_empty() {
crate::theme::FONT_SANS.to_string()
} else {
families.remove(0)
};
(primary, families)
}
#[cfg(test)]
mod tests {
use super::*;
+112 -8
View File
@@ -1,4 +1,4 @@
use super::{Contour, P, WorldBounds, connector, rough, shapes, strokes};
use super::{Contour, P, WorldBounds, connector, parse_css_font_stack, rough, shapes, strokes};
use crate::{
PlaygroundTheme,
rich_text::{LaidOutRichParagraph, RichParagraph, RichParagraphStyle},
@@ -171,12 +171,30 @@ impl TextStyle<'_> {
}
}
}
let (primary, extra_fallbacks) = parse_css_font_stack(self.font);
let resolved_family =
if primary == crate::theme::FONT_SANS || primary == crate::theme::FONT_CODE {
primary
} else {
let available = ts.all_font_names();
std::iter::once(primary.as_str())
.chain(extra_fallbacks.iter().map(String::as_str))
.find(|fam| available.iter().any(|a| a.eq_ignore_ascii_case(fam)))
.unwrap_or(crate::theme::FONT_SANS)
.to_string()
};
let mut fallbacks = extra_fallbacks;
if !fallbacks.iter().any(|f| f == crate::theme::FONT_SANS) {
fallbacks.push(crate::theme::FONT_SANS.to_string());
}
fallbacks.extend(
crate::default_font_fallbacks()
.fallback_list()
.iter()
.cloned(),
);
let mut style = RichParagraphStyle {
font_family: self
.font
.trim_start_matches("blocksuite:surface:")
.to_string()
.into(),
font_family: resolved_family.into(),
font_size: self.size as f32,
base_weight: ui::FontWeight(self.weight.parse().unwrap_or(if self.weight == "bold" {
700.
@@ -194,7 +212,7 @@ impl TextStyle<'_> {
};
let mut face = ui::font(style.font_family.clone());
face.weight = style.base_weight;
face.fallbacks = Some(crate::default_font_fallbacks());
face.fallbacks = Some(ui::FontFallbacks(std::sync::Arc::new(fallbacks)));
let id = ts.resolve_font(&face);
let size = px(style.font_size);
let ascent = f32::from(ts.ascent(id, size));
@@ -453,7 +471,9 @@ fn layout_shape(
builder = builder.dash_array(&[px(12.), px(12.)]);
}
for contour in contours {
contour.mapped(world).emit(&mut builder);
if !contour.edges.is_empty() {
contour.mapped(world).emit(&mut builder);
}
}
item.finish_path(builder, resolve(theme, color));
}
@@ -1096,4 +1116,88 @@ mod tests {
)
}
}
#[test]
fn scribbled_dashed_shape_and_rough_dashed_connector_tessellate_without_panic() {
let platform = ui::HeadlessPlatform::new(320, 240, 1.);
let _ = ui::Application::with_platform(platform).run_embedded(|cx| {
crate::register_bundled_fonts(cx).unwrap();
let elements = vec![
SurfaceElement::from_properties(
"scribbled-dash-rect".into(),
serde_json::json!({
"type": "shape",
"shapeType": "rect",
"shapeStyle": "Scribbled",
"strokeStyle": "dash",
"strokeWidth": 2.0,
"roughness": 1.4,
"filled": true,
"xywh": "[10,10,140,80]",
"index": "a0"
}),
RichText::default(),
),
SurfaceElement::from_properties(
"rough-dash-conn".into(),
serde_json::json!({
"type": "connector",
"mode": 2,
"rough": true,
"roughness": 1.4,
"strokeStyle": "dash",
"strokeWidth": 2.0,
"source": { "position": [20.0, 120.0] },
"target": { "position": [240.0, 180.0] },
"index": "a1"
}),
RichText::default(),
),
];
let window = cx
.open_window(ui::WindowOptions::default(), |_, cx| {
cx.new(|_| SurfaceOrderView { elements })
})
.unwrap();
let _ = window.update(cx, |_, window, cx| {
window.refresh();
let _ = cx;
});
});
}
#[test]
fn canvas_css_font_stacks_resolve_without_panic() {
let platform = ui::HeadlessPlatform::new(320, 200, 1.);
let _ = ui::Application::with_platform(platform).run_embedded(|cx| {
crate::register_bundled_fonts(cx).unwrap();
let ts = ui::WindowTextSystem::new(cx.text_system().clone());
let text = RichText {
plain: "Synthetic Mindmap Node".into(),
delta: vec![TextDeltaOp::Insert {
insert: y_octo::TextInsert::Text("Synthetic Mindmap Node".into()),
format: None,
}],
};
for font_stack in [
"blocksuite:surface:Poppins",
"'Kalam', cursive",
"blocksuite:surface:BebasNeue",
"\"UnknownCanvasFont\", sans-serif",
] {
let style = TextStyle {
color: &ColorValue::Single("#111111".into()),
font: font_stack,
size: 16.0,
weight: "500",
slant: "normal",
align: TextAlign::Left,
};
let (layout, _) = style
.layout(&text, 240.0, PlaygroundTheme::Light, &ts)
.unwrap_or_else(|| panic!("expected layout for {font_stack}"));
assert!(!layout.lines().is_empty(), "empty lines for {font_stack}");
}
});
}
}
@@ -74,7 +74,9 @@ pub(super) fn emit(contour: &Contour, b: &mut PathBuilder, seed: i32, roughness:
matches!(contour.edges.first(), Some(Edge::Cubic(..))),
);
for path in out {
path.emit(b);
if !path.edges.is_empty() {
path.emit(b);
}
}
}
fn trace(contour: &Contour, b: &mut Vec<Contour>, rng: &mut Random, roughness: f64, svg: bool) {
+2 -2
View File
@@ -4,7 +4,7 @@ use ui::{
};
use crate::{
block_flow::{PAGE_SURFACE_ID, PageViewport, RemotePresence, page_elements, page_geometry},
block_flow::{PAGE_SURFACE_ID, PageViewport, RemotePresence, page_elements},
room_client::RoomStatus,
theme::{FONT_SANS, Palette},
};
@@ -336,7 +336,7 @@ impl PlaygroundView {
if window.focused(cx).is_none() {
self.editor_focus.focus(window, cx);
}
let geometry = page_geometry(viewport_width);
let geometry = self.current_page_geometry(viewport_width);
let surface = div()
.id("page-viewport")
.relative()
+84 -1
View File
@@ -499,7 +499,7 @@ impl PlaygroundView {
pub fn set_document(&mut self, state: crate::DocState, cx: &mut ui::Context<Self>) {
self.finish_inline_targets(crate::overlays::InlineTargetEnd::DiscardPreedit, None, None);
self.editor = Default::default();
self.saved_page_selection = None;
self.full_width_pages.clear();
self.overlays.reset();
self.reading_anchor = None;
self.flow = crate::block_flow::BlockFlow::new();
@@ -588,6 +588,34 @@ impl PlaygroundView {
.into_any_element(),
)
}
pub fn set_page_full_width(&mut self, page_id: impl Into<String>, full_width: bool) {
let id = page_id.into();
let changed = if full_width {
self.full_width_pages.insert(id)
} else {
self.full_width_pages.remove(&id)
};
if changed {
self.env_rev += 1;
}
}
pub fn is_current_page_full_width(&self) -> bool {
self.page_id
.as_deref()
.is_some_and(|id| self.full_width_pages.contains(id))
}
pub(crate) fn current_page_geometry(
&self,
viewport_width: f32,
) -> crate::block_flow::PageGeometry {
crate::block_flow::page_geometry_with_full_width(
viewport_width,
self.is_current_page_full_width(),
)
}
}
#[cfg(not(target_arch = "wasm32"))]
@@ -609,3 +637,58 @@ pub(crate) fn install_native_preview_wakeup(
}
}));
}
impl crate::PlaygroundOptions {
/// Parse command-line flags: `--theme light|dark`, `--mode page|edgeless`,
/// `--edgeless-readonly`, `--room <room>` and `--relay <ws_url>` (a relay without a room is an error).
pub fn from_args(args: impl IntoIterator<Item = String>) -> anyhow::Result<Self> {
let mut options = Self::default();
let mut room = None;
let mut relay = None;
let mut args = args.into_iter();
while let Some(flag) = args.next() {
let mut value = || {
args.next()
.ok_or_else(|| anyhow::anyhow!("{flag} requires a value"))
};
match flag.as_str() {
"--theme" => {
let value = value()?;
options.theme = crate::PlaygroundTheme::parse(&value)
.ok_or_else(|| anyhow::anyhow!("unknown theme {value:?} (light|dark)"))?;
}
"--mode" => {
let value = value()?;
options.mode = crate::PlaygroundMode::parse(&value)
.ok_or_else(|| anyhow::anyhow!("unknown mode {value:?} (page|edgeless)"))?;
}
"--edgeless-readonly" => options.edgeless_readonly = true,
"--page-readonly" => options.page_readonly = true,
"--database-readonly" => options.database_readonly = true,
"--form-factor" => {
let value = value()?;
options.form_factor = match value.as_str() {
"desktop" => crate::FormFactor::Desktop,
"tablet" => crate::FormFactor::Tablet,
"phone" => crate::FormFactor::Phone,
_ => anyhow::bail!("unknown form factor {value:?} (desktop|tablet|phone)"),
};
}
"--room" => room = Some(value()?),
"--relay" => relay = Some(value()?),
other => anyhow::bail!("unknown flag: {other}"),
}
}
match (room, relay) {
(Some(room), relay) => {
let config = crate::room_client::RoomConfig::new(&room, relay.as_deref());
#[cfg(not(target_family = "wasm"))]
config.validate_native()?;
options.room = Some(config);
}
(None, Some(_)) => anyhow::bail!("--relay requires --room <room>"),
(None, None) => {}
}
Ok(options)
}
}
@@ -340,7 +340,9 @@ impl PlaygroundView {
cx: &mut Context<Self>,
) {
let layout = if self.mode == crate::PlaygroundMode::Page {
let width = page_geometry(f32::from(w.viewport_size().width)).column_width;
let width = self
.current_page_geometry(f32::from(w.viewport_size().width))
.column_width;
self.ensure_layout(width, w)
} else {
self.flow_layout()
@@ -516,7 +518,9 @@ impl PlaygroundView {
pub(crate) fn select_all_progressive(&mut self, w: &mut Window, cx: &mut Context<Self>) {
let layout = if self.mode == PlaygroundMode::Page {
let width = page_geometry(f32::from(w.viewport_size().width)).column_width;
let width = self
.current_page_geometry(f32::from(w.viewport_size().width))
.column_width;
self.ensure_layout(width, w)
} else {
self.flow_layout()
@@ -554,7 +558,9 @@ impl PlaygroundView {
}
pub(crate) fn open_link_bar_shortcut(&mut self, w: &mut Window, cx: &mut Context<Self>) {
let width = page_geometry(f32::from(w.viewport_size().width)).column_width;
let width = self
.current_page_geometry(f32::from(w.viewport_size().width))
.column_width;
let Some(layout) = self.ensure_layout(width, w) else {
return;
};
@@ -74,7 +74,9 @@ impl PlaygroundView {
pub(super) fn current_flow_layout(&mut self, w: &Window) -> Option<Rc<FlowLayout>> {
if self.mode == crate::PlaygroundMode::Page {
let width = page_geometry(f32::from(w.viewport_size().width)).column_width;
let width = self
.current_page_geometry(f32::from(w.viewport_size().width))
.column_width;
self.ensure_layout(width, w)
} else {
self.flow_layout()
@@ -227,7 +227,8 @@ impl PlaygroundView {
self.dirty_text = None;
self.doc_rev += 1;
self.ensure_layout(
page_geometry(f32::from(w.viewport_size().width)).column_width,
self.current_page_geometry(f32::from(w.viewport_size().width))
.column_width,
w,
);
self.announce_selection(cx);
@@ -553,7 +554,8 @@ impl PlaygroundView {
cx: &mut Context<Self>,
) -> DocResult {
self.ensure_layout(
page_geometry(f32::from(w.viewport_size().width)).column_width,
self.current_page_geometry(f32::from(w.viewport_size().width))
.column_width,
w,
);
if self.apply_markdown(&sel, text, w, cx)? {
@@ -783,7 +785,10 @@ impl PlaygroundView {
pub(crate) fn screen_rect(&self, r: FlowRect, w: &Window) -> Bounds<Pixels> {
Bounds::new(
point(
px(page_geometry(f32::from(w.viewport_size().width)).column_x + r.x),
px(self
.current_page_geometry(f32::from(w.viewport_size().width))
.column_x
+ r.x),
px(TOPBAR_HEIGHT + r.y - self.scroll_y),
),
size(px(r.w), px(r.h)),
@@ -366,7 +366,8 @@ impl EntityInputHandler for PlaygroundView {
}
if self.table_cell.is_some() {
if let Some(layout) = self.ensure_layout(
page_geometry(f32::from(w.viewport_size().width)).column_width,
self.current_page_geometry(f32::from(w.viewport_size().width))
.column_width,
w,
) {
return self.table_cell_selection_bounds(r, &layout, w);
@@ -396,7 +397,8 @@ impl EntityInputHandler for PlaygroundView {
.map(|(id, _)| id)
.unwrap_or_else(|| sel.focus.block_id.clone());
let Some(layout) = self.ensure_layout(
page_geometry(f32::from(w.viewport_size().width)).column_width,
self.current_page_geometry(f32::from(w.viewport_size().width))
.column_width,
w,
) else {
return vec![];
@@ -54,7 +54,7 @@ impl PlaygroundView {
ContentScope::Page
}
pub(super) fn input_point(&self, pos: Point<Pixels>, window: &Window) -> Option<DocPoint> {
let geometry = page_geometry(f32::from(window.viewport_size().width));
let geometry = self.current_page_geometry(f32::from(window.viewport_size().width));
let layout = self.flow_layout()?;
let (x, y) = (
f32::from(pos.x) - geometry.column_x,
@@ -232,6 +232,7 @@ impl PlaygroundView {
return;
}
self.commit_active_preedit(w, cx);
self.keyboard_toolbar_dismissed = false;
self.editor.selection = Some(sel);
self.editor.block_selection.clear();
self.editor.block_selection_anchor = None;
@@ -394,7 +394,9 @@ impl PlaygroundView {
cx: &mut Context<Self>,
) {
let layout = if self.mode == crate::PlaygroundMode::Page {
let width = page_geometry(f32::from(w.viewport_size().width)).column_width;
let width = self
.current_page_geometry(f32::from(w.viewport_size().width))
.column_width;
self.ensure_layout(width, w)
} else {
self.flow_layout()
@@ -62,6 +62,12 @@ impl PlaygroundView {
{
self.page_id = None;
}
if let Some(full_width) = self.state.workspace.full_width_pages()
&& full_width != self.full_width_pages
{
self.full_width_pages = full_width;
self.env_rev += 1;
}
self.snapshot = self
.page_id
.as_deref()
@@ -142,7 +148,8 @@ impl PlaygroundView {
_ => "",
};
if !text.is_empty() {
parts.push(text.to_string());
parts
.push(text.replace("\r\n", " ").replace(['\r', '\n'], " "));
if parts.len() >= 2 {
break;
}
@@ -250,6 +257,11 @@ impl PlaygroundView {
},
);
room.link.send(RoomCommand::FetchBlob(source_id));
} else if self.room.is_none()
&& !matches!(self.images.get(&source_id), Some(ImageSlot::Unavailable))
{
self.images.insert(source_id, ImageSlot::Unavailable);
self.env_rev += 1;
}
}
}
@@ -291,27 +303,52 @@ impl PlaygroundView {
}
/// Drop any body caret/range or block selection whose target block was removed or is
/// unaddressable in the current mode so subsequent typing never targets a hidden/deleted block.
/// unaddressable in the current mode, and clamp surviving endpoints to each block's
/// current UTF-16 length so subsequent edits never hit out-of-bounds CRDT indices.
pub(crate) fn prune_dangling_selection(
&mut self,
w: Option<&mut Window>,
cx: &mut ui::Context<Self>,
) {
let selection_alive = self.editor.selection.as_ref().is_none_or(|sel| {
self.snapshot.as_ref().is_some_and(|snap| {
self.is_block_addressable_in_current_mode(snap, &sel.anchor.block_id)
&& self.is_block_addressable_in_current_mode(snap, &sel.focus.block_id)
})
let endpoint_bounds = self.editor.selection.as_ref().and_then(|sel| {
let snap = self.snapshot.as_ref()?;
if !self.is_block_addressable_in_current_mode(snap, &sel.anchor.block_id)
|| !self.is_block_addressable_in_current_mode(snap, &sel.focus.block_id)
{
return None;
}
let a_max = self
.block_text(&sel.anchor.block_id)?
.encode_utf16()
.count() as u64;
let f_max = self.block_text(&sel.focus.block_id)?.encode_utf16().count() as u64;
Some((a_max, f_max))
});
let mut pruned = false;
if !selection_alive {
self.editor.selection = None;
self.editor.preedit = None;
self.editor.last_typing = None;
self.editor.pending_marks.clear();
self.editor.slash_trigger = None;
self.overlays.set_keyboard_toolbar_visible(false);
pruned = true;
if self.editor.selection.is_some() {
match endpoint_bounds {
None => {
self.editor.selection = None;
self.editor.preedit = None;
self.editor.last_typing = None;
self.editor.pending_marks.clear();
self.editor.slash_trigger = None;
self.overlays.set_keyboard_toolbar_visible(false);
pruned = true;
}
Some((a_max, f_max)) => {
if let Some(sel) = self.editor.selection.as_mut()
&& (sel.anchor.caret.utf16_offset > a_max
|| sel.focus.caret.utf16_offset > f_max)
{
sel.anchor.caret.utf16_offset = sel.anchor.caret.utf16_offset.min(a_max);
sel.focus.caret.utf16_offset = sel.focus.caret.utf16_offset.min(f_max);
self.editor.preedit = None;
self.editor.last_typing = None;
pruned = true;
}
}
}
}
if !self.editor.block_selection.is_empty() {
let valid_ids: std::collections::HashSet<String> = self
@@ -369,15 +406,11 @@ impl PlaygroundView {
}
let now_ms = self.now_ms(cx);
let current_x = self.indicator_x(now_ms);
let prev_mode = self.mode;
// Commit any pending inline edit (table cell or Edgeless label) cleanly before switching modes.
self.finish_inline_targets(InlineTargetEnd::CommitPreedit, Some(window), Some(cx));
if self.edgeless.authoring.editing_spatial_block().is_some() {
self.edgeless_commit_inline_edit(window, cx);
}
if prev_mode == PlaygroundMode::Page && target == PlaygroundMode::Edgeless {
self.saved_page_selection = self.editor.selection.take();
}
self.edgeless.authoring.reset_transient();
self.page_scroll_fling = None;
self.code_scroll_fling = None;
@@ -390,9 +423,6 @@ impl PlaygroundView {
self.context_paste_task = None;
self.context_menu_target = None;
self.overlays.reset();
if target == PlaygroundMode::Page && self.editor.selection.is_none() {
self.editor.selection = self.saved_page_selection.take();
}
self.prune_dangling_selection(Some(window), cx);
self.pill_motion = Some(Motion::new(
current_x,
@@ -541,7 +571,7 @@ impl PlaygroundView {
&& self.form_factor.is_touch_form_factor()
&& let Some(layout) = self.flow_layout()
{
let geom = crate::block_flow::page_geometry(self.window_size.0);
let geom = self.current_page_geometry(self.window_size.0);
let wx = f32::from(event.position.x) - geom.column_x;
let wy = f32::from(event.position.y) - crate::TOPBAR_HEIGHT + self.scroll_y;
if let Some(block) = layout.blocks.iter().find(|b| {
@@ -716,58 +746,3 @@ impl PlaygroundView {
Some(layout)
}
}
impl crate::PlaygroundOptions {
/// Parse command-line flags: `--theme light|dark`, `--mode page|edgeless`,
/// `--edgeless-readonly`, `--room <room>` and `--relay <ws_url>` (a relay without a room is an error).
pub fn from_args(args: impl IntoIterator<Item = String>) -> anyhow::Result<Self> {
let mut options = Self::default();
let mut room = None;
let mut relay = None;
let mut args = args.into_iter();
while let Some(flag) = args.next() {
let mut value = || {
args.next()
.ok_or_else(|| anyhow::anyhow!("{flag} requires a value"))
};
match flag.as_str() {
"--theme" => {
let value = value()?;
options.theme = crate::PlaygroundTheme::parse(&value)
.ok_or_else(|| anyhow::anyhow!("unknown theme {value:?} (light|dark)"))?;
}
"--mode" => {
let value = value()?;
options.mode = PlaygroundMode::parse(&value)
.ok_or_else(|| anyhow::anyhow!("unknown mode {value:?} (page|edgeless)"))?;
}
"--edgeless-readonly" => options.edgeless_readonly = true,
"--page-readonly" => options.page_readonly = true,
"--database-readonly" => options.database_readonly = true,
"--form-factor" => {
let value = value()?;
options.form_factor = match value.as_str() {
"desktop" => crate::FormFactor::Desktop,
"tablet" => crate::FormFactor::Tablet,
"phone" => crate::FormFactor::Phone,
_ => anyhow::bail!("unknown form factor {value:?} (desktop|tablet|phone)"),
};
}
"--room" => room = Some(value()?),
"--relay" => relay = Some(value()?),
other => anyhow::bail!("unknown flag: {other}"),
}
}
match (room, relay) {
(Some(room), relay) => {
let config = crate::room_client::RoomConfig::new(&room, relay.as_deref());
#[cfg(not(target_family = "wasm"))]
config.validate_native()?;
options.room = Some(config);
}
(None, Some(_)) => anyhow::bail!("--relay requires --room <room>"),
(None, None) => {}
}
Ok(options)
}
}
+9 -13
View File
@@ -198,6 +198,7 @@ pub struct PlaygroundView {
pub(crate) page_id: Option<String>,
pub(crate) snapshot: Option<Rc<PageSnapshot>>,
pub(crate) page_titles: BTreeMap<String, String>,
pub(crate) full_width_pages: BTreeSet<String>,
pub(crate) default_doc_directory: directory::InMemoryDocDirectory,
pub(crate) cached_page_revisions: HashMap<String, u64>,
pub(crate) custom_doc_directory: Option<Box<dyn directory::WorkspaceDocDirectory>>,
@@ -256,7 +257,6 @@ pub struct PlaygroundView {
pub(crate) last_touch_scroll_ms: Option<f64>,
pub(crate) keep_keyboard_on_block_selection: bool,
pub(crate) block_selection_return_caret: Option<String>,
pub(crate) saved_page_selection: Option<editor_session::DocumentSelection>,
pub(crate) touch_long_press_anchor:
Option<(editor_session::DocPoint, editor_session::DocPoint)>,
pub(crate) touch_selection_menu_open: bool,
@@ -369,6 +369,7 @@ impl PlaygroundView {
page_id: None,
snapshot: None,
page_titles: BTreeMap::new(),
full_width_pages: BTreeSet::new(),
default_doc_directory,
cached_page_revisions: HashMap::new(),
custom_doc_directory: None,
@@ -425,7 +426,6 @@ impl PlaygroundView {
native_selection_drag_anchor: None,
native_selection_drag_cell_anchor: None,
native_selection_drag_active: false,
saved_page_selection: None,
edgeless_readonly_selection_target: None,
caret_active_since_ms: 0.0,
caret_blink_task: None,
@@ -1890,14 +1890,10 @@ pub(crate) mod tests {
assert_eq!(broken.layout.line_count(), 2, "{context}");
assert_eq!(block("e-marks").body.height, 23.0, "{context}");
// Images without usable bytes keep their frame and say why.
assert_eq!(text_of("e-image-missing"), "Loading image");
assert_eq!(text_of("e-image-broken"), "Image unavailable");
let frame_width = 300.0_f32.min(long.body.width);
assert_eq!(
block("e-image-missing").body.height,
(120.0 * frame_width / 300.0).round()
);
// Offline missing and broken images both render the compact 78px error card.
assert_eq!(text_of("e-image-missing"), "Image loading failed.");
assert_eq!(text_of("e-image-broken"), "Image loading failed.");
assert_eq!(block("e-image-missing").body.height, 78.0);
// A bookmark without metadata falls back to its host name.
assert_eq!(text_of("e-bookmark"), "example.org");
// An empty code block still has one line, plus its caption.
@@ -2617,12 +2613,12 @@ pub(crate) mod tests {
&|view| fetch(view).is_some_and(|fetch| !fetch.in_flight && fetch.misses >= 3),
"the third miss",
);
assert_eq!(image_text().as_deref(), Some("Image unavailable"));
assert_eq!(image_text().as_deref(), Some("Image loading failed."));
step(
&|view| fetch(view).is_some_and(|fetch| !fetch.in_flight && fetch.misses >= 6),
"retries past the backoff cap",
);
assert_eq!(image_text().as_deref(), Some("Image unavailable"));
assert_eq!(image_text().as_deref(), Some("Image loading failed."));
assert_eq!(
[1, 2, 3, 4, 5, 6, 60].map(blob_retry_backoff_ms),
[500, 1_000, 2_000, 4_000, 4_000, 4_000, 4_000]
@@ -2644,7 +2640,7 @@ pub(crate) mod tests {
assert!(
!matches!(
image.text.as_deref(),
Some("Loading image" | "Image unavailable")
Some("Loading image" | "Image loading failed.")
),
"{:?}",
image.text
@@ -45,7 +45,7 @@ impl PlaygroundView {
OverlayScene {
snapshot,
layout,
geometry: crate::block_flow::page_geometry(self.window_size.0),
geometry: self.current_page_geometry(self.window_size.0),
window: self.window_size,
bottom_inset: self.ime_insets.last_bottom,
scroll_y: self.scroll_y,
@@ -96,6 +96,10 @@ impl PlaygroundView {
if after.is_some() {
self.context_paste_task = None;
self.context_menu_target = None;
if before.is_none() {
self.keyboard_toolbar_dismissed = false;
window.request_virtual_keyboard();
}
}
if before.is_some() && after.is_none() {
self.reset_caret_blink(cx);
@@ -287,12 +291,11 @@ impl PlaygroundView {
self.equation_snapshot = None;
}
self.sync_link_input(input, window, cx);
self.keyboard_toolbar_dismissed = false;
self.editor.slash_trigger = None;
self.editor.linked_doc_trigger = None;
self.editor.block_selection.clear();
if let Some(layout) = self.flow_layout() {
let geometry = crate::page_geometry(f32::from(window.viewport_size().width));
let geometry = self.current_page_geometry(f32::from(window.viewport_size().width));
let world_x = f32::from(event.position.x) - geometry.column_x;
let world_y = f32::from(event.position.y) - crate::TOPBAR_HEIGHT + self.scroll_y;
if let Some((block_id, local_x, local_y)) = layout.blocks.iter().find_map(|block| {
@@ -84,7 +84,14 @@ impl PlaygroundView {
let Some(note_id) = note_id else {
return;
};
let before = self.selection_snapshot();
let before = self.selection_snapshot().or_else(|| {
let page = self.page()?;
let (bid, off) = self.flow_layout()?.blocks.iter().rev().find_map(|b| {
b.editable()
.then(|| (b.block_id.clone(), b.body.plain.encode_utf16().count() as u64))
})?;
page.capture_selection_snapshot(&bid, off, &bid, off).ok()
});
let new_id = self.fresh_block_id();
let now_ms = self.now_ms(cx) as u64;
let commit = self.page_mut().ok().and_then(|page| {
@@ -138,7 +138,7 @@ impl PlaygroundView {
use crate::{
PlaygroundMode, TOPBAR_HEIGHT,
block_flow::{CODE_PADDING, CodePreviewKind, page_geometry},
block_flow::{CODE_PADDING, CodePreviewKind},
wasm_preview::{HtmlEmbedMount, reconcile_html_embeds},
};
@@ -151,7 +151,7 @@ impl PlaygroundView {
return;
};
let geom = page_geometry(viewport_width);
let geom = self.current_page_geometry(viewport_width);
let vp_top = TOPBAR_HEIGHT;
let vp_bottom = TOPBAR_HEIGHT + viewport_height;
let mut mounts = Vec::new();
@@ -434,7 +434,7 @@ impl PlaygroundView {
/// or selects the word inside a tapped table cell / selects a non-editable block (`L3`).
pub fn long_press_word(&mut self, x: f32, y: f32, window: &mut Window, cx: &mut Context<Self>) {
if let Some(layout) = self.flow_layout() {
let geom = crate::block_flow::page_geometry(f32::from(window.viewport_size().width));
let geom = self.current_page_geometry(f32::from(window.viewport_size().width));
let wx = x - geom.column_x;
let wy = y - crate::TOPBAR_HEIGHT + self.scroll_y;
if let Some(block) = layout
@@ -645,11 +645,16 @@ impl PlaygroundView {
self.focus_first_text_block(window, cx);
}
/// Reload the built-in showcase document and focus its first text block.
/// Reload the built-in showcase document (focusing the first text block on desktop only;
/// touch form factors leave body selection empty until an explicit editing tap).
pub fn load_showcase_document(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if let Ok(state) = crate::seed_showcase_doc() {
self.set_document(state, cx);
self.focus_first_text_block(window, cx);
if self.form_factor.is_touch_form_factor() {
self.editor_focus.focus(window, cx);
} else {
self.focus_first_text_block(window, cx);
}
}
}
@@ -766,7 +771,6 @@ impl PlaygroundView {
Some(cx),
);
self.editor = Default::default();
self.saved_page_selection = None;
self.overlays.reset();
self.reading_anchor = None;
self.flow = crate::block_flow::BlockFlow::new();
@@ -11,7 +11,7 @@ use ui::{Context, KeyDownEvent, Window};
use crate::{
PlaygroundView, TOPBAR_HEIGHT,
block_flow::{FlowLayout, page_geometry},
block_flow::FlowLayout,
edgeless::EdgelessInlineEdit,
overlays::{InlineTableCell, TableCellDragMode},
};
@@ -164,7 +164,7 @@ impl PlaygroundView {
let _ = page.stop_capturing();
}
if let Some((sx, sy)) = screen_pos {
let geom = page_geometry(f32::from(window.viewport_size().width));
let geom = self.current_page_geometry(f32::from(window.viewport_size().width));
if let Some(layout) = self.ensure_layout(geom.column_width, window)
&& let Some((bx, by, hit)) =
Self::find_table_cell_hit(&layout, &block_id, &row_id, &column_id)
@@ -220,7 +220,7 @@ impl PlaygroundView {
&cell.column_id,
)
{
let geom = page_geometry(f32::from(window.viewport_size().width));
let geom = self.current_page_geometry(f32::from(window.viewport_size().width));
let local_x = sx - geom.column_x - bx + self.overlays.code_scroll_x(&cell.block_id);
let local_y = sy - TOPBAR_HEIGHT + self.scroll_y - by;
let off = hit.hit_text(local_x, local_y, &initial).utf16_offset as usize;
@@ -11,7 +11,7 @@ use y_octo::{TextDeltaOp, TextInsert};
use crate::{
PlaygroundView, TOPBAR_HEIGHT,
block_flow::{FlowLayout, FlowRect, PAGE_SURFACE_ID, PageViewport, page_geometry},
block_flow::{FlowLayout, FlowRect, PAGE_SURFACE_ID, PageViewport},
theme::Palette,
};
@@ -111,7 +111,7 @@ impl PlaygroundView {
let (bx, by, hit) =
Self::find_table_cell_hit(&layout, &cell.block_id, &cell.row_id, &cell.column_id)?;
let scroll_x = self.overlays.code_scroll_x(&cell.block_id);
let geom = page_geometry(f32::from(w.viewport_size().width));
let geom = self.current_page_geometry(f32::from(w.viewport_size().width));
let local_x = f32::from(p.x) - geom.column_x - bx + scroll_x;
let local_y = f32::from(p.y) - TOPBAR_HEIGHT + self.scroll_y - by;
hit.rect.contains(local_x, local_y).then(|| {
@@ -3,7 +3,7 @@
use ui::{Context, MouseButton, MouseMoveEvent, Window};
use super::TableCellDragMode;
use crate::{PlaygroundView, TOPBAR_HEIGHT, block_flow::page_geometry};
use crate::{PlaygroundView, TOPBAR_HEIGHT};
impl PlaygroundView {
/// Mark the active table cell to be revealed vertically on the next frame and immediately
@@ -77,7 +77,7 @@ impl PlaygroundView {
else {
return;
};
let geom = page_geometry(f32::from(window.viewport_size().width));
let geom = self.current_page_geometry(f32::from(window.viewport_size().width));
let local_x = f32::from(event.position.x) - geom.column_x - bx
+ self.overlays.code_scroll_x(&block_id);
let local_y = f32::from(event.position.y) - TOPBAR_HEIGHT + self.scroll_y - by;
@@ -10,7 +10,6 @@ use crate::{
PlaygroundMode, PlaygroundView, TOPBAR_HEIGHT,
block_flow::{
FlowKind, FlowLayout, FlowRect, FlowTextLayout, heading_marker_rect_for_direction,
page_geometry,
},
edgeless::{NOTE_CARD_PADDING, SpatialItemKind, point_in_rotated_rect, rotate_point_around},
editor_session::{DocPoint, DocumentSelection, word_range},
@@ -416,7 +415,7 @@ impl PlaygroundView {
let Some(block) = layout.block(&block_id) else {
return false;
};
let geom = page_geometry(self.window_size.0);
let geom = self.current_page_geometry(self.window_size.0);
let sx = geom.column_x + block.x + block.body.width * 0.5;
let sy = TOPBAR_HEIGHT + block.y + block.body.height * 0.5 - self.scroll_y;
let scene =
@@ -452,7 +451,7 @@ impl PlaygroundView {
window: &Window,
) -> Option<String> {
let layout = self.flow_layout()?;
let geom = page_geometry(f32::from(window.viewport_size().width));
let geom = self.current_page_geometry(f32::from(window.viewport_size().width));
let wx = f32::from(pos.x) - geom.column_x;
let wy = f32::from(pos.y) - TOPBAR_HEIGHT + self.scroll_y;
layout.blocks.iter().find_map(|b| {
@@ -472,7 +471,7 @@ impl PlaygroundView {
let Some(layout) = self.flow_layout() else {
return false;
};
let geom = page_geometry(f32::from(window.viewport_size().width));
let geom = self.current_page_geometry(f32::from(window.viewport_size().width));
let wx = x - geom.column_x;
let wy = y - TOPBAR_HEIGHT + self.scroll_y;
let dir = window.layout_direction();
@@ -599,7 +598,7 @@ impl PlaygroundView {
window: &Window,
) -> Option<String> {
let layout = self.flow_layout()?;
let geom = page_geometry(f32::from(window.viewport_size().width));
let geom = self.current_page_geometry(f32::from(window.viewport_size().width));
let wx = x - geom.column_x;
let wy = y - TOPBAR_HEIGHT + self.scroll_y;
Self::hit_inline_reference_in_layout(&layout, wx, wy)
@@ -6,7 +6,7 @@ use ui::{Bounds, Context, Window, point, px};
use super::{SelectionRectGeometry, endpoint_is_rtl};
use crate::{
PlaygroundMode, PlaygroundView, TOPBAR_HEIGHT,
block_flow::{FlowKind, FlowLayout, FlowRect, page_geometry},
block_flow::{FlowKind, FlowLayout, FlowRect},
edgeless::{NOTE_CARD_PADDING, rotate_point_around},
editor_session::{DocPoint, DocumentSelection, word_range},
};
@@ -55,7 +55,7 @@ impl PlaygroundView {
let Some(layout) = self.flow_layout() else {
return false;
};
let geom = page_geometry(f32::from(window.viewport_size().width));
let geom = self.current_page_geometry(f32::from(window.viewport_size().width));
let wx = x - geom.column_x;
let wy = y - TOPBAR_HEIGHT + self.scroll_y;
if let Some(last) = layout.blocks.last()
@@ -86,7 +86,7 @@ fn extract_snapshot_snippet(snapshot: &PageSnapshot) -> String {
_ => "",
};
if !text.is_empty() {
parts.push(text.to_string());
parts.push(text.replace("\r\n", " ").replace(['\r', '\n'], " "));
if parts.len() >= 2 {
break;
}
+67 -88
View File
@@ -32,10 +32,7 @@ pub struct PathBuilder {
impl From<lyon::path::Builder> for PathBuilder {
fn from(builder: lyon::path::Builder) -> Self {
Self {
raw: builder.with_svg(),
..Default::default()
}
Self::from(builder.with_svg())
}
}
@@ -106,16 +103,10 @@ impl PathBuilder {
///
/// [MDN](https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Attribute/stroke-dasharray)
pub fn dash_array(mut self, dash_array: &[Pixels]) -> Self {
// If an odd number of values is provided, then the list of values is repeated to yield an even number of values.
// Thus, 5,3,2 is equivalent to 5,3,2,5,3,2.
let array = if dash_array.len() % 2 == 1 {
let mut new_dash_array = dash_array.to_vec();
new_dash_array.extend_from_slice(dash_array);
new_dash_array
} else {
dash_array.to_vec()
};
let mut array = dash_array.to_vec();
if array.len() % 2 == 1 {
array.extend_from_slice(dash_array);
}
self.dash_array = Some(array);
self
}
@@ -209,21 +200,14 @@ impl PathBuilder {
/// Applies a translation to the path.
#[inline]
pub fn translate(&mut self, to: Point<Pixels>) {
if let Some(transform) = self.transform {
self.transform = Some(transform.then_translate(Vector2D::new(to.x.0, to.y.0)));
} else {
self.transform = Some(Transform::translation(to.x.0, to.y.0))
}
let t = self.transform.unwrap_or_default();
self.transform = Some(t.then_translate(Vector2D::new(to.x.0, to.y.0)));
}
/// Applies a scale to the path.
#[inline]
pub fn scale(&mut self, scale: f32) {
if let Some(transform) = self.transform {
self.transform = Some(transform.then_scale(scale, scale));
} else {
self.transform = Some(Transform::scale(scale, scale));
}
self.transform = Some(self.transform.unwrap_or_default().then_scale(scale, scale));
}
/// Applies a rotation to the path.
@@ -231,12 +215,8 @@ impl PathBuilder {
/// The `angle` is in degrees value in the range 0.0 to 360.0.
#[inline]
pub fn rotate(&mut self, angle: f32) {
let radians = angle.to_radians();
if let Some(transform) = self.transform {
self.transform = Some(transform.then_rotate(Angle::radians(radians)));
} else {
self.transform = Some(Transform::rotation(Angle::radians(radians)));
}
let t = self.transform.unwrap_or_default();
self.transform = Some(t.then_rotate(Angle::radians(angle.to_radians())));
}
/// Builds into a [`Path`].
@@ -249,17 +229,12 @@ impl PathBuilder {
path: &lyon::path::Path,
options: &FillOptions,
) -> Result<Path<Pixels>, Error> {
// Will contain the result of the tessellation.
let mut buf: VertexBuffers<lyon::math::Point, u16> = VertexBuffers::new();
let mut tessellator = FillTessellator::new();
// Compute the tessellation.
tessellator.tessellate_path(
FillTessellator::new().tessellate_path(
path,
options,
&mut BuffersBuilder::new(&mut buf, |vertex: FillVertex| vertex.position()),
&mut BuffersBuilder::new(&mut buf, |v: FillVertex| v.position()),
)?;
Ok(Self::build_path(buf))
}
@@ -268,71 +243,75 @@ impl PathBuilder {
path: &lyon::path::Path,
options: &StrokeOptions,
) -> Result<Path<Pixels>, Error> {
let path = if let Some(dash_array) = dash_array {
let measurements = lyon::algorithms::measure::PathMeasurements::from_path(path, 0.01);
let mut sampler = measurements
.create_sampler(path, lyon::algorithms::measure::SampleType::Normalized);
let mut builder = lyon::path::Path::builder();
let total_length = sampler.length();
let dash_array_len = dash_array.len();
let mut pos = 0.;
let mut dash_index = 0;
while pos < total_length {
let dash_length = dash_array[dash_index % dash_array_len].0;
let next_pos = (pos + dash_length).min(total_length);
if dash_index % 2 == 0 {
let start = pos / total_length;
let end = next_pos / total_length;
sampler.split_range(start..end, &mut builder);
if let Some(da) = dash_array.filter(|da| da.iter().any(|d| d.0 > 0.0)) {
use lyon::algorithms::measure::{PathMeasurements, SampleType};
use lyon::path::Event;
let (mut out, mut sub, mut has_seg) = (
lyon::path::Path::builder(),
lyon::path::Path::builder(),
false,
);
for event in path.iter() {
match event {
Event::Begin { at } => {
sub = lyon::path::Path::builder();
sub.begin(at);
has_seg = false;
}
Event::Line { to, .. } => {
sub.line_to(to);
has_seg = true;
}
Event::Quadratic { ctrl, to, .. } => {
sub.quadratic_bezier_to(ctrl, to);
has_seg = true;
}
Event::Cubic {
ctrl1, ctrl2, to, ..
} => {
sub.cubic_bezier_to(ctrl1, ctrl2, to);
has_seg = true;
}
Event::End { close, .. } => {
sub.end(close);
if !has_seg {
continue;
}
let sp = std::mem::replace(&mut sub, lyon::path::Path::builder()).build();
let m = PathMeasurements::from_path(&sp, 0.01);
let mut s = m.create_sampler(&sp, SampleType::Normalized);
let (total, mut pos, mut i) = (s.length(), 0.0, 0);
while total > 0.0 && pos < total {
let next = (pos + da[i % da.len()].0.max(0.0)).min(total);
if i % 2 == 0 && next > pos {
s.split_range((pos / total)..(next / total), &mut out);
}
(pos, i) = (next, i + 1);
}
}
}
pos = next_pos;
dash_index += 1;
}
&builder.build()
} else {
path
};
// Will contain the result of the tessellation.
return Self::tessellate_stroke(None, &out.build(), options);
}
let mut buf: VertexBuffers<lyon::math::Point, u16> = VertexBuffers::new();
let mut tessellator = StrokeTessellator::new();
// Compute the tessellation.
tessellator.tessellate_path(
StrokeTessellator::new().tessellate_path(
path,
options,
&mut BuffersBuilder::new(&mut buf, |vertex: StrokeVertex| vertex.position()),
&mut BuffersBuilder::new(&mut buf, |v: StrokeVertex| v.position()),
)?;
Ok(Self::build_path(buf))
}
/// Builds a [`Path`] from a [`lyon::tessellation::VertexBuffers`].
pub fn build_path(buf: VertexBuffers<lyon::math::Point, u16>) -> Path<Pixels> {
if buf.vertices.is_empty() {
let Some(&first_point) = buf.vertices.first() else {
return Path::new(Point::default());
}
let first_point = buf.vertices[0];
};
let mut path = Path::new(first_point.into());
for i in 0..buf.indices.len() / 3 {
let i0 = buf.indices[i * 3] as usize;
let i1 = buf.indices[i * 3 + 1] as usize;
let i2 = buf.indices[i * 3 + 2] as usize;
let v0 = buf.vertices[i0];
let v1 = buf.vertices[i1];
let v2 = buf.vertices[i2];
path.push_triangle(
(v0.into(), v1.into(), v2.into()),
(point(0., 1.), point(0., 1.), point(0., 1.)),
);
for tri in buf.indices.chunks_exact(3) {
let [v0, v1, v2] = [0, 1, 2].map(|i| buf.vertices[tri[i] as usize].into());
path.push_triangle((v0, v1, v2), (point(0., 1.), point(0., 1.), point(0., 1.)));
}
path
}
}
+128 -143
View File
@@ -373,17 +373,14 @@ impl TextSystem {
// Consider removing this?
/// Returns the shaped layout width of for the given character, in the given font and size.
pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
let mut buffer = [0; 4];
let buffer = ch.encode_utf8(&mut buffer);
let mut buf = [0; 4];
let s = ch.encode_utf8(&mut buf);
let runs = [FontRun {
len: s.len(),
font_id,
}];
self.platform_text_system
.layout_line(
buffer,
font_size,
&[FontRun {
len: buffer.len(),
font_id,
}],
)
.layout_line(s, font_size, &runs)
.width
}
@@ -441,39 +438,38 @@ impl TextSystem {
font_size: Pixels,
line_height: Pixels,
) -> Pixels {
let ascent = self.ascent(font_id, font_size);
let descent = self.descent(font_id, font_size);
let padding_top = (line_height - ascent - descent) / 2.;
padding_top + ascent
let (a, d) = (
self.ascent(font_id, font_size),
self.descent(font_id, font_size),
);
(line_height - a - d) / 2. + a
}
fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
let lock = self.font_metrics.upgradable_read();
if let Some(metrics) = lock.get(&font_id) {
read(metrics)
} else {
let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
let metrics = lock
.entry(font_id)
.or_insert_with(|| self.platform_text_system.font_metrics(font_id));
read(metrics)
return read(metrics);
}
let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
read(
lock.entry(font_id)
.or_insert_with(|| self.platform_text_system.font_metrics(font_id)),
)
}
/// Returns a handle to a line wrapper, for the given font and font size.
pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
let lock = &mut self.wrapper_pool.lock();
let font_id = self.resolve_font(&font);
let char_widths = lock
.entry(FontIdWithSize { font_id, font_size })
let key = FontIdWithSize { font_id, font_size };
let widths = self
.wrapper_pool
.lock()
.entry(key)
.or_default()
.pop()
.unwrap_or_default();
let wrapper = LineWrapper::new(font_id, font_size, self.clone(), char_widths);
LineWrapperHandle {
wrapper: Some(wrapper),
wrapper: Some(LineWrapper::new(font_id, font_size, self.clone(), widths)),
text_system: self.clone(),
}
}
@@ -481,14 +477,12 @@ impl TextSystem {
/// Get the rasterized size and location of a specific, rendered glyph.
pub(crate) fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
let raster_bounds = self.raster_bounds.upgradable_read();
if let Some(bounds) = raster_bounds.get(params) {
Ok(*bounds)
} else {
let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
raster_bounds.insert(params.clone(), bounds);
Ok(bounds)
if let Some(&bounds) = raster_bounds.get(params) {
return Ok(bounds);
}
let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
RwLockUpgradableReadGuard::upgrade(raster_bounds).insert(params.clone(), bounds);
Ok(bounds)
}
pub(crate) fn rasterize_glyph(
@@ -554,10 +548,29 @@ impl TextSystem {
if let Some(font_id) = lookup_font(font) {
Some(font_id)
} else {
let font_id = self.fallback_font_stack.iter().find_map(lookup_font);
let candidate = |family: &str| Font {
family: SharedString::from(family.to_owned()),
fallbacks: None,
..font.clone()
};
let font_id = font
.fallbacks
.as_ref()
.and_then(|fb| {
fb.fallback_list()
.iter()
.find_map(|f| lookup_font(&candidate(f)))
})
.or_else(|| self.fallback_font_stack.iter().find_map(&mut lookup_font))
.or_else(|| {
self.platform_text_system
.all_font_names()
.into_iter()
.find_map(|f| lookup_font(&candidate(&f)))
});
if let Some(font_id) = font_id {
font_ids.with_upgraded(|font_ids| {
font_ids.insert(font.clone(), CachedFont::Fallback(font_id));
font_ids.with_upgraded(|m| {
m.insert(font.clone(), CachedFont::Fallback(font_id));
});
}
font_id
@@ -567,13 +580,14 @@ impl TextSystem {
log::warn!("failed to load font {font:?}: {error:#}");
}
font_id.unwrap_or_else(|| {
let stack = self
.fallback_font_stack
.iter()
.map(|f| &f.family)
.join(", ");
panic!(
"failed to resolve font '{}' or any of the fallbacks: {}",
font.family,
self.fallback_font_stack
.iter()
.map(|fallback| &fallback.family)
.join(", ")
"failed to resolve font '{}' or any of the fallbacks: {stack}",
font.family
);
})
}
@@ -669,32 +683,36 @@ impl WindowTextSystem {
layout
}
fn paintable_line(text: SharedString, layout: Arc<LineLayout>, runs: &[TextRun]) -> ShapedLine {
debug_assert!(
text.find('\n').is_none(),
"text argument should not contain newlines"
);
fn push_decoration_run(
last: Option<&mut DecorationRun>,
run: &TextRun,
len: u32,
) -> Option<DecorationRun> {
if let Some(last) = last
&& last.color == run.color
&& last.underline == run.underline
&& last.strikethrough == run.strikethrough
&& last.background_color == run.background_color
{
last.len += len;
return None;
}
Some(DecorationRun {
len,
color: run.color,
background_color: run.background_color,
underline: run.underline,
strikethrough: run.strikethrough,
})
}
fn paintable_line(text: SharedString, layout: Arc<LineLayout>, runs: &[TextRun]) -> ShapedLine {
debug_assert!(!text.contains('\n'), "text argument cannot have newlines");
let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
for run in runs {
if let Some(last_run) = decoration_runs.last_mut()
&& last_run.color == run.color
&& last_run.underline == run.underline
&& last_run.strikethrough == run.strikethrough
&& last_run.background_color == run.background_color
{
last_run.len += run.len as u32;
continue;
}
decoration_runs.push(DecorationRun {
len: run.len as u32,
color: run.color,
background_color: run.background_color,
underline: run.underline,
strikethrough: run.strikethrough,
});
let next = Self::push_decoration_run(decoration_runs.last_mut(), run, run.len as u32);
decoration_runs.extend(next);
}
ShapedLine {
layout,
text,
@@ -710,20 +728,18 @@ impl WindowTextSystem {
runs: &[TextRun],
letter_spacing_px: f32,
) -> ShapedLine {
// Preserve shaping across paint-only boundaries; the separate decoration
// runs still associate each glyph with its source color.
let mut fonts = self.font_runs_buffer.take();
fonts.clear();
for run in runs {
let id = self.resolve_font(&run.font);
let font_id = self.resolve_font(&run.font);
if let Some(last) = fonts.last_mut()
&& last.font_id == id
&& last.font_id == font_id
{
last.len += run.len;
} else {
fonts.push(FontRun {
len: run.len,
font_id: id,
font_id,
});
}
}
@@ -788,25 +804,13 @@ impl WindowTextSystem {
};
let run_len_within_line = cmp::min(line_end - run_start, run.len);
let decoration_changed = if let Some(last_run) = decoration_runs.last_mut()
&& last_run.color == run.color
&& last_run.underline == run.underline
&& last_run.strikethrough == run.strikethrough
&& last_run.background_color == run.background_color
{
last_run.len += run_len_within_line as u32;
false
} else {
decoration_runs.push(DecorationRun {
len: run_len_within_line as u32,
color: run.color,
background_color: run.background_color,
underline: run.underline,
strikethrough: run.strikethrough,
});
true
};
let next = Self::push_decoration_run(
decoration_runs.last_mut(),
run,
run_len_within_line as u32,
);
let decoration_changed = next.is_some();
decoration_runs.extend(next);
let font_id = self.resolve_font(&run.font);
if let Some(font_run) = font_runs.last_mut()
@@ -864,25 +868,15 @@ impl WindowTextSystem {
if let Some(first_line) = split_lines.next()
&& let Some(second_line) = split_lines.next()
{
let mut emit =
|s: &str, start| process_line(SharedString::new(s), start, start + s.len());
let mut line_start = 0;
process_line(
SharedString::new(first_line),
line_start,
line_start + first_line.len(),
);
emit(first_line, line_start);
line_start += first_line.len() + '\n'.len_utf8();
process_line(
SharedString::new(second_line),
line_start,
line_start + second_line.len(),
);
emit(second_line, line_start);
for line_text in split_lines {
line_start += line_text.len() + '\n'.len_utf8();
process_line(
SharedString::new(line_text),
line_start,
line_start + line_text.len(),
);
emit(line_text, line_start);
}
} else {
let end = text.len();
@@ -925,27 +919,21 @@ impl WindowTextSystem {
let mut last_run = None::<&TextRun>;
let mut font_runs = self.font_runs_buffer.take();
font_runs.clear();
for run in runs.iter() {
let decoration_changed = if let Some(last_run) = last_run
&& last_run.color == run.color
&& last_run.underline == run.underline
&& last_run.strikethrough == run.strikethrough
// we do not consider differing background color relevant, as it does not affect glyphs
// && last_run.background_color == run.background_color
{
false
} else {
for run in runs {
let same = last_run.is_some_and(|l| {
l.color == run.color
&& l.underline == run.underline
&& l.strikethrough == run.strikethrough
});
if !same {
last_run = Some(run);
true
};
}
let font_id = self.resolve_font(&run.font);
if let Some(font_run) = font_runs.last_mut()
&& font_id == font_run.font_id
&& !decoration_changed
if let Some(fr) = font_runs.last_mut()
&& font_id == fr.font_id
&& same
{
font_run.len += run.len;
fr.len += run.len;
} else {
font_runs.push(FontRun {
len: run.len,
@@ -953,24 +941,19 @@ impl WindowTextSystem {
});
}
}
font_runs
}
/// Returns the shaped layout width of for the given character, in the given font and size.
pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
let mut buffer = [0; 4];
let buffer: &_ = ch.encode_utf8(&mut buffer);
let mut buf = [0; 4];
let s = ch.encode_utf8(&mut buf);
let runs = [FontRun {
len: s.len(),
font_id,
}];
self.line_layout_cache
.layout_line(
buffer,
font_size,
&[FontRun {
len: buffer.len(),
font_id,
}],
None,
)
.layout_line(s, font_size, &runs, None)
.width
}
}
@@ -989,15 +972,17 @@ pub struct LineWrapperHandle {
impl Drop for LineWrapperHandle {
fn drop(&mut self) {
let mut state = self.text_system.wrapper_pool.lock();
let wrapper = self.wrapper.take().unwrap();
state
.get_mut(&FontIdWithSize {
font_id: wrapper.font_id,
font_size: wrapper.font_size,
})
let w = self.wrapper.take().unwrap();
let key = FontIdWithSize {
font_id: w.font_id,
font_size: w.font_size,
};
self.text_system
.wrapper_pool
.lock()
.get_mut(&key)
.unwrap()
.push(wrapper.into_char_widths());
.push(w.into_char_widths());
}
}