diff --git a/packages/frontend/desktop/src/views_extra/mod.rs b/packages/frontend/desktop/src/views_extra/mod.rs index ca5a973c2a..a791944f96 100644 --- a/packages/frontend/desktop/src/views_extra/mod.rs +++ b/packages/frontend/desktop/src/views_extra/mod.rs @@ -165,8 +165,12 @@ fn display_time(ms: Option) -> String { ) } +/// Dot color of a tag that has no color yet, such as a tag that a peer added +/// before its definition arrived. The inspector uses the same color. +const UNHYDRATED_TAG_FALLBACK_RGB: u32 = 0x64748b; + fn tag_chip(tag: &str, color: Option, palette: DesktopPalette) -> Div { - let dot = color.map_or(palette.accent, |rgb| ui::rgb(rgb & 0x00ff_ffff).into()); + let dot = ui::rgb(color.unwrap_or(UNHYDRATED_TAG_FALLBACK_RGB) & 0x00ff_ffff); max_width(div(), ui::relative(1.0)) .flex() .items_center() diff --git a/packages/frontend/desktop/src/views_extra/tests.rs b/packages/frontend/desktop/src/views_extra/tests.rs index 962b36566e..c185d6af08 100644 --- a/packages/frontend/desktop/src/views_extra/tests.rs +++ b/packages/frontend/desktop/src/views_extra/tests.rs @@ -8,6 +8,7 @@ use ui::{ use ui_tokens::ThemeMode; use super::{ + UNHYDRATED_TAG_FALLBACK_RGB, outline_rail::HIDDEN_MAX_PANE_WIDTH, scroll::{DocRowKey, RowGeometry, RowLayout, RowStyle}, }; @@ -779,3 +780,40 @@ fn outline_rail_keeps_first_visible_heading_when_the_list_shrinks_and_grows() { assert_eq!(first_visible_heading(), shortened); assert!(app.contains(&format!("{prefix}{}", ids[40]))); } + +// The line ceiling counts this file as production code. This block is test code only. +#[cfg(test)] +mod peer_tag_colors { + use image::GenericImageView; + + use super::*; + + #[test] + fn explorer_list_and_grid_draw_unhydrated_peer_tags_in_the_inspector_fallback_color() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let views = state.store.views(); + let known = views.tag("architecture").unwrap(); + let known = known.color(crate::theme_tokens_for(ThemeMode::Light)); + assert!(views.tag("peer-new").is_none()); + assert!(!state.store.tag_colors.contains_key("peer-new")); + let doc = state.store.docs.get_mut("doc-sync").unwrap(); + doc.meta.tags = vec!["architecture".into(), "peer-new".into()]; + state.store.touch_meta(); + state.navigate_active_pane(DesktopRoute::AllDocs); + let app = Shell::with_state(1280, state); + for grid in [false, true] { + if grid { + app.click("desktop.explorer.grid"); + } + let area = app.bounds("desktop.list.doc.doc-sync"); + let frame = app.update(|_, window, _| window.render_to_image().unwrap()); + let (x, y) = (area.x as u32, area.y as u32); + let row = frame.view(x, y, area.width as u32, area.height as u32); + for rgb in [known, UNHYDRATED_TAG_FALLBACK_RGB] { + let [_, r, g, b] = rgb.to_be_bytes(); + let dot = row.pixels().any(|(_, _, pixel)| pixel.0[..3] == [r, g, b]); + assert!(dot, "grid {grid}: no tag dot of #{rgb:06x}"); + } + } + } +} diff --git a/packages/frontend/desktop/src/workbench/topbar/tabs.rs b/packages/frontend/desktop/src/workbench/topbar/tabs.rs index 7795eccf6b..8e49dd209d 100644 --- a/packages/frontend/desktop/src/workbench/topbar/tabs.rs +++ b/packages/frontend/desktop/src/workbench/topbar/tabs.rs @@ -1,10 +1,15 @@ +use std::ops::Range; + +use blocksuite_editor::scroll::{ScrollAxis, dominant_axis_delta, wheel_delta}; use ui::{ - Context, CursorStyle, DispatchPhase, InteractiveElement, IntoElement, MouseButton, - MouseMoveEvent, MouseUpEvent, ParentElement, Styled, canvas, div, px, + App, Context, CursorStyle, DispatchPhase, ElementId, Entity, InteractiveElement, IntoElement, + MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement, RenderOnce, SharedString, Styled, + ViewElement, Window, canvas, div, px, }; use crate::{ - CHEVRON_LEFT_SVG, CHEVRON_RIGHT_SVG, DesktopFlexExt, PLUS_ICON_SVG, split_view::DocViewMode, + CHEVRON_LEFT_SVG, CHEVRON_RIGHT_SVG, DesktopFlexExt, PLUS_ICON_SVG, + split_view::{DocViewMode, PaneId}, }; use super::{ @@ -66,26 +71,181 @@ pub(in crate::workbench) fn render_app_tabs( }), )); } - let can_close = pane.tabs.len() > 1; - let mut labels = div() - .flex() - .items_center() - .gap(px(4.0)) - .min_w_0() - .overflow_hidden(); - for (idx, tab) in pane.tabs.iter().enumerate() { - let mut label = div() - .flex() - .items_center() - .min_w_0() - .w(px(200.0)) - .h(px(26.0)) - .rounded(px(4.0)) - .bg(if idx == pane.active_tab { - palette.bg_elevated - } else { - palette.bg_pill + strip + .child(ViewElement::new(AppTabLabels { + shell: cx.entity(), + pane: pane.id, + palette, + })) + .child(icon_button( + "desktop.app_tabs.new", + PLUS_ICON_SVG, + false, + palette, + cx.listener(|shell, _, window, cx| { + shell.sync_editors(cx); + shell.state.open_app_tab(DocViewMode::Page); + window.focus(&shell.focus_handle, cx); + cx.notify(); + }), + )) +} + +const TAB_WIDTH: f32 = 200.0; +const TAB_GAP: f32 = 4.0; +const TAB_STRIDE: f32 = TAB_WIDTH + TAB_GAP; +const TAB_OVERSCAN: usize = 2; + +/// Horizontal scroll state of the app tab strip of one pane. +#[derive(Default)] +struct TabStripScroll { + scroll_x: f32, + /// Width of the tab area when the last paint showed it narrower than its tabs. + /// `None` when the tabs fitted, or before the first paint. + available: Option, + /// Content width at the last paint. + painted_content: Option, + /// Active tab that the strip last scrolled into view. Closing another tab + /// keeps the scroll position. + revealed: Option, +} + +fn content_width(count: usize) -> f32 { + count as f32 * TAB_WIDTH + count.saturating_sub(1) as f32 * TAB_GAP +} + +/// Clamps `scroll_x` to the content and, for `reveal`, moves the least distance +/// that shows that whole tab in `viewport`. +fn clamp_scroll(scroll_x: f32, count: usize, viewport: f32, reveal: Option) -> f32 { + let mut scroll_x = scroll_x; + if let Some(index) = reveal { + let start = index as f32 * TAB_STRIDE; + if start < scroll_x { + scroll_x = start; + } else if start + TAB_WIDTH > scroll_x + viewport { + scroll_x = start + TAB_WIDTH - viewport; + } + } + scroll_x.clamp(0.0, (content_width(count) - viewport).max(0.0)) +} + +/// Tabs that intersect `[scroll_x, scroll_x + viewport]`, with `TAB_OVERSCAN` tabs on each side. +fn visible_tabs(count: usize, scroll_x: f32, viewport: f32) -> Range { + if count == 0 || viewport <= 0.0 { + return 0..0; + } + let first = (scroll_x / TAB_STRIDE).floor() as usize; + let end = ((scroll_x + viewport) / TAB_STRIDE).ceil() as usize; + first.saturating_sub(TAB_OVERSCAN).min(count)..end.saturating_add(TAB_OVERSCAN).min(count) +} + +/// The app tabs of the first pane. Only the tabs in the visible range and the +/// overscan mount; a wheel or a trackpad scrolls the strip sideways. +struct AppTabLabels { + shell: Entity, + pane: PaneId, + palette: DesktopPalette, +} + +impl RenderOnce for AppTabLabels { + fn render(self, window: &mut Window, app: &mut App) -> impl IntoElement { + let state = window.use_keyed_state( + ElementId::NamedInteger( + SharedString::new_static("desktop.app_tabs.scroll"), + self.pane, + ), + app, + |_, _| TabStripScroll::default(), + ); + let pane = &self.shell.read(app).state.split.panes[0]; + let count = pane.tabs.len(); + let active = pane.active_tab; + let revealed = pane.active_tab().id; + let content = content_width(count); + let stored = state.read(app); + let available = stored.available; + // The tab area is as wide as its tabs until it reaches the space beside the + // buttons. When the last paint does not tell that width, the window width + // bounds it from above. + let (viewport, exact) = match (available, stored.painted_content) { + (Some(available), _) => (available.min(content), true), + (None, Some(painted)) if content <= painted => (content, true), + _ => (content.min(window.viewport_size().width.into()), false), + }; + let reveal = (stored.revealed != Some(revealed)).then_some(active); + let scroll_x = clamp_scroll(stored.scroll_x, count, viewport, reveal); + if scroll_x != stored.scroll_x || (reveal.is_some() && exact) { + state.update(app, |stored, _| { + stored.scroll_x = scroll_x; + if exact { + stored.revealed = Some(revealed); + } }); + } + let range = visible_tabs(count, scroll_x, viewport); + let palette = self.palette; + let labels = self.shell.update(app, |shell, cx| { + render_tab_range(shell, range, scroll_x, palette, cx) + }); + + let measure_state = state.clone(); + let measure = canvas( + move |bounds, window, app| { + let width = f32::from(bounds.size.width); + let painted = (width + 0.5 < content).then_some(width); + if painted != available || !exact { + window.defer(app, move |_, app| { + measure_state.update(app, |stored, cx| { + stored.painted_content = Some(content); + if stored.available != painted { + stored.available = painted; + cx.notify(); + } + }); + }); + } + }, + |_, (), _, _| {}, + ) + .absolute() + .inset_0(); + + div() + .id("desktop.app_tabs.labels") + .relative() + .w(px(content)) + .h(px(26.0)) + .min_w_0() + .overflow_hidden() + .on_scroll(move |event, _, app| { + state.update(app, |stored, cx| { + let (dx, dy) = wheel_delta(event, 0.0); + let mut axis = ScrollAxis::new(stored.scroll_x, content - viewport); + if axis.apply(dominant_axis_delta(dx, dy)) { + stored.scroll_x = axis.offset; + cx.stop_propagation(); + cx.notify(); + } + }); + }) + .children(labels) + .child(measure) + } +} + +fn render_tab_range( + shell: &DesktopShellView, + range: Range, + scroll_x: f32, + palette: DesktopPalette, + cx: &mut Context, +) -> Vec { + let pane = &shell.state.split.panes[0]; + let can_close = pane.tabs.len() > 1; + let pane_id = pane.id; + let mut labels = Vec::with_capacity(range.len()); + for (idx, tab) in pane.tabs[range.clone()].iter().enumerate() { + let idx = range.start + idx; let tab_id = tab.id; let title = std::iter::once(&tab.route) .chain( @@ -99,54 +259,56 @@ pub(in crate::workbench) fn render_app_tabs( .map(|route| shell.state.route_title(route)) .collect::>() .join(" | "); - let pane_id = pane.id; - label = label.child( - button( - format!("desktop.app_tabs.tab.{idx}"), - false, - palette, - cx.listener(move |shell, _, window, cx| { - shell.sync_editors(cx); - if let Some(pane) = shell - .state - .split - .panes - .iter_mut() - .find(|pane| pane.id == pane_id) - && let Some(index) = pane.tabs.iter().position(|tab| tab.id == tab_id) - { - pane.select_tab(index); - window.focus(&shell.focus_handle, cx); - cx.notify(); - } - }), - ) - .flex_1() - .flex_shrink(1.0) + let mut label = div() + .absolute() + .top(px(0.0)) + .left(px(idx as f32 * TAB_STRIDE - scroll_x)) + .flex() + .items_center() + .w(px(TAB_WIDTH)) .h(px(26.0)) - .min_w_0() - .px(px(8.0)) - .text_size(px(13.0)) - .text_color(palette.text_primary) - .child(div().w_full().truncate().child(title)), - ); + .rounded(px(4.0)) + .bg(if idx == pane.active_tab { + palette.bg_elevated + } else { + palette.bg_pill + }) + .child( + button( + format!("desktop.app_tabs.tab.{idx}"), + false, + palette, + cx.listener(move |shell, _, window, cx| { + shell.sync_editors(cx); + if let Some(pane) = shell + .state + .split + .panes + .iter_mut() + .find(|pane| pane.id == pane_id) + && let Some(index) = pane.tabs.iter().position(|tab| tab.id == tab_id) + { + pane.select_tab(index); + window.focus(&shell.focus_handle, cx); + cx.notify(); + } + }), + ) + .flex_1() + .flex_shrink(1.0) + .h(px(26.0)) + .min_w_0() + .px(px(8.0)) + .text_size(px(13.0)) + .text_color(palette.text_primary) + .child(div().w_full().truncate().child(title)), + ); if can_close { label = label.child(close_tab_button(0, idx, palette, cx)); } - labels = labels.child(label); + labels.push(label.into_any_element()); } - strip.child(labels).child(icon_button( - "desktop.app_tabs.new", - PLUS_ICON_SVG, - false, - palette, - cx.listener(|shell, _, window, cx| { - shell.sync_editors(cx); - shell.state.open_app_tab(DocViewMode::Page); - window.focus(&shell.focus_handle, cx); - cx.notify(); - }), - )) + labels } #[derive(Clone, Copy)] @@ -279,3 +441,253 @@ pub(in crate::workbench) fn render_split_dividers( } elements } + +#[cfg(test)] +mod tests { + use ui::{ + AppContext, Application, ApplicationHandle, Bounds, HeadlessPlatform, HeadlessWindow, + PlatformInput, ScrollDelta, ScrollEvent, WindowBounds, WindowHandle, WindowOptions, point, + size, + }; + use ui_tokens::ThemeMode; + + use super::*; + use crate::{DesktopAppState, register_desktop_fonts}; + + const TABS: usize = 1_001; + + #[test] + fn tab_strip_geometry_clamps_reveals_and_bounds_the_mounted_range() { + assert_eq!(content_width(0), 0.0); + assert_eq!(content_width(1), 200.0); + assert_eq!(content_width(3), 608.0); + for (scroll_x, count, viewport, reveal, expected) in [ + (0.0, 3, 1000.0, None, 0.0), + (500.0, 3, 1000.0, None, 0.0), + (-20.0, 10, 500.0, None, 0.0), + (9_000.0, 10, 500.0, None, 1536.0), + (0.0, 10, 500.0, Some(9), 1536.0), + (0.0, 10, 500.0, Some(2), 108.0), + (1000.0, 10, 500.0, Some(2), 408.0), + (300.0, 10, 500.0, Some(2), 300.0), + ] { + assert_eq!( + clamp_scroll(scroll_x, count, viewport, reveal), + expected, + "{scroll_x} {count} {viewport} {reveal:?}" + ); + } + for (count, scroll_x, viewport, expected) in [ + (0, 0.0, 800.0, 0..0), + (5, 0.0, 0.0, 0..0), + (3, 0.0, 800.0, 0..3), + (TABS, 0.0, 1000.0, 0..7), + (TABS, 204.0 * 500.0 + 10.0, 1000.0, 498..507), + (TABS, content_width(TABS) - 1000.0, 1000.0, 994..TABS), + ] { + assert_eq!( + visible_tabs(count, scroll_x, viewport), + expected, + "{count} {scroll_x} {viewport}" + ); + } + } + + struct Shell { + app: ApplicationHandle, + handle: WindowHandle, + window: HeadlessWindow, + } + + impl Shell { + fn with_tabs(count: usize) -> Self { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + while state.split.panes[0].tabs.len() < count { + state.open_app_tab(DocViewMode::Page); + } + state.split.panes[0].select_tab(0); + let platform = HeadlessPlatform::new(1280, 800, 1.0); + let app = Application::with_platform(platform.clone()).run_embedded(|_| {}); + let handle = app.update(|cx| { + register_desktop_fonts(cx).expect("desktop fonts"); + cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::new( + point(px(0.0), px(0.0)), + size(px(1280.0), px(800.0)), + ))), + ..WindowOptions::default() + }, + |_, cx| cx.new(|cx| DesktopShellView::new(state, cx)), + ) + .expect("desktop window") + }); + let window = platform + .windows() + .into_iter() + .next() + .expect("headless window"); + let shell = Self { + app, + handle, + window, + }; + shell.frame(); + shell + } + + fn frame(&self) { + // The second frame shows the visible width that the first frame measured. + self.window.request_frame(); + self.window.request_frame(); + } + + fn update( + &self, + f: impl FnOnce(&mut DesktopShellView, &mut Window, &mut Context) -> T, + ) -> T { + self.app + .update(|cx| self.handle.update(cx, f).expect("desktop view")) + } + + fn bounds(&self, id: &str) -> Option { + self.update(|_, window, _| { + window + .frame_snapshot() + .elements + .get(id) + .map(|element| element.bounds) + }) + } + + fn mounted_tabs(&self) -> Vec { + let mut tabs: Vec = self.update(|_, window, _| { + window + .frame_snapshot() + .elements + .keys() + .filter_map(|id| id.strip_prefix("desktop.app_tabs.tab.")?.parse().ok()) + .collect() + }); + tabs.sort_unstable(); + tabs + } + + fn click(&self, id: &str) { + let b = self.bounds(id).expect(id); + self.window + .simulate_click(point(px(b.x + b.width / 2.0), px(b.y + b.height / 2.0))); + self.frame(); + } + + fn wheel(&self, dx: f32, dy: f32) { + // Overscan tabs lie under the buttons beside the visible area: aim inside its end. + let b = self.bounds("desktop.app_tabs").expect("tab strip"); + let x = self.strip_end() - TAB_WIDTH / 2.0; + self.window + .dispatch_input(PlatformInput::Scroll(ScrollEvent { + position: point(px(x), px(b.y + b.height / 2.0)), + delta: ScrollDelta::Pixels(point(px(dx), px(dy))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + self.frame(); + } + + fn active(&self) -> (usize, usize) { + self.update(|shell, _, _| { + let pane = &shell.state.split.panes[0]; + (pane.active_tab, pane.tabs.len()) + }) + } + + /// Right edge of the visible tab area: the new tab button follows it after one gap. + fn strip_end(&self) -> f32 { + self.bounds("desktop.app_tabs.new").expect("new tab").x - TAB_GAP + } + } + + #[test] + fn thousand_tabs_mount_a_bounded_range_scroll_close_by_pane_index_and_reveal_the_active_tab() { + let shell = Shell::with_tabs(TABS); + let first = shell.bounds("desktop.app_tabs.tab.0").expect("first tab"); + let start = first.x; + assert!( + shell.mounted_tabs().len() <= 16, + "{:?}", + shell.mounted_tabs() + ); + assert_eq!(shell.mounted_tabs()[0], 0); + + // A vertical wheel and a horizontal trackpad delta both scroll the strip. + for (dx, dy) in [(0.0, -1_000_000.0), (1_000_000.0, 0.0), (-1_000_000.0, 0.0)] { + shell.wheel(dx, dy); + let mounted = shell.mounted_tabs(); + assert!(mounted.len() <= 16, "{mounted:?}"); + let last = mounted.last() == Some(&(TABS - 1)); + assert_eq!(last, dx <= 0.0, "{dx} {dy}: {mounted:?}"); + assert_eq!(mounted[0] == 0, dx > 0.0, "{dx} {dy}: {mounted:?}"); + } + let last = shell + .bounds(&format!("desktop.app_tabs.tab.{}", TABS - 1)) + .expect("last tab"); + assert!(last.x >= start); + assert_eq!(last.x + last.width + 24.0, shell.strip_end()); + + // A mounted tab far from the start keeps its index in the pane: its close + // button removes that tab and no other. + let ids = |shell: &Shell| -> Vec { + shell.update(|shell, _, _| { + shell.state.split.panes[0] + .tabs + .iter() + .map(|tab| tab.id) + .collect() + }) + }; + let mut expected = ids(&shell); + let closed = expected.remove(TABS - 3); + shell.click(&format!("desktop.pane.0.tab.{}.close", TABS - 3)); + assert_eq!(ids(&shell), expected); + assert!(!ids(&shell).contains(&closed)); + assert_eq!(shell.active(), (0, TABS - 1)); + + shell.click(&format!("desktop.app_tabs.tab.{}", TABS - 2)); + assert_eq!(shell.active(), (TABS - 2, TABS - 1)); + + // Closing the last tab clamps the scroll: no empty space after the new last tab. + shell.click(&format!("desktop.pane.0.tab.{}.close", TABS - 2)); + assert_eq!(shell.active(), (TABS - 3, TABS - 2)); + let end = shell + .bounds(&format!("desktop.app_tabs.tab.{}", TABS - 3)) + .expect("new last tab"); + assert_eq!(end.x + end.width + 24.0, shell.strip_end()); + + // Selecting a tab outside the visible range scrolls it into view. + shell.update(|shell, _, cx| { + shell.state.split.panes[0].select_tab(0); + cx.notify(); + }); + shell.frame(); + assert_eq!(shell.active(), (0, TABS - 2)); + assert_eq!( + shell.bounds("desktop.app_tabs.tab.0").expect("first tab").x, + start + ); + shell.update(|shell, _, cx| { + shell.state.split.panes[0].select_tab(500); + cx.notify(); + }); + shell.frame(); + let middle = shell + .bounds("desktop.app_tabs.tab.500") + .expect("middle tab"); + assert!(middle.x >= start && middle.x + middle.width + 24.0 <= shell.strip_end()); + assert!( + shell.mounted_tabs().len() <= 16, + "{:?}", + shell.mounted_tabs() + ); + } +}