feat: add page surfaces and collapsible sidebar

This commit is contained in:
2026-11-10 16:18:47 +08:00
parent e0eff7755f
commit 82f9256a84
35 changed files with 1480 additions and 1751 deletions
+5 -2
View File
@@ -23,7 +23,8 @@
| [native_chrome](shell/native_chrome.rs) | macOS 原生按钮对齐和工具栏双击系统动作 |
| [sources](shell/sources.rs) | 默认断开的云文件 provider 接口及工作区 |
| [system_ui](shell/system_ui/mod.rs) | 独立宿主管理控件、交互和主题 |
| [tabs](shell/tabs.rs) | 共享标签绘制/命中、密集布局、滚动、拖放及动画 |
| [tabs](shell/tabs.rs) | 页面注册表的不可变 ID、标题和当前选择投影 |
| [sidebar](shell/sidebar.rs) | 页面/开发工具入口、收起状态与最小宿主控制区 |
## runtime
@@ -60,7 +61,8 @@
| [geometry](render/geometry.rs) | 点和矩形值 |
| [layout](render/layout.rs) | 原生测量、排列、出现几何及预算 |
| [native_visual](render/native_visual.rs) | 托管原生视觉协议、值转换和签名检查 |
| [scene](render/scene.rs) | 页面、标签、插入标记和开发工具画面合成 |
| [scene](render/scene.rs) | 页面视角、可见裁剪、侧栏和开发工具画面合成 |
| [page](render/page.rs) | 四种页面空间、约束、平移缩放及正逆坐标变换 |
| [scroll](render/scroll.rs) | 逐 Mount 偏移、嵌套滚动和剪裁投影 |
| [software_renderer](render/software_renderer.rs) | 软件光栅化、抗锯齿覆盖和嵌套剪裁 |
| [source_hit](render/source_hit.rs) | 源/原生命中协议与匹配目标 |
@@ -79,6 +81,7 @@
- HTTP 路由:`runtime/api.rs`;worker:`runtime/api/worker.rs`;在线指南:`runtime/api/guide.rs`。
- Bridge 安装:`bridge/ui_bridge/bootstrap.rs`;Block 调用:`calls.rs`;签名:`signatures.rs`;不可变树:`tree.rs`。
- 默认页:`bridge/ui_bridge/start_page.endor`;Console/Sources/Network/Settings:`shell/developer_tools/`。
- 页面模式与宿主边界见 [页面空间说明](../docs/page-surfaces.md);相机输入:`bridge/ui_bridge/page_input.rs`。
- 现有 API 和宿主测试:`runtime/api/tests.rs`、`runtime/endor_host/tests.rs`;其他模块中也保留原单元测试。
VM 和托管根只由执行 worker 操作。原生窗口收到已发布值,不收到 ObjectRef。完整 PUT 成功才接替活跃程序;Console 保留实际 VM;失败和清理语义见架构文档。
+29 -19
View File
@@ -2,6 +2,7 @@
mod bootstrap;
mod calls;
mod developer_pages;
mod page_input;
mod signatures;
mod tree;
@@ -658,6 +659,7 @@ pub enum LayoutProgress {
}
struct LayoutContext {
surface: crate::page::Surface,
root: Arc<UiNode>,
tabs: Vec<crate::tabs::Tab>,
full_viewport: Option<crate::layout::Size>,
@@ -1189,13 +1191,16 @@ impl UiBridge {
vm.release_value(page)?;
return Ok(());
}
if matches!(input.kind.as_str(), "page-pan" | "page-zoom") {
return self.dispatch_page_view(vm, input);
}
if matches!(
input.kind.as_str(),
"tab-activate" | "tab-close" | "tab-detach" | "tab-drop"
) {
return self.dispatch_tab(vm, input);
}
let (weak, desktop, candidates, viewport) = {
let (weak, desktop, candidates, viewport, surface) = {
let state = self
.session
.lock()
@@ -1211,13 +1216,8 @@ impl UiBridge {
.ok_or_else(|| anyhow::anyhow!("Mount is no longer active"))?,
state.desktop,
state.mounts.ordered(),
state.layout.viewport.map(|size| crate::layout::Size {
width: (size.width - crate::tabs::RAIL - crate::tabs::INSET).max(0.0),
height: (size.height
- crate::tabs::INSET
- crate::tabs::height(&state.last_tabs))
.max(0.0),
}),
state.layout.viewport,
state.surface.clone(),
)
};
if input.kind == "scroll" {
@@ -1231,8 +1231,7 @@ impl UiBridge {
.ok_or_else(|| anyhow::anyhow!("scroll has no pointer"))?;
if !data.mounted
|| data.version != input.layout_version
|| viewport
.is_some_and(|size| point[0] >= size.width || point[1] >= size.height)
|| !surface.contains(point, viewport)
|| !data
.geometry
.contains(crate::geometry::Point::new(point[0], point[1]))
@@ -1265,11 +1264,10 @@ impl UiBridge {
return result;
}
let mount = if let (Some(press), Some(release)) = (input.press_point, input.point) {
if viewport.is_some_and(|size| {
[press, release]
.iter()
.any(|point| point[0] >= size.width || point[1] >= size.height)
}) {
if [press, release]
.iter()
.any(|point| !surface.contains(*point, viewport))
{
return Ok(());
}
let Some(mount) = crate::source_hit::resolve(vm, desktop, candidates, press, release)?
@@ -1477,6 +1475,7 @@ impl UiBridge {
state.force_frame = false;
state.last_snapshot = snapshot;
state.last_tabs = frame.tabs.clone();
state.surface = frame.surface.clone();
state.published_version = frame.layout_version;
// Hooks may call Page/container APIs; never hold the session mutex
// across user code. Publish only after the refresh loop settles.
@@ -1649,10 +1648,8 @@ impl UiBridge {
project_tabs(vm, &mut state)?
};
let full_viewport = layout.viewport;
if let Some(size) = &mut layout.viewport {
size.width = (size.width - crate::tabs::RAIL - crate::tabs::INSET).max(0.0);
size.height = (size.height - crate::tabs::height(&tabs) - crate::tabs::INSET).max(0.0);
}
let surface = root.surface.clone().unwrap_or_default();
layout.page_mode = root.surface.as_ref().map(|surface| surface.mode);
{
let state = self
.session
@@ -1688,6 +1685,7 @@ impl UiBridge {
(hooks, state.mounts.ordered(), checkpoint)
};
let context = LayoutContext {
surface,
root: root.clone(),
tabs,
full_viewport,
@@ -1736,6 +1734,7 @@ impl UiBridge {
fn discard_layout_context(&self, vm: &mut Vm, context: LayoutContext) -> Result<()> {
let LayoutContext {
surface: _,
desktop,
window,
hooks,
@@ -1824,6 +1823,7 @@ impl UiBridge {
draft: crate::source_layout::Draft,
) -> Result<crate::document::Frame> {
let LayoutContext {
mut surface,
root,
tabs,
full_viewport,
@@ -1851,6 +1851,16 @@ impl UiBridge {
// after either layout path has produced the final page geometry.
frame.tabs = tabs;
frame.window = window;
if let Some(root) = frame.mounts.first() {
surface.extent = crate::layout::Size {
width: root.width,
height: root.height,
};
}
if let Some(viewport) = full_viewport {
surface.clamp(viewport);
}
frame.surface = surface;
// Capture versions before lifecycle hooks can change a dependency.
let desktops = self
.session
+66
View File
@@ -0,0 +1,66 @@
//! Camera mutations run on the owning VM worker, just like other page input.
use super::*;
impl UiBridge {
pub(super) fn dispatch_page_view(
&self,
vm: &mut Vm,
input: &crate::events::Input,
) -> Result<()> {
let (page, mut surface, viewport) = {
let state = self
.session
.lock()
.map_err(|_| anyhow::anyhow!("UI session poisoned"))?;
anyhow::ensure!(
state.published_version == input.layout_version,
"obsolete page view"
);
(
state
.active
.ok_or_else(|| anyhow::anyhow!("no active Page"))?,
state.surface.clone(),
state.layout.viewport,
)
};
let delta = input
.delta
.ok_or_else(|| anyhow::anyhow!("page view requires delta"))?;
if input.kind == "page-zoom" {
anyhow::ensure!(
surface.mode == crate::page::Mode::Canvas,
"zoom requires canvas mode"
);
let pointer = input
.point
.ok_or_else(|| anyhow::anyhow!("zoom requires anchor"))?;
let pointer = crate::geometry::Point::new(pointer[0], pointer[1]);
anyhow::ensure!(
pointer.x >= 0.0
&& pointer.y >= 0.0
&& viewport.is_none_or(|v| pointer.x < v.width && pointer.y < v.height),
"zoom anchor is outside viewport"
);
let world = surface.to_world(pointer);
surface.zoom = (surface.zoom * delta[0]).clamp(0.1, 4.0);
surface.pan = crate::geometry::Point::new(
world.x - pointer.x / surface.zoom,
world.y - pointer.y / surface.zoom,
);
} else {
surface.pan.x += delta[0] / surface.zoom;
surface.pan.y += delta[1] / surface.zoom;
}
if let Some(viewport) = viewport {
surface.clamp(viewport);
}
let limit = MAX_DIMENSION as f32;
surface.pan.x = surface.pan.x.clamp(-limit, limit);
surface.pan.y = surface.pan.y.clamp(-limit, limit);
vm.set_attr(page, "panX", crate::native_visual::value(surface.pan.x))?;
vm.set_attr(page, "panY", crate::native_visual::value(surface.pan.y))?;
vm.set_attr(page, "zoom", crate::native_visual::value(surface.zoom))?;
Ok(())
}
}
+88 -57
View File
@@ -1,39 +1,63 @@
// Tessera's start page is an ordinary Endor Page, including its layout and actions.
// This module has its own globals; creating tabs does not replace user bindings.
class StartPage: Page {
function measure(self: StartPage, mount: Mount, constraints: Constraints): MeasureResult {
return MeasureResult(constraints.maxWidth, constraints.maxHeight)
// The page, cards and actions belong to Endor. The host only owns its sidebar.
class Note: Column {
tint: String
function measure(self: Note, mount: Mount, constraints: Constraints): MeasureResult {
measured = Column.measure(self, mount, constraints)
return MeasureResult(224, measured.height)
}
function paint(self: Note, mount: Mount, geometry: Bounds): DisplayList {
fill = PaintCommand()
fill.kind = "roundedRect"
fill.x = geometry.x
fill.y = geometry.y
fill.width = geometry.width
fill.height = geometry.height
fill.radius = 14
fill.color = self.tint
return DisplayList(ObjectList(fill))
}
}
class StartRow: Row {
function measure(self: StartRow, mount: Mount, constraints: Constraints): MeasureResult {
measured = Row.measure(self, mount, constraints)
return MeasureResult(constraints.maxWidth, measured.height)
}
}
// Quiet action rows retain native hit targets and keyboard focus without card chrome.
class StartButton: Button {
function measure(self: StartButton, mount: Mount, constraints: Constraints): MeasureResult {
return MeasureResult(360, 40)
}
function paint(self: StartButton, mount: Mount, geometry: Bounds): DisplayList {
class QuietButton: Button {
function paint(self: QuietButton, mount: Mount, geometry: Bounds): DisplayList {
return DisplayList(ObjectList())
}
}
class StartLine: Row {
function measure(self: StartLine, mount: Mount, constraints: Constraints): MeasureResult {
measured = Row.measure(self, mount, constraints)
return MeasureResult(360, measured.height)
}
}
class StartActions {
home: Page
function blank(self: StartActions, event: Event): Unit {
page = Page()
page.title = "未命名页面"
back = Button("返回开始页")
page.title = "窗口页面"
page.mode = "window"
back = Button("返回画布")
back.onClick(self.home.activate)
page.render(Column(32, 16, TextBlock("未命名页面", 2), TextBlock("一个新的 Page 对象,已加入当前窗口。"), TextBlock("用 Endor 的 page.render(...) 组织内容。"), back))
page.render(Column(56, 20, TextBlock("恰好一个窗口", 3), TextBlock("页面跟随可用区域调整。内容和工具栏由 Endor 自己组织。"), back))
}
function vertical(self: StartActions, event: Event): Unit {
page = Page()
page.title = "纵向页面"
page.mode = "vertical"
page.padding = 48
page.gap = 28
page.render(Column(0, 12, TextBlock("向下,继续生长", 3), TextBlock("宽度跟随窗口,高度随子组件增长。滚轮向下浏览。")))
page.append(Note(24, 16, TextBlock("01 / 收集想法", 2), RectBlock(176, 130, 10, "#E2EADB"), TextBlock("从一个小小的念头开始。"), "#F0F3E9"))
page.append(Note(24, 16, TextBlock("02 / 连接片段", 2), RectBlock(176, 130, 10, "#E6DBEF"), TextBlock("内容保留在同一条连续的页面里。"), "#F4EEF7"))
page.append(Note(24, 16, TextBlock("03 / 慢慢展开", 2), RectBlock(176, 130, 10, "#EDDCC5"), TextBlock("追加一个子组件,页面自然延伸。"), "#FAF2E7"))
page.append(Note(24, 16, TextBlock("04 / 留一点空白", 2), TextBlock("不必把所有想法都放在第一屏。"), "#EDF1F6"))
}
function horizontal(self: StartActions, event: Event): Unit {
page = Page()
page.title = "横向页面"
page.mode = "horizontal"
page.padding = 48
page.gap = 32
page.render(Note(24, 16, TextBlock("从左,走向右", 2), RectBlock(176, 180, 10, "#DDE8F1"), TextBlock("高度跟随窗口,宽度由子组件决定。"), "#EDF3F8"))
page.append(Note(24, 16, TextBlock("收集", 2), RectBlock(176, 210, 10, "#D7E5DA"), TextBlock("一张卡片,一个想法。"), "#EFF4EC"))
page.append(Note(24, 16, TextBlock("整理", 2), RectBlock(176, 170, 10, "#E5D9EB"), TextBlock("横向滚动,保留思考的顺序。"), "#F4EFF7"))
page.append(Note(24, 16, TextBlock("继续", 2), RectBlock(176, 230, 10, "#EFDFC7"), TextBlock("滚轮或 Shift + 滚轮浏览更多内容。"), "#FAF3E8"))
page.append(Note(24, 16, TextBlock("不止一屏", 2), TextBlock("右侧仍有空间。"), "#EEF1F5"))
}
function canvas(self: StartActions, event: Event): Unit {
page = newTab()
}
function counter(self: StartActions, event: Event): Unit {
count = ui.state(0)
@@ -41,40 +65,47 @@ class StartActions {
add.onClick(count.increment)
page = Page()
page.title = "共享对象"
page.render(Column(32, 16, TextBlock("一个对象,两个视图", 2), TextBlock("点击一次,两处展示同时更新。切换标签后,状态仍然保留。"), Row(0, 32, ui.textOf(count, "value", 3), ui.textOf(count, "value", 3)), add))
}
function compose(self: StartActions, event: Event): Unit {
label = TextBlock("对象可以被多处引用")
page = Page()
page.title = "组合页面"
page.render(Column(32, 20, TextBlock("把对象组合成界面", 2), TextBlock("Column 组织纵向内容,Row 组织横向内容。"), Row(0, 16, RectBlock(100, 64, 12, "#DCE8FF"), RectBlock(100, 64, 12, "#E3ECDC"), RectBlock(100, 64, 12, "#F3E4DB")), label, Row(0, 24, label, label)))
page.render(Column(48, 24, TextBlock("一个对象,两个视图", 2), Row(0, 32, ui.textOf(count, "value", 3), ui.textOf(count, "value", 3)), add))
}
}
function newTab(): Page {
page = StartPage()
page.title = "新标签页"
page = Page()
page.title = "自由画布"
page.mode = "canvas"
actions = StartActions(page)
blank = StartButton("+ 创建页面")
counter = StartButton("↗ 共享对象示例")
compose = StartButton("◇ 界面组合示例")
blank.on("click", actions.blank)
counter.on("click", actions.counter)
compose.on("click", actions.compose)
heading = StartLine(0, 0, TextBlock("Endor", 2, "#30343B"))
heading.mainAlign = "center"
subtitle = StartLine(0, 0, TextBlock("创建页面,或从一个示例开始。", 1, "#80858D"))
subtitle.mainAlign = "center"
newHint = StartLine(0, 0, TextBlock("新建标签页", 1, "#8A8F97"), TextBlock("⌘ T / Ctrl + T", 1, "#747B85"))
newHint.mainAlign = "space-between"
closeHint = StartLine(0, 0, TextBlock("关闭标签页", 1, "#8A8F97"), TextBlock("⌘ W / Ctrl + W", 1, "#747B85"))
closeHint.mainAlign = "space-between"
content = Column(0, 8,
heading, subtitle, Spacer(20),
blank, counter, compose, Spacer(20),
newHint, closeHint)
row = StartRow(24, 0, content)
row.mainAlign = "center"
page.mainAlign = "center"
page.render(row)
fixed = Button("窗口页面")
vertical = Button("纵向延伸")
horizontal = Button("横向延伸")
canvas = Button("新的画布")
shared = QuietButton("试试:一个对象,两个视图 ↗")
fixed.on("click", actions.blank)
vertical.on("click", actions.vertical)
horizontal.on("click", actions.horizontal)
canvas.on("click", actions.canvas)
shared.on("click", actions.counter)
hero = Column(0, 16, TextBlock("给想法,一点空间。", 3, "#303941"), TextBlock("页面可以是一扇窗口,也可以一直延伸。", 1, "#7D858C"), Spacer(8), Row(0, 10, fixed, vertical), Row(0, 10, horizontal, canvas), shared)
hero.x = 316
hero.y = 254
page.render(hero)
left = Note(24, 14, TextBlock("随手记下", 2), RectBlock(176, 100, 10, "#D5E4DA"), TextBlock("想法不必排成一条直线。"), "#EDF3E9")
left.x = 36
left.y = 92
page.append(left)
top = Note(24, 14, TextBlock("四种页面,同一个世界"), TextBlock("窗口 · 纵向 · 横向 · 自由画布", 1, "#7D858C"), "#EFF1F7")
top.x = 466
top.y = 58
page.append(top)
right = Note(24, 14, RectBlock(176, 138, 12, "#DDDAEA"), TextBlock("把片段放在一起", 2), TextBlock("位置属于组件,视角属于页面。"), "#F1EDF5")
right.x = 826
right.y = 190
page.append(right)
bottom = Note(24, 14, TextBlock("不止眼前这一屏", 2), TextBlock("触控板或滚轮平移\n空格拖动 / 鼠标中键拖动\n双指捏合 / ⌘ Ctrl + 滚轮缩放"), "#F7F0E5")
bottom.x = 104
bottom.y = 524
page.append(bottom)
end = Note(24, 14, TextBlock("继续向外探索", 2), RectBlock(176, 100, 10, "#CEDFE7"), TextBlock("画布上的对象仍是普通 Endor 组件。"), "#EAF1F5")
end.x = 716
end.y = 614
page.append(end)
return page
}
+11 -1
View File
@@ -3,6 +3,7 @@ use std::sync::Arc;
#[derive(Debug, Clone, PartialEq)]
pub struct UiNode {
pub surface: Option<crate::page::Surface>,
pub flex: f32,
pub flex_policy: crate::layout::FlexPolicy,
pub main_align: crate::layout::MainAlign,
@@ -17,6 +18,7 @@ impl UiNode {
pub fn children(&self) -> &[Arc<UiNode>] {
match &self.kind {
UiKind::Column { children, .. }
| UiKind::Canvas { children, .. }
| UiKind::Row { children, .. }
| UiKind::Button { children, .. }
| UiKind::Scroll { children, .. } => children,
@@ -29,7 +31,8 @@ impl UiNode {
}
pub fn shallow_eq(&self, other: &Self) -> bool {
if self.flex_policy != other.flex_policy
if self.surface != other.surface
|| self.flex_policy != other.flex_policy
|| self.flex != other.flex
|| self.main_align != other.main_align
|| self.block_id != other.block_id
@@ -48,6 +51,9 @@ impl UiNode {
.all(|(a, b)| Arc::ptr_eq(a, b))
};
match (&self.kind, &other.kind) {
(UiKind::Canvas { positions: a, .. }, UiKind::Canvas { positions: b, .. }) => {
a == b && same_children()
}
(
UiKind::Text {
value: a,
@@ -124,6 +130,10 @@ impl UiNode {
#[derive(Debug, Clone, PartialEq)]
pub enum UiKind {
Canvas {
positions: Vec<[f32; 2]>,
children: Vec<Arc<UiNode>>,
},
Button {
padding: f32,
gap: f32,
+5 -3
View File
@@ -11,15 +11,17 @@ pub(crate) use model::{
binding, block, document, mount, object_list, presentation, protocols, snapshot, window,
};
pub(crate) use render::{
display_list, geometry, layout, native_visual, scene, scroll, software_renderer, source_hit,
source_layout, source_paint, text,
display_list, geometry, layout, native_visual, page, scene, scroll, software_renderer,
source_hit, source_layout, source_paint, text,
};
pub(crate) use runtime::{
api, endor_host, endor_script, event_dispatch, events, io_tasks, tasks, vm_sequence,
};
#[cfg(target_os = "macos")]
pub(crate) use shell::native_chrome;
pub(crate) use shell::{activity, app, clipboard, developer_tools, sources, system_ui, tabs};
pub(crate) use shell::{
activity, app, clipboard, developer_tools, sidebar, sources, system_ui, tabs,
};
use std::sync::{Arc, RwLock};
+40
View File
@@ -121,6 +121,8 @@ pub struct Data {
pub flex_policy: crate::layout::FlexPolicy,
pub main_align: crate::layout::MainAlign,
pub scroll_axis: crate::scroll::Axis,
pub position: [f32; 2],
pub surface: crate::page::Surface,
pub next_slot: u64,
pub history: Vec<ObjectRef>,
pub history_index: usize,
@@ -150,6 +152,8 @@ impl Data {
flex_policy: crate::layout::FlexPolicy::default(),
main_align: crate::layout::MainAlign::Start,
scroll_axis: crate::scroll::Axis::Both,
position: [0.0, 0.0],
surface: crate::page::Surface::new(crate::page::Mode::Window),
next_slot,
history: vec![],
history_index: 0,
@@ -320,6 +324,8 @@ pub fn native_properties(data: &Data) -> Vec<(&'static str, Value)> {
Value::Number((value as f64).into())
}
let mut fields = vec![
("x", number(data.position[0])),
("y", number(data.position[1])),
("flex", number(data.flex)),
(
"flexBasis",
@@ -332,6 +338,12 @@ pub fn native_properties(data: &Data) -> Vec<(&'static str, Value)> {
("flexShrink", number(data.flex_policy.shrink)),
];
match &data.kind {
Kind::Page => fields.extend([
("mode", Value::Text(data.surface.mode.name().into())),
("panX", number(data.surface.pan.x)),
("panY", number(data.surface.pan.y)),
("zoom", number(data.surface.zoom)),
]),
Kind::Text { value, size, color } => fields.extend([
("text", Value::Text(value.clone())),
("size", Value::Number((*size as i64).into())),
@@ -393,6 +405,30 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
}
Ok(n)
};
if matches!(name, "x" | "y" | "panX" | "panY" | "zoom") {
let n = crate::scroll::coordinate(value)?;
match name {
"x" => data.position[0] = n,
"y" => data.position[1] = n,
"panX" if matches!(data.kind, Kind::Page) => data.surface.pan.x = n,
"panY" if matches!(data.kind, Kind::Page) => data.surface.pan.y = n,
"zoom" if matches!(data.kind, Kind::Page) => {
if !(0.1..=4.0).contains(&n) {
return Err(invalid_zoom());
}
data.surface.zoom = n;
}
_ => {}
}
return Ok(());
}
if matches!(data.kind, Kind::Page) && name == "mode" {
let Value::Text(name) = value else {
return Err(bad());
};
data.surface.mode = crate::page::Mode::parse(name)?;
return Ok(());
}
match name {
"flexBasis" => {
data.flex_policy.basis = if matches!(value, Value::Nil)
@@ -472,3 +508,7 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
}
Ok(())
}
fn invalid_zoom() -> VmError {
VmError::InvalidArgument("Page.zoom expects a number from 0.1 to 4")
}
+15
View File
@@ -113,6 +113,18 @@ pub struct RenderDocument {
impl RenderDocument {
pub fn validate(&self) -> Result<()> {
let surface = &self.frame.surface;
if !surface.zoom.is_finite()
|| !(0.1..=4.0).contains(&surface.zoom)
|| ![surface.pan.x, surface.pan.y]
.iter()
.all(|v| v.is_finite() && v.abs() <= 1_000_000.0)
|| ![surface.extent.width, surface.extent.height]
.iter()
.all(|v| v.is_finite() && (0.0..=1_000_000.0).contains(v))
{
bail!("invalid page camera or extent");
}
if self.windows.len() > 15 {
bail!("too many window projections");
}
@@ -322,6 +334,8 @@ impl CodeNode {
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Frame {
#[serde(default)]
pub surface: crate::page::Surface,
#[serde(default = "default_window")]
pub window: u64,
#[serde(default = "default_background")]
@@ -347,6 +361,7 @@ pub struct Frame {
impl Default for Frame {
fn default() -> Self {
Self {
surface: crate::page::Surface::default(),
window: crate::window::MAIN_WINDOW,
background: default_background(),
commands: Vec::new(),
+3
View File
@@ -16,6 +16,7 @@ pub(crate) struct Presentation {
pub tab_ids: Vec<(WeakObjectRef, u64)>,
pub next_tab: u64,
pub last_tabs: Vec<crate::tabs::Tab>,
pub surface: crate::page::Surface,
pub render_cache: crate::snapshot::RenderCache,
pub layout: crate::layout::LayoutRuntime,
pub mounts: crate::mount::MountTable,
@@ -122,6 +123,7 @@ impl Presentation {
tab_ids: Vec::new(),
next_tab: 0,
last_tabs: Vec::new(),
surface: crate::page::Surface::default(),
render_cache: crate::snapshot::RenderCache::default(),
layout: crate::layout::LayoutRuntime::default(),
mounts: crate::mount::MountTable::default(),
@@ -177,6 +179,7 @@ mod tests {
height: 160.0,
});
let root = UiNode {
surface: None,
flex: 0.0,
flex_policy: crate::layout::FlexPolicy::default(),
main_align: crate::layout::MainAlign::Start,
+21
View File
@@ -264,6 +264,22 @@ impl RenderCache {
gap: data.gap,
children,
},
Kind::Page if data.surface.mode == crate::page::Mode::Canvas => UiKind::Canvas {
positions: data
.children
.iter()
.map(|child| {
let (_, data) = block::resolve(store, child.block)?;
Ok(block::visual_data(store, data)?.position)
})
.collect::<Result<Vec<_>, VmError>>()?,
children,
},
Kind::Page if data.surface.mode == crate::page::Mode::Horizontal => UiKind::Row {
padding: data.padding,
gap: data.gap,
children,
},
Kind::Column | Kind::Page => UiKind::Column {
padding: data.padding,
gap: data.gap,
@@ -276,6 +292,11 @@ impl RenderCache {
},
};
let next = UiNode {
surface: matches!(data.kind, Kind::Page).then(|| {
let mut surface = data.surface.clone();
surface.page = block.to_string();
surface
}),
flex: data.flex,
flex_policy: data.flex_policy,
main_align: data.main_align,
+38
View File
@@ -65,6 +65,44 @@ pub struct DisplayList {
}
impl DisplayList {
pub fn scale(&mut self, scale: f32) {
for command in &mut self.commands {
let rect = match command {
DrawCommand::WrappedText { rect, style, .. } => {
*style = style.scaled(scale);
Some(rect)
}
DrawCommand::PushClip(rect) => Some(rect),
DrawCommand::FillRoundedRect { rect, radius, .. } => {
*radius *= scale;
Some(rect)
}
DrawCommand::StrokeRoundedRect {
rect,
radius,
width,
..
} => {
*radius *= scale;
*width *= scale;
Some(rect)
}
DrawCommand::Text { origin, style, .. } => {
origin.x *= scale;
origin.y *= scale;
*style = style.scaled(scale);
None
}
_ => None,
};
if let Some(rect) = rect {
rect.x *= scale;
rect.y *= scale;
rect.width *= scale;
rect.height *= scale;
}
}
}
pub fn push(&mut self, command: DrawCommand) {
self.commands.push(command);
}
+1 -1
View File
@@ -1,4 +1,4 @@
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Point {
pub x: f32,
pub y: f32,
+41 -10
View File
@@ -59,7 +59,7 @@ impl Default for FlexPolicy {
}
}
#[derive(Default, Debug, Clone, Copy, PartialEq)]
#[derive(Default, Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Size {
pub width: f32,
pub height: f32,
@@ -90,6 +90,7 @@ pub struct LayoutRuntime {
pub settle_passes: usize,
pub slices: usize,
pub viewport: Option<Size>,
pub page_mode: Option<crate::page::Mode>,
}
struct Item<'a> {
@@ -107,6 +108,13 @@ fn bounded(value: f32) -> Result<f32> {
Ok(value)
}
fn coordinate(value: f32) -> Result<f32> {
if !value.is_finite() || value.abs() > MAX_DIMENSION as f32 {
bail!("UI coordinate exceeds the 1000000 limit");
}
Ok(value)
}
pub fn root_constraints(viewport: Option<Size>) -> [f32; 4] {
let size = viewport.unwrap_or(Size {
width: MAX_DIMENSION as f32,
@@ -115,6 +123,9 @@ pub fn root_constraints(viewport: Option<Size>) -> [f32; 4] {
[0.0, 0.0, size.width, size.height]
}
pub fn child_constraints(node: &UiNode, parent: [f32; 4]) -> [f32; 4] {
if matches!(node.kind, UiKind::Canvas { .. }) {
return root_constraints(None);
}
if let UiKind::Scroll { width, height, .. } = node.kind {
return arranged_child_constraints(
node,
@@ -229,6 +240,14 @@ fn measure_shape(shape: &Shape) -> Result<Size> {
fn shape(node: &UiNode, children: Vec<Size>, constraints: [f32; 4]) -> Result<Shape> {
Ok(match &node.kind {
UiKind::Canvas { positions, .. } => {
let mut size = Size::default();
for (position, child) in positions.iter().zip(children) {
size.width = size.width.max(position[0] + child.width);
size.height = size.height.max(position[1] + child.height);
}
Shape::Rect(size.width, size.height)
}
UiKind::Text { value, size, .. } => Shape::Text(value.clone(), *size, constraints[2]),
UiKind::Rect { width, height, .. } => Shape::Rect(*width, *height),
UiKind::Spacer(size) => Shape::Rect(*size, *size),
@@ -399,6 +418,12 @@ pub fn arrange_native(
bounds: Size,
children: &[Size],
) -> Result<Vec<(f32, f32)>> {
if let UiKind::Canvas { positions, .. } = &node.kind {
return Ok(positions
.iter()
.map(|point| (x + point[0], y + point[1]))
.collect());
}
let Some((row, padding, gap)) = container(node) else {
return Ok(vec![]);
};
@@ -427,10 +452,10 @@ pub fn arrange_native(
} else {
(x + padding, y + cursor)
};
bounded(point.0)?;
bounded(point.1)?;
bounded(point.0 + child.width)?;
bounded(point.1 + child.height)?;
coordinate(point.0)?;
coordinate(point.1)?;
coordinate(point.0 + child.width)?;
coordinate(point.1 + child.height)?;
points.push(point);
cursor += if row { child.width } else { child.height };
cursor += gap + distributed_gap;
@@ -439,6 +464,12 @@ pub fn arrange_native(
}
impl LayoutRuntime {
pub fn root_constraints(&self) -> [f32; 4] {
self.page_mode.map_or_else(
|| root_constraints(self.viewport),
|mode| mode.constraints(self.viewport),
)
}
pub fn invalidate(&mut self, block: &str) {
self.sizes.remove(block);
}
@@ -495,7 +526,7 @@ impl LayoutRuntime {
self.settle_passes = usize::from(!structural);
self.slices = usize::from(!structural);
let mut items = Vec::<Item<'_>>::new();
let mut work = vec![(root, None::<usize>, 0, root_constraints(self.viewport))];
let mut work = vec![(root, None::<usize>, 0, self.root_constraints())];
let mut used = HashSet::new();
while let Some((node, parent, slot, constraints)) = work.pop() {
if items.len() >= MAX_LAYOUT_VISITS {
@@ -568,10 +599,10 @@ impl LayoutRuntime {
self.arranged += usize::from(!structural);
let (x, y) = points[index];
let size = sizes[index];
bounded(x)?;
bounded(y)?;
bounded(x + size.width)?;
bounded(y + size.height)?;
coordinate(x)?;
coordinate(y)?;
coordinate(x + size.width)?;
coordinate(y + size.height)?;
mounts.push(MountGeometry {
id: item.id,
clip: None,
+1
View File
@@ -3,6 +3,7 @@ pub(crate) mod display_list;
pub(crate) mod geometry;
pub(crate) mod layout;
pub(crate) mod native_visual;
pub(crate) mod page;
pub(crate) mod scene;
pub(crate) mod scroll;
pub(crate) mod software_renderer;
+2 -2
View File
@@ -202,8 +202,8 @@ impl NativeCallable for Method {
)?)
}
Query::Arrange => {
let x = number(cx, input, "x", false)?;
let y = number(cx, input, "y", false)?;
let x = number(cx, input, "x", true)?;
let y = number(cx, input, "y", true)?;
let width = number(cx, input, "width", false)?;
let height = number(cx, input, "height", false)?;
if x + width > MAX_DIMENSION as f32 || y + height > MAX_DIMENSION as f32 {
+190
View File
@@ -0,0 +1,190 @@
//! Page space is independent of the native window. The camera is applied once
//! for painting and inverted once for input; layout and Mounts stay in world units.
use crate::{geometry::Point, layout::Size};
use endor_core::VmError;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Mode {
#[default]
Window,
Vertical,
Horizontal,
Canvas,
}
impl Mode {
pub fn name(self) -> &'static str {
match self {
Self::Window => "window",
Self::Vertical => "vertical",
Self::Horizontal => "horizontal",
Self::Canvas => "canvas",
}
}
pub fn parse(name: &str) -> Result<Self, VmError> {
match name {
"window" => Ok(Self::Window),
"vertical" => Ok(Self::Vertical),
"horizontal" => Ok(Self::Horizontal),
"canvas" => Ok(Self::Canvas),
_ => Err(VmError::InvalidArgument(
"Page.mode expects window, vertical, horizontal or canvas",
)),
}
}
pub fn constraints(self, viewport: Option<Size>) -> [f32; 4] {
let Some(size) = viewport else {
return crate::layout::root_constraints(None);
};
let limit = crate::ui_bridge::MAX_DIMENSION as f32;
match self {
Self::Window => [size.width, size.height, size.width, size.height],
Self::Vertical => [size.width, size.height, size.width, limit],
Self::Horizontal => [size.width, size.height, limit, size.height],
Self::Canvas => [0.0, 0.0, limit, limit],
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Surface {
pub mode: Mode,
pub page: String,
pub pan: Point,
#[serde(default = "unit")]
pub zoom: f32,
pub extent: Size,
}
fn unit() -> f32 {
1.0
}
impl Default for Surface {
fn default() -> Self {
Self {
mode: Mode::Window,
page: String::new(),
pan: Point::default(),
zoom: 1.0,
extent: Size::default(),
}
}
}
impl Surface {
pub fn new(mode: Mode) -> Self {
Self {
mode,
zoom: 1.0,
..Self::default()
}
}
pub fn to_world(&self, point: Point) -> Point {
Point::new(
point.x / self.zoom + self.pan.x,
point.y / self.zoom + self.pan.y,
)
}
pub fn to_view(&self, point: Point) -> Point {
Point::new(
(point.x - self.pan.x) * self.zoom,
(point.y - self.pan.y) * self.zoom,
)
}
pub fn contains(&self, point: [f32; 2], viewport: Option<Size>) -> bool {
let point = self.to_view(Point::new(point[0], point[1]));
point.x >= 0.0
&& point.y >= 0.0
&& viewport.is_none_or(|size| point.x < size.width && point.y < size.height)
}
pub fn clamp(&mut self, viewport: Size) {
match self.mode {
Mode::Window => {
self.pan = Point::default();
self.zoom = 1.0;
}
Mode::Vertical => {
self.zoom = 1.0;
self.pan.x = 0.0;
self.pan.y = self
.pan
.y
.clamp(0.0, (self.extent.height - viewport.height).max(0.0));
}
Mode::Horizontal => {
self.zoom = 1.0;
self.pan.y = 0.0;
self.pan.x = self
.pan
.x
.clamp(0.0, (self.extent.width - viewport.width).max(0.0));
}
Mode::Canvas => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn camera_inverse_and_cursor_anchored_zoom_preserve_world_position() {
let mut view = Surface::new(Mode::Canvas);
view.pan = Point::new(-240.0, 120.0);
view.zoom = 0.75;
let pointer = Point::new(300.0, 180.0);
let world = view.to_world(pointer);
assert_eq!(view.to_view(world), pointer);
view.zoom = 2.0;
view.pan = Point::new(
world.x - pointer.x / view.zoom,
world.y - pointer.y / view.zoom,
);
assert_eq!(view.to_view(world), pointer);
assert!(view.contains(
[world.x, world.y],
Some(Size {
width: 500.0,
height: 400.0
})
));
assert!(!view.contains(
[-1000.0, -1000.0],
Some(Size {
width: 500.0,
height: 400.0
})
));
}
#[test]
fn finite_pages_clamp_after_content_shrinks() {
let mut view = Surface::new(Mode::Vertical);
view.pan = Point::new(25.0, 900.0);
view.extent = Size {
width: 400.0,
height: 800.0,
};
view.clamp(Size {
width: 400.0,
height: 600.0,
});
assert_eq!(view.pan, Point::new(0.0, 200.0));
view.extent.height = 100.0;
view.clamp(Size {
width: 400.0,
height: 600.0,
});
assert_eq!(view.pan.y, 0.0);
}
}
+38 -52
View File
@@ -1,8 +1,9 @@
use crate::{
activity::Activity,
developer_tools::{self, DeveloperToolsLayout, Workspace as DeveloperToolsState},
display_list::DisplayList,
display_list::{DisplayList, DrawCommand},
document::RenderDocument,
geometry::{Point, Rect},
};
#[derive(Clone, Debug, Default)]
@@ -17,7 +18,7 @@ pub fn build_scene(
document: &RenderDocument,
developer_tools_state: &mut DeveloperToolsState,
activity: &Activity,
tab_chrome: crate::tabs::Chrome,
sidebar: &mut crate::sidebar::State,
) -> DisplayScene {
let tool = document
.frame
@@ -27,69 +28,54 @@ pub fn build_scene(
.and_then(|tab| tab.developer_tool.as_deref());
developer_tools_state.select(tool);
developer_tools_state.document_updated(document);
let mut display_list = document.display_list(scale).unwrap_or_else(|_| {
let left = sidebar.left();
let surface = &document.frame.surface;
let content = Rect::new(
left * scale,
0.0,
(width as f32 - left * scale).max(0.0),
height as f32,
);
let zoom = if tool.is_some() { 1.0 } else { surface.zoom };
let mut page = document.display_list(scale * zoom).unwrap_or_else(|_| {
RenderDocument::default()
.display_list(scale)
.expect("default document is valid")
});
let offset = crate::tabs::height(&document.frame.tabs);
let inset = crate::tabs::INSET;
let left = crate::tabs::RAIL;
let content = crate::geometry::Rect::new(
left * scale,
offset * scale,
(width as f32 - (left + inset) * scale).max(0.0),
(height as f32 - (offset + inset) * scale).max(0.0),
);
display_list.translate(crate::geometry::Point::new(left * scale, offset * scale));
let mut framed = DisplayList::default();
use crate::display_list::DrawCommand;
framed.push(DrawCommand::Clear(crate::system_ui::theme::BAR));
framed.push(DrawCommand::PushClip(content));
for command in display_list.commands() {
if let DrawCommand::Clear(color) = command {
framed.push(DrawCommand::FillRoundedRect {
rect: content,
radius: 10.0 * scale,
color: *color,
});
} else {
framed.push(command.clone());
page.translate(Point::new(
(left - surface.pan.x * zoom) * scale,
-surface.pan.y * zoom * scale,
));
let mut display_list = DisplayList::default();
display_list.push(DrawCommand::Clear(
crate::document::parse_color(&document.frame.background)
.unwrap_or(crate::system_ui::theme::BG),
));
display_list.push(DrawCommand::PushClip(content));
for command in page.commands() {
if !matches!(command, DrawCommand::Clear(_)) {
display_list.push(command.clone());
}
}
framed.push(DrawCommand::PopClip);
let mut display_list = framed;
crate::tabs::draw(
tab_chrome.offset,
&mut display_list,
&document.frame.tabs,
width as f32 / scale,
scale,
tab_chrome.pointer,
&tab_chrome.visual,
);
if let Some(index) = tab_chrome.insertion {
crate::tabs::draw_insertion(
tab_chrome.offset,
&mut display_list,
&document.frame.tabs,
width as f32 / scale,
index,
scale,
);
}
display_list.push(DrawCommand::PopClip);
let (mut developer_list, mut developer_layout) = developer_tools::build(
width.saturating_sub(((left + inset) * scale) as u32),
height.saturating_sub(((offset + inset) * scale) as u32),
width.saturating_sub((left * scale) as u32),
height,
scale,
document,
developer_tools_state,
activity,
);
developer_list.translate(crate::geometry::Point::new(left * scale, offset * scale));
developer_layout.translate(left, offset);
developer_list.translate(Point::new(left * scale, 0.0));
developer_layout.translate(left, 0.0);
display_list.extend(developer_list);
let mut chrome = sidebar.draw(
&document.frame.tabs,
height as f32 / scale,
developer_tools_state.accent,
);
chrome.scale(scale);
display_list.extend(chrome);
DisplayScene {
display_list,
layout: SceneLayout {
+3 -3
View File
@@ -458,8 +458,8 @@ impl NativeCallable for Collect {
return Err(invalid("duplicate arrangement slot"));
}
let bounds = [
number(cx, *item, "x", false)?,
number(cx, *item, "y", false)?,
number(cx, *item, "x", true)?,
number(cx, *item, "y", true)?,
number(cx, *item, "width", false)?,
number(cx, *item, "height", false)?,
];
@@ -876,7 +876,7 @@ pub fn start(
children[indices[&parent]].push(index);
}
}
let mut constraints = vec![layout::root_constraints(runtime.viewport); nodes.len()];
let mut constraints = vec![runtime.root_constraints(); nodes.len()];
for index in 0..nodes.len() {
let next = layout::child_constraints(&nodes[index], constraints[index]);
for child in &children[index] {
+26 -3
View File
@@ -54,6 +54,29 @@ It does not publish a page or change revision. Console does not use this endpoin
All execution endpoints share the eight-entry queue. These are in-process bounded
host executions, not a complete untrusted-code sandbox or a process-isolation design.
## Page modes and camera
Page.mode is "window" (default), "vertical", "horizontal" or "canvas".
Window fills the available page viewport. Vertical constrains width and grows
height with children; horizontal constrains height and grows width. Scroll
finite pages with the wheel; the offset clamps to their actual extent.
Canvas arranges direct children at signed child.x / child.y world positions.
page.render(root) replaces content; page.append(child) adds another child.
Changing these attributes updates live occurrences, without copying objects.
Canvas uses Page.panX / panY as the world origin and Page.zoom (0.1..4).
Wheel/trackpad pans, Space+left drag or middle drag pans, pinch or Cmd/Ctrl+wheel
zooms around the pointer. Positions are finite and bounded to +/-1000000 by the
existing renderer budget; canvas navigation is not clipped to content extent.
The camera belongs to the Page and survives page switching.
Nested ScrollBlock input is handled before page panning.
Native transport kinds "page-pan" and "page-zoom" use mount=0 and current
window/session/layout_version. Pan delta is a two-component viewport-pixel
displacement. Zoom uses delta=[positive_scale_factor,0] and point=[x,y] in
viewport coordinates. Ordinary click/scroll coordinates remain world coordinates;
the host inverts the camera and the worker rechecks visibility and frame identity.
## Managed visual types
`Object`, `Type`, `Function`, `Task`, `Block`, `ContainerBlock`, `TextBlock`, `RectBlock`,
@@ -67,7 +90,7 @@ declarations, explicit first `self` parameters, positional field construction an
member assignment. Inherited methods bind the actual receiver; overridden methods
are dynamically selected through self. Concrete native visual subclasses reuse real native allocators; abstract bases remain unconstructible. Explicit traits and source parameter/return annotation checks are enabled; declared-field construction/write checks are enabled alongside source function checks; complete initialization and static/effect typing remain pending. Native Block/Page methods use the same type method tables and binding path.
Window is a host-provided managed resource: ui.window(), page.window(), page.open(window), window.pages()/id()/viewport(), resize(width,height), moveTo(x,y), setTitle(text) and focus(). Requests project to their actual native window only after successful input/candidate completion and carry the current runtime session. Resize is asynchronous and the reported viewport is authoritative; this host accepts 1..4096 logical dimensions with a native 720x480 minimum. Failed input/candidates discard pending requests and read-only rendering rejects window effects. Open Pages appear in native tab chrome, with page.title, click activation/close, Ctrl+Tab cycling and Cmd/Ctrl+W close when page keyboard focus is active. Overflow arrows reach additional pages. These operations call actual Page methods in the same VM; tab IDs are weak runtime projections and add no GC roots. The 36-logical-pixel bar reduces Page constraint height; window/ui viewport reports the full inner size and native pointer positions are translated into content coordinates. Window() now creates additional native windows in the same VM, up to 16 open resources. Page.open(window)/moveToWindow(window) preserve Page and business identity while replacing Mounts; detachToWindow() creates and returns a new Window. Dragging a tab away from its strip invokes the same method. Window.close()/secondary OS close remove Page roots, unmount, and retire the resource context; retained Pages can reopen in another live window, and closed Window resources reject viewport/resize/title/focus operations. Closing the primary OS shell exits the application. Secondary viewport inputs and frame publication use the same worker. Secondary close after callback/rendering failure uses host-only teardown without invoking source callbacks or resuming execution. After reset/discard, closing an old picture never touches a fresh VM resource with the same number; viewport inputs are also generation-scoped. A teardown failure discards the affected VM and disables remaining pictures. Native initialization/surface errors are reported rather than panicking; failed secondary creation leaves a managed resource closable from Console. Native tab reordering, existing-window drops and release-point placement use the managed methods described below. Application-exit cleanup is described below.
Window is a host-provided managed resource: ui.window(), page.window(), page.open(window), window.pages()/id()/viewport(), resize(width,height), moveTo(x,y), setTitle(text) and focus(). Each window has a collapsible left sidebar for pages and Console/Sources/Network/Settings. Cmd/Ctrl+B toggles it. Collapsed, only the sidebar toggle and native macOS window controls remain over page content. Viewport queries report the actual available page area, with no top strip or content inset. Page selection/closure calls actual managed Page methods; Ctrl+Tab cycles pages, Cmd/Ctrl+T creates one and Cmd/Ctrl+W closes the active page. Window() creates another native resource in the same VM, up to 16. Page.open(window), moveToWindow(window) and detachToWindow() preserve business identity and replace occurrence Mounts. Window.close() releases Page roots and retires its presentation; primary native close exits the application. Resource changes publish only after successful input/candidate completion. Frame/session/window generations reject stale events and commands. Sidebar pointer drag/reorder is not implemented.
Application exit now uses a private VM-worker control channel, independent of HTTP queue capacity. Main native close and a managed primary Window.close request asynchronous cleanup; duplicate requests coalesce and mutation requests are rejected with 503 while exiting. An unpublished candidate/input refresh is cancelled without replay. The current VM cancels all Task entries, closes managed windows, detaches occurrences child-before-parent per window, and invokes normal onUnmount hooks once. It does not run layout/paint during shutdown. All windows are closed before hooks run; new windows and tasks are forbidden. A stopped/faulted VM detaches without source hooks; reset/discarded pictures cannot revive an old VM. A hook error aborts remaining source hooks, releases prepared hook roots, drops the VM and reports failure before native exit. Completed shutdown is acknowledged to the GUI, which then ends the event loop. An OS exit bypassing CloseRequested uses a five-second bounded final fallback; non-cooperative native calls remain atomic and force-kill/crash cannot guarantee notifications. Native stderr records the window/mount/task-entry counts and whether source hooks were enabled, or the cleanup error. See examples/exit-lifecycle.endor. Cross-platform exit/drag validation remains broader follow-up work.
@@ -78,10 +101,10 @@ Source layout/paint now validate name-level read observations from Aster: each g
While a native tab drag is held over an overflow arrow area, the strip waits 350ms then reveals one hidden tab every 120ms, including in a compatible destination window. The preview scroll does not activate Pages or change business state. Drawing, hit testing and insertion gaps share the same transient visible range; release uses its full-order insertion index. Leaving the strip stops the timer; release, Escape, a new press or runtime generation change restores the normal active-tab-centered strip. A resize or changing tab count clamps the range. Native drag/mixed-DPI behavior still requires platform validation; application-exit cleanup is described below.
Page navigation is in the left sidebar; the former horizontal strip and its drag/overflow animation are removed. Managed moveTab/moveToWindow/detachToWindow and the version-checked tab-drop API remain available. Sidebar pointer drag/reorder and mixed-DPI cross-window gestures are not implemented in this revision.
ContainerBlock.insert(position,block) accepts a zero-based position through the current count, returns a new stable slot and preserves existing slots/Mounts. Invalid indices and child cycles fail before changing the child list. Page.moveTab(position) uses a final zero-based index in its owning window. Native drops invoke the actual Page moveToWindow/moveTab/activate methods; a declined or redirected window move skips destination reordering. A drop allows 300000 instructions per method. Source overrides participate; earlier writes do not roll back after failure. Window.moveTo(x,y) queues the physical desktop outer origin, with signed integers within +/-1000000. Detached placement preserves the saved grab offset; the window manager may adjust it and unsupported global placement reports a diagnostic. Dragging uses a 12-logical-pixel threshold, visible insertion marker and Escape cancellation. Overflow auto-scroll, external-app occlusion and mixed-DPI verification remain pending. See examples/tab-placement.endor.
ContainerBlock.insert(position,block) accepts a zero-based position through the current count, returns a new stable slot and preserves existing slots/Mounts. Invalid indices and child cycles fail before changing the child list. Page.moveTab(position) uses a final zero-based index in its owning window. Native drops invoke the actual Page moveToWindow/moveTab/activate methods; a declined or redirected window move skips destination reordering. A drop allows 300000 instructions per method. Source overrides participate; earlier writes do not roll back after failure. Window.moveTo(x,y) queues the physical desktop outer origin, with signed integers within +/-1000000. Detached placement preserves the saved grab offset; the window manager may adjust it and unsupported global placement reports a diagnostic. These movement methods remain callable from Endor and transport clients; the sidebar currently provides selection and closure rather than pointer dragging. See examples/tab-placement.endor.
Source measure and arrange overrides execute bottom-up and top-down in one read-only VM layout call. Structural Mount links exist before first measurement; bounds queries reject premature geometry. Native base layout uses current occurrence child measurements, and Arrangement must assign every stable child slot exactly once. Layout dependencies changed by lifecycle hooks trigger another pass before publication. Page constraints now use the current logical window viewport. Column/Button propagate cross-axis width and Row propagates cross-axis height; desired sizes are clamped. ui.viewport() provides a managed snapshot whose private input participates in rendering dependencies. Native resize updates are coalesced on the same worker without adding source inputs. Source measurement caches use Mount/method/children/constraints and actual subcall object reads, including returned-result decoding; Mount-reading methods conservatively bypass caching. ui.stats() exposes sourceMeasureHits/sourceMeasureMisses outside read-only rendering. Native TextBlock wrapping now uses the occurrence width in measurement/cache/painting; source measurement/arrangement now repeats until constraints and geometry settle; additional allocation policies remain pending; ScrollBlock scrolling is described below.
+102
View File
@@ -479,3 +479,105 @@ page.render(TextBlock("input priority"))
let value = runtime.execute("count.value", "app.main").unwrap().value;
assert_eq!(value, "1");
}
#[test]
fn canvas_camera_crosses_real_http_route_and_preserves_negative_world_clicks() {
let server = Arc::new(Server::http("127.0.0.1:0").unwrap());
let namespace = Arc::new(RwLock::new(NamespaceState {
viewport: Some(crate::layout::Size {
width: 600.0,
height: 400.0,
}),
..NamespaceState::default()
}));
let api = start_server(server.clone(), namespace.clone(), Arc::new(|| {})).unwrap();
let client = TestServer {
address: server.server_addr().to_ip().unwrap(),
server,
api: Some(api),
};
let source = r#"
count=ui.state(0)
button=Button("world")
button.onClick(count.increment)
button.x=-160
button.y=-80
page=Page()
page.mode="canvas"
page.render(button)
"#;
let response = client.request("PUT", "/v1/namespaces/app.main/code", source);
assert_eq!(response.0, 200, "{}", response.2);
let camera = |kind: &str, delta: [f32; 2], point: Option<[f32; 2]>| {
let frame = &namespace.read().unwrap().document.frame;
serde_json::to_string(&crate::events::Input {
window: 1,
session: frame.session,
layout_version: frame.layout_version,
mount: 0,
kind: kind.into(),
delta: Some(delta),
point,
press_point: None,
screen_position: None,
tab_drop: None,
})
.unwrap()
};
let event_path = "/v1/namespaces/app.main/events";
let pan = camera("page-pan", [-240.0, -160.0], None);
let response = client.request("POST", event_path, &pan);
assert_eq!(response.0, 200, "{}", response.2);
assert_eq!(
namespace.read().unwrap().document.frame.surface.pan,
crate::geometry::Point::new(-240.0, -160.0)
);
assert_eq!(client.request("POST", event_path, &pan).0, 409);
let response = client.request(
"POST",
event_path,
&camera("page-zoom", [2.0, 0.0], Some([120.0, 90.0])),
);
assert_eq!(response.0, 200, "{}", response.2);
{
let current = namespace.read().unwrap();
assert_eq!(current.document.frame.surface.zoom, 2.0);
assert_eq!(
current.document.frame.surface.pan,
crate::geometry::Point::new(-180.0, -115.0)
);
}
let input = {
let current = namespace.read().unwrap();
let frame = &current.document.frame;
let mount = frame.mounts.iter().find(|m| m.interactive).unwrap();
assert!(mount.x < 0.0 && mount.y < 0.0);
crate::events::Input {
window: 1,
session: frame.session,
layout_version: frame.layout_version,
mount: mount.id,
kind: "click".into(),
point: Some([-150.0, -70.0]),
press_point: Some([-150.0, -70.0]),
delta: None,
screen_position: None,
tab_drop: None,
}
};
let response = client.request("POST", event_path, &serde_json::to_string(&input).unwrap());
assert_eq!(response.0, 200, "{}", response.2);
let response = client.request("POST", "/v1/namespaces/app.main/repl", "count.value");
assert_eq!(response.0, 200, "{}", response.2);
assert_eq!(
serde_json::from_str::<serde_json::Value>(&response.2).unwrap()["value"],
"1"
);
let response = client.request(
"POST",
event_path,
&camera("page-zoom", [0.0, 0.0], Some([120.0, 90.0])),
);
assert_eq!(response.0, 400);
assert!(namespace.read().unwrap().document.frame.fault.is_none());
}
+14 -1
View File
@@ -336,6 +336,8 @@ impl Worker {
"click"
| "focus"
| "scroll"
| "page-pan"
| "page-zoom"
| "tab-activate"
| "tab-close"
| "tab-detach"
@@ -422,7 +424,10 @@ impl Worker {
|| frame.session != input.session
|| (input.kind != "window-close" && frame.layout_version != input.layout_version)
|| frame.fault.is_some()
|| if input.kind == "window-close" || input.kind.starts_with("developer-open:") {
|| if input.kind == "window-close"
|| input.kind.starts_with("developer-open:")
|| matches!(input.kind.as_str(), "page-pan" | "page-zoom")
{
input.mount != 0
} else if matches!(
input.kind.as_str(),
@@ -447,6 +452,14 @@ impl Worker {
"event targets an obsolete or inactive frame",
));
}
if input.kind == "page-zoom" && frame.surface.mode != crate::page::Mode::Canvas
|| input.kind == "page-pan" && frame.surface.mode == crate::page::Mode::Window
{
return RequestProgress::Complete(error_response(
StatusCode(400),
"camera input is unavailable in this Page mode",
));
}
Some(input)
} else {
None
+200 -9
View File
@@ -207,10 +207,10 @@ page.render(Column(0,8,Column(0,8,paragraph,tail),Column(50,8,paragraph)))
})
.collect();
assert_eq!(commands.len(), 2);
// The 240px window reserves 56px for the rail and 8px for its inset.
// The second occurrence additionally has 50px padding on each side.
assert_eq!(commands[0][0], 176.0);
assert_eq!(commands[1][0], 76.0);
// The viewport is already the available page area; there is no implicit
// rail/inset subtraction. The second occurrence has 50px padding per side.
assert_eq!(commands[0][0], 240.0);
assert_eq!(commands[1][0], 140.0);
assert!(commands[1][1] > commands[0][1]);
let tail = initial
.frame
@@ -251,7 +251,7 @@ page.render(Column(0,8,Column(0,8,paragraph,tail),Column(50,8,paragraph)))
_ => None,
})
.collect();
assert_eq!(widths, [336.0, 236.0]);
assert_eq!(widths, [400.0, 300.0]);
let heights: Vec<_> = resized
.frame
.commands
@@ -1774,14 +1774,14 @@ fn viewport_resize_changes_constraints_and_preserves_mount_identity_without_sour
}),
)
.unwrap();
// Page content excludes the 56px rail, 8px inset and 24px root padding
// on each side, both initially and after resizing the outer window.
// The viewport is the actual page area; only the Endor root's 24px padding
// on each side is removed, both initially and after resizing.
assert!(
initial
.frame
.mounts
.iter()
.any(|mount| mount.width == 688.0 && mount.height == 24.0)
.any(|mount| mount.width == 752.0 && mount.height == 24.0)
);
let ids: Vec<_> = initial.frame.mounts.iter().map(|mount| mount.id).collect();
let document = session
@@ -1805,7 +1805,7 @@ fn viewport_resize_changes_constraints_and_preserves_mount_identity_without_sour
.frame
.mounts
.iter()
.any(|mount| mount.width == 248.0 && mount.height == 24.0)
.any(|mount| mount.width == 312.0 && mount.height == 24.0)
);
assert_eq!(session.inputs, 0);
assert!(
@@ -5675,3 +5675,194 @@ fn shutdown_hooks_cannot_create_new_background_work() {
assert!(format!("{error:#}").contains("runtime is exiting; new tasks are forbidden"));
assert!(session.is_faulted());
}
#[test]
fn page_modes_grow_on_the_declared_axis_and_follow_live_children() {
for (mode, expected) in [
("window", (400.0, 300.0)),
("vertical", (400.0, 710.0)),
("horizontal", (910.0, 300.0)),
] {
let source = format!(
r#"page=Page()
page.mode="{mode}"
page.gap=10
page.render(RectBlock(450,350))
page.append(RectBlock(450,350))"#
);
let (mut session, document) = ReplSession::load_with_viewport(
&source,
"app.main",
1,
300,
Some(crate::layout::Size {
width: 400.0,
height: 300.0,
}),
)
.unwrap();
let root = &document.frame.mounts[0];
assert_eq!((root.width, root.height), expected, "{mode}");
if mode == "vertical" {
let next = session
.execute("page.append(RectBlock(450,350))", "app.main")
.unwrap()
.document
.unwrap();
assert_eq!(next.frame.mounts[0].height, 1070.0);
}
if mode == "horizontal" {
let next = session
.execute("page.append(RectBlock(450,350))", "app.main")
.unwrap()
.document
.unwrap();
assert_eq!(next.frame.mounts[0].width, 1370.0);
}
}
}
#[test]
fn canvas_positions_are_live_signed_and_shared_without_copying_objects() {
let (mut session, initial) = ReplSession::load_with_viewport(
r#"
item=Button("same object")
item.x=-120
item.y=90
page=Page()
page.mode="canvas"
page.render(item)
page.append(item)
page.panX=-160
page.zoom=2
"#,
"app.main",
1,
301,
Some(crate::layout::Size {
width: 400.0,
height: 300.0,
}),
)
.unwrap();
let mounts: Vec<_> = initial
.frame
.mounts
.iter()
.filter(|mount| mount.interactive)
.collect();
assert_eq!(mounts.len(), 2);
assert_eq!(mounts[0].block_id, mounts[1].block_id);
assert_ne!(mounts[0].id, mounts[1].id);
assert_eq!((mounts[0].x, mounts[0].y), (-120.0, 90.0));
assert_eq!(initial.frame.surface.pan.x, -160.0);
assert_eq!(initial.frame.surface.zoom, 2.0);
let next = session
.execute("item.x=500\nitem.y=-60", "app.main")
.unwrap()
.document
.unwrap();
assert!(
next.frame
.mounts
.iter()
.filter(|m| m.interactive)
.all(|m| m.x == 500.0 && m.y == -60.0)
);
let old_page = next.frame.surface.page.clone();
let window = session
.execute(
"other=Page()\nother.render(TextBlock(\"other\"))",
"app.main",
)
.unwrap()
.document
.unwrap();
assert_eq!(window.frame.surface.mode, crate::page::Mode::Window);
let restored = session
.execute("page.activate()", "app.main")
.unwrap()
.document
.unwrap();
assert_eq!(restored.frame.surface.page, old_page);
assert_eq!(restored.frame.surface.pan.x, -160.0);
assert_eq!(restored.frame.surface.zoom, 2.0);
}
#[test]
fn bundled_start_page_creates_all_four_real_page_modes() {
let mut session = ReplSession::new_with_viewport(
302,
Some(crate::layout::Size {
width: 1024.0,
height: 800.0,
}),
)
.unwrap();
let mut document = session
.execute("ui.newTab()", "app.main")
.unwrap()
.document
.unwrap();
assert_eq!(document.frame.surface.mode, crate::page::Mode::Canvas);
for (label, mode) in [
("窗口页面", crate::page::Mode::Window),
("纵向延伸", crate::page::Mode::Vertical),
("横向延伸", crate::page::Mode::Horizontal),
] {
let home_tab = document
.frame
.tabs
.iter()
.find(|tab| tab.title == "自由画布")
.unwrap()
.id;
let point = document
.frame
.commands
.iter()
.find_map(|command| match command {
RenderCommand::Text { x, y, value, .. } if value == label => {
Some(crate::geometry::Point::new(x + 2.0, y + 2.0))
}
_ => None,
})
.unwrap();
let mount = document
.frame
.hit_test(point)
.expect("button label must be clickable")
.id;
document = session
.dispatch(&crate::events::Input {
window: 1,
session: document.frame.session,
layout_version: document.frame.layout_version,
mount,
kind: "click".into(),
point: Some([point.x, point.y]),
press_point: Some([point.x, point.y]),
delta: None,
tab_drop: None,
screen_position: None,
})
.unwrap()
.document
.unwrap();
assert_eq!(document.frame.surface.mode, mode, "{label}");
assert!(document.frame.fault.is_none());
let input = crate::events::Input {
window: 1,
session: document.frame.session,
layout_version: document.frame.layout_version,
mount: home_tab,
kind: "tab-activate".into(),
point: None,
press_point: None,
delta: None,
tab_drop: None,
screen_position: None,
};
document = session.dispatch(&input).unwrap().document.unwrap();
}
}
+31 -2
View File
@@ -73,12 +73,41 @@ impl Input {
{
return Err("screen_position is only accepted for tab-detach with bounded coordinates");
}
if matches!(self.kind.as_str(), "page-pan" | "page-zoom") {
let valid_delta = self.delta.is_some_and(|delta| {
delta
.iter()
.all(|v| v.is_finite() && v.abs() <= 1_000_000.0)
});
let valid_point = self.point.is_none_or(|point| {
point
.iter()
.all(|v| v.is_finite() && (0.0..=1_000_000.0).contains(v))
});
if !valid_delta
|| !valid_point
|| self.mount != 0
|| self.press_point.is_some()
|| self.screen_position.is_some()
{
return Err("invalid page camera input");
}
if self.kind == "page-zoom"
&& (self.point.is_none()
|| self
.delta
.is_none_or(|delta| !(0.1..=10.0).contains(&delta[0]) || delta[1] != 0.0))
{
return Err("page-zoom requires an anchor and positive scale factor");
}
return Ok(());
}
if self.kind == "scroll" {
return match (self.point, self.press_point, self.delta) {
(Some(point), None, Some(delta))
if point
.iter()
.all(|v| v.is_finite() && (0.0..=1_000_000.0).contains(v))
.all(|v| v.is_finite() && v.abs() <= 1_000_000.0)
&& delta
.iter()
.all(|v| v.is_finite() && v.abs() <= 1_000_000.0) =>
@@ -98,7 +127,7 @@ impl Input {
&& point
.into_iter()
.chain(press)
.all(|value| value.is_finite() && (0.0..=1_000_000.0).contains(&value)) =>
.all(|value| value.is_finite() && value.abs() <= 1_000_000.0) =>
{
Ok(())
}
+269 -618
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -5,6 +5,7 @@ pub(crate) mod clipboard;
pub(crate) mod developer_tools;
#[cfg(target_os = "macos")]
pub(crate) mod native_chrome;
pub(crate) mod sidebar;
pub(crate) mod sources;
pub(crate) mod system_ui;
pub(crate) mod tabs;
+1 -1
View File
@@ -68,7 +68,7 @@ pub fn align_controls(window: &Window) {
return;
}
let bounds = view.bounds();
let center = f64::from(crate::tabs::HEIGHT) / 2.0;
let center = f64::from(crate::sidebar::HEADER) / 2.0;
let content_y = if view.isFlipped() {
bounds.origin.y + center
} else {
+162
View File
@@ -0,0 +1,162 @@
//! The only persistent host toolbar. A collapsed sidebar owns just its toggle
//! and the native traffic-light safe area; the page owns the rest of the window.
use crate::{
display_list::{DisplayList, DrawCommand},
geometry::{Point, Rect},
system_ui::{
Button, Interaction, Target, Ui,
theme::{self, Theme},
},
tabs::Tab,
};
pub const WIDTH: f32 = 256.0;
pub const HEADER: f32 = 40.0;
pub const CONTROLS: f32 = if cfg!(target_os = "macos") { 86.0 } else { 0.0 };
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Action {
Toggle,
NewPage,
Tool(&'static str),
Activate(u64),
Close(u64),
}
pub struct State {
pub open: bool,
pub interaction: Interaction,
pub targets: Vec<Target<Action>>,
pub scroll: f32,
}
impl Default for State {
fn default() -> Self {
Self {
open: true,
interaction: Interaction::default(),
targets: Vec::new(),
scroll: 0.0,
}
}
}
impl State {
pub fn left(&self) -> f32 {
if self.open { WIDTH } else { 0.0 }
}
pub fn covers(&self, point: Point) -> bool {
if self.open {
point.x >= 0.0 && point.x < WIDTH
} else {
Rect::new(0.0, 0.0, CONTROLS + 44.0, HEADER).contains(point)
}
}
pub fn draw(
&mut self,
tabs: &[Tab],
height: f32,
accent: crate::display_list::Color,
) -> DisplayList {
let mut ui = Ui::new(Theme::new(accent), self.interaction.clone());
if self.open {
ui.fill(Rect::new(0.0, 0.0, WIDTH, height), theme::BAR);
}
let toggle_x = if self.open {
WIDTH - 40.0
} else {
CONTROLS + 4.0
};
// Draw a sidebar icon with primitives so its shape does not depend on fonts.
ui.button(
Rect::new(toggle_x, 6.0, 30.0, 28.0),
Action::Toggle,
Button::new(""),
);
ui.list.push(DrawCommand::StrokeRoundedRect {
rect: Rect::new(toggle_x + 7.0, 13.0, 16.0, 13.0),
radius: 2.0,
width: 1.0,
color: theme::MUTED,
});
ui.fill(Rect::new(toggle_x + 12.0, 14.0, 1.0, 11.0), theme::MUTED);
if self.open {
ui.label(20.0, 61.0, "ENDORPHIN", theme::TEXT, false);
ui.button(
Rect::new(12.0, 95.0, WIDTH - 24.0, 34.0),
Action::NewPage,
Button::new("+ 新建页面"),
);
for (index, (name, label)) in [
("Console", "Console"),
("Sources", "Sources"),
("Network", "Network"),
("Settings", "Settings"),
]
.into_iter()
.enumerate()
{
let selected = tabs
.iter()
.any(|tab| tab.active && tab.developer_tool.as_deref() == Some(name));
ui.button(
Rect::new(12.0, 147.0 + index as f32 * 34.0, WIDTH - 24.0, 30.0),
Action::Tool(name),
Button::new(label).selected(selected),
);
}
ui.label(20.0, 303.0, "页面", theme::MUTED, false);
let area = Rect::new(8.0, 333.0, WIDTH - 16.0, (height - 383.0).max(0.0));
let pages: Vec<_> = tabs
.iter()
.filter(|tab| tab.developer_tool.is_none())
.collect();
self.scroll = self
.scroll
.clamp(0.0, (pages.len() as f32 * 36.0 - area.height).max(0.0));
ui.list.push(DrawCommand::PushClip(area));
for (index, tab) in pages.into_iter().enumerate() {
let y = area.y + index as f32 * 36.0 - self.scroll;
// Register only fully visible rows: paint clipping must match input.
if y < area.y || y + 32.0 > area.y + area.height {
continue;
}
ui.button(
Rect::new(12.0, y, WIDTH - 56.0, 32.0),
Action::Activate(tab.id),
Button::new(&tab.title).selected(tab.active),
);
ui.button(
Rect::new(WIDTH - 40.0, y, 28.0, 32.0),
Action::Close(tab.id),
Button::new("×"),
);
}
ui.list.push(DrawCommand::PopClip);
ui.label(20.0, height - 32.0, "本地工作区", theme::MUTED, false);
}
self.targets = ui.targets;
self.interaction.reconcile(&self.targets);
ui.list
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn collapsing_removes_every_host_target_except_the_toggle() {
let mut sidebar = State::default();
sidebar.draw(&[], 800.0, theme::PALETTE[0]);
assert!(sidebar.targets.len() > 1);
sidebar.open = false;
sidebar.draw(&[], 800.0, theme::PALETTE[0]);
assert_eq!(sidebar.targets.len(), 1);
assert_eq!(sidebar.targets[0].action, Some(Action::Toggle));
assert_eq!(sidebar.left(), 0.0);
assert!(!sidebar.covers(Point::new(400.0, 10.0)));
assert!(!sidebar.covers(Point::new(10.0, 80.0)));
}
}
+2 -669
View File
@@ -1,30 +1,7 @@
//! Immutable tab chrome. IDs are session-local projections, never heap handles.
use crate::{
display_list::{Color, DisplayList, DrawCommand},
geometry::{Point, Rect},
text::TextStyle,
};
//! Immutable page registry projections. Host navigation is rendered in sidebar.
//! IDs are session-local data and never own managed VM objects.
use serde::{Deserialize, Serialize};
mod hover;
mod motion;
pub use motion::{Motion, Visual};
// Native traffic lights and all tab controls share this row's center line.
pub const HEIGHT: f32 = 40.0;
pub const INSET: f32 = 8.0;
const NEW_TAB_SPACE: f32 = 44.0;
const MIN_WIDTH: f32 = 88.0;
pub const RAIL: f32 = 56.0;
pub const CONTROLS: f32 = if cfg!(target_os = "macos") { 86.0 } else { 0.0 };
pub const LEADING: f32 = CONTROLS + 12.0;
#[derive(Clone, Default)]
pub struct Chrome {
pub offset: Option<f32>,
pub insertion: Option<usize>,
pub pointer: Option<Point>,
pub visual: Visual,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Tab {
pub id: u64,
@@ -33,647 +10,3 @@ pub struct Tab {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub developer_tool: Option<String>,
}
pub fn height(tabs: &[Tab]) -> f32 {
let _ = tabs;
HEIGHT
}
/// Scroll offsets are logical pixels, never a discrete page index.
fn viewport(width: f32) -> Rect {
Rect::new(
LEADING,
0.0,
(width - NEW_TAB_SPACE - LEADING).max(0.0),
HEIGHT,
)
}
fn tab_width(tabs: &[Tab], width: f32) -> f32 {
(viewport(width).width / tabs.len().max(1) as f32)
.clamp(MIN_WIDTH, 208.0)
.min(viewport(width).width)
}
fn scroll_offset(tabs: &[Tab], width: f32, start: Option<f32>) -> f32 {
let tab_width = tab_width(tabs, width);
let available = viewport(width).width;
let maximum = (tabs.len() as f32 * tab_width - available).max(0.0);
let active = tabs.iter().position(|tab| tab.active).unwrap_or(0);
start
.unwrap_or(((active + 1) as f32 * tab_width - available).max(0.0))
.clamp(0.0, maximum)
}
#[cfg(test)]
fn visible_range(tabs: &[Tab], width: f32, start: Option<f32>) -> std::ops::Range<usize> {
let tab_width = tab_width(tabs, width);
if tab_width <= 0.0 {
return 0..0;
}
let offset = scroll_offset(tabs, width, start);
(offset / tab_width).floor() as usize
..(((offset + viewport(width).width) / tab_width).ceil() as usize).min(tabs.len())
}
/// Invisible drag edge zones only; ordinary clicks never scroll or activate another tab.
pub fn edge_direction(tabs: &[Tab], width: f32, start: Option<f32>, point: Point) -> i8 {
if !viewport(width).contains(point) || point.y >= HEIGHT {
return 0;
}
let offset = scroll_offset(tabs, width, start);
let maximum = (tabs.len() as f32 * tab_width(tabs, width) - viewport(width).width).max(0.0);
if point.x < LEADING + 24.0 && offset > 0.0 {
-1
} else if point.x > width - NEW_TAB_SPACE - 24.0 && offset < maximum {
1
} else {
0
}
}
pub fn wheel_offset(tabs: &[Tab], width: f32, start: Option<f32>, delta: f32) -> f32 {
scroll_offset(tabs, width, Some(scroll_offset(tabs, width, start) + delta))
}
pub fn scroll_start(tabs: &[Tab], width: f32, start: Option<f32>, direction: i8) -> Option<f32> {
let current = scroll_offset(tabs, width, start);
let next = wheel_offset(tabs, width, Some(current), direction as f32 * MIN_WIDTH);
(next != current).then_some(next)
}
struct Item<'a> {
tab: &'a Tab,
rect: Rect,
}
/// Retain all IDs, including clipped tabs, for continuous movement through the viewport.
fn tab_rects(start: Option<f32>, tabs: &[Tab], width: f32) -> Vec<(u64, Rect)> {
let tab_width = tab_width(tabs, width);
let offset = scroll_offset(tabs, width, start);
tabs.iter()
.enumerate()
.map(|(index, tab)| {
(
tab.id,
Rect::new(
LEADING + index as f32 * tab_width - offset,
0.0,
tab_width,
HEIGHT,
),
)
})
.collect()
}
fn items(start: Option<f32>, tabs: &[Tab], width: f32) -> Vec<Item<'_>> {
let viewport = viewport(width);
tabs.iter()
.zip(tab_rects(start, tabs, width))
.filter(|(_, (_, rect))| {
rect.x + rect.width > viewport.x && rect.x < viewport.x + viewport.width
})
.map(|(tab, (_, rect))| Item { tab, rect })
.collect()
}
fn pill_rect(rect: Rect) -> Rect {
Rect::new(rect.x + 2.0, 4.0, (rect.width - 4.0).max(0.0), HEIGHT - 8.0)
}
fn close_rect(rect: Rect) -> Rect {
Rect::new(
rect.x + rect.width - 25.0,
(HEIGHT - 18.0) / 2.0,
18.0,
18.0,
)
}
pub fn hit(start: Option<f32>, tabs: &[Tab], width: f32, point: Point) -> Option<(u64, bool)> {
if point.x < LEADING
|| point.x >= width - NEW_TAB_SPACE
|| point.y < 0.0
|| point.y >= height(tabs)
{
return None;
}
items(start, tabs, width)
.into_iter()
.find(|item| pill_rect(item.rect).contains(point))
.map(|item| (item.tab.id, close_rect(item.rect).contains(point)))
}
/// Gap index in the complete published order, including overflow-hidden tabs.
pub fn insertion_index(
start: Option<f32>,
tabs: &[Tab],
width: f32,
point: Point,
) -> Option<usize> {
if point.x < LEADING || point.x >= width - NEW_TAB_SPACE || point.y < 0.0 || point.y >= HEIGHT {
return None;
}
if tabs.is_empty() {
return Some(0);
}
let visible: Vec<_> = items(start, tabs, width).into_iter().collect();
for item in &visible {
if point.x < item.rect.x + item.rect.width / 2.0 {
return tabs.iter().position(|tab| tab.id == item.tab.id);
}
}
visible
.last()
.and_then(|last| tabs.iter().position(|tab| tab.id == last.tab.id))
.map(|index| index + 1)
}
pub fn drag_anchor(
start: Option<f32>,
tabs: &[Tab],
width: f32,
id: u64,
point: Point,
) -> Option<Point> {
if !viewport(width).contains(point) {
return None;
}
let item = items(start, tabs, width)
.into_iter()
.find(|item| item.tab.id == id && pill_rect(item.rect).contains(point))?;
(!close_rect(item.rect).contains(point)).then(|| Point::new(point.x - item.rect.x, point.y))
}
pub fn draw_insertion(
start: Option<f32>,
list: &mut DisplayList,
tabs: &[Tab],
width: f32,
index: usize,
scale: f32,
) {
let visible: Vec<_> = items(start, tabs, width).into_iter().collect();
let x = if tabs.is_empty() {
Some(LEADING + 8.0)
} else {
visible
.iter()
.find(|item| tabs.get(index).is_some_and(|tab| tab.id == item.tab.id))
.map(|item| item.rect.x)
.or_else(|| {
visible
.last()
.filter(|item| {
tabs.iter().position(|tab| tab.id == item.tab.id) == index.checked_sub(1)
})
.map(|item| item.rect.x + item.rect.width)
})
};
if let Some(x) = x {
list.push(DrawCommand::FillRoundedRect {
rect: Rect::new(
x.clamp(1.5, (width - 1.5).max(1.5)) * scale - 1.5 * scale,
3.0 * scale,
3.0 * scale,
(HEIGHT - 6.0) * scale,
),
radius: scale,
color: Color::rgb(56, 95, 220),
});
}
}
pub fn plus_rect(start: Option<f32>, tabs: &[Tab], width: f32) -> Rect {
if tabs.len() as f32 * tab_width(tabs, width) > viewport(width).width {
return Rect::new(width - 34.0, (HEIGHT - 28.0) / 2.0, 24.0, 28.0);
}
let end = items(start, tabs, width)
.iter()
.map(|item| item.rect.x + item.rect.width)
.fold(LEADING, f32::max);
Rect::new(
(end + 4.0).min(width - 34.0),
(HEIGHT - 28.0) / 2.0,
24.0,
28.0,
)
}
fn tab_style() -> TextStyle {
TextStyle {
font_size: 13.0,
line_height: 18.0,
..TextStyle::ui(1)
}
}
pub fn draw(
_start: Option<f32>,
list: &mut DisplayList,
tabs: &[Tab],
width: f32,
scale: f32,
_pointer: Option<Point>,
visual: &Visual,
) {
let scaled = |rect: Rect| {
Rect::new(
rect.x * scale,
rect.y * scale,
rect.width * scale,
rect.height * scale,
)
};
list.push(DrawCommand::FillRoundedRect {
rect: scaled(Rect::new(0.0, 0.0, width, HEIGHT)),
radius: 0.0,
color: crate::system_ui::theme::BAR,
});
let plus = visual.plus;
if visual.plus_hover > 0.0 {
list.push(DrawCommand::FillRoundedRect {
rect: scaled(plus),
radius: 6.0 * scale,
color: crate::system_ui::theme::mix(
crate::system_ui::theme::BAR,
crate::system_ui::theme::TEXT,
0.06 * visual.plus_hover,
),
});
}
list.push(DrawCommand::Text {
origin: Point::new(
(plus.x + (plus.width - crate::text::measure("+", tab_style()).width) / 2.0) * scale,
((HEIGHT - tab_style().line_height) / 2.0) * scale,
),
value: "+".into(),
style: tab_style().scaled(scale),
color: crate::system_ui::theme::MUTED,
});
let mut paint_items: Vec<_> = tabs
.iter()
.map(|tab| Item {
tab,
rect: visual.rect(tab.id, Rect::default()),
})
.collect();
paint_items.extend(
visual
.exiting
.iter()
.map(|(tab, rect)| Item { tab, rect: *rect }),
);
for item in paint_items {
{
if item.rect.width <= 0.0
|| item.rect.x + item.rect.width <= visual.viewport.x
|| item.rect.x >= visual.viewport.x + visual.viewport.width
{
continue;
}
list.push(DrawCommand::PushClip(scaled(visual.viewport)));
list.push(DrawCommand::PushClip(scaled(pill_rect(item.rect))));
}
let pill = scaled(pill_rect(item.rect));
let active = item.tab.active;
let hover = visual.hover(item.tab.id);
let background = if active {
crate::system_ui::theme::BG
} else {
crate::system_ui::theme::mix(
crate::system_ui::theme::BAR,
crate::system_ui::theme::TEXT,
0.06 * hover,
)
};
if active || hover > 0.0 {
list.push(DrawCommand::FillRoundedRect {
rect: pill,
radius: 6.0 * scale,
color: background,
});
}
{
// Match the close button with an 18px slot and 7px edge inset.
let icon = "◇";
list.push(DrawCommand::Text {
origin: Point::new(
(item.rect.x
+ 7.0
+ (18.0 - crate::text::measure(icon, tab_style()).width) / 2.0)
* scale,
((HEIGHT - tab_style().line_height) / 2.0) * scale,
),
value: icon.into(),
style: tab_style().scaled(scale),
color: crate::system_ui::theme::MUTED,
});
}
let title = &item.tab.title;
let text_rect = Rect::new(
item.rect.x + 30.0,
(HEIGHT - tab_style().line_height) / 2.0,
(item.rect.width - 58.0).max(0.0),
tab_style().line_height,
);
list.push(DrawCommand::PushClip(scaled(text_rect)));
list.push(DrawCommand::Text {
origin: Point::new(
(item.rect.x + 30.0) * scale,
((HEIGHT - tab_style().line_height) / 2.0) * scale,
),
value: title.into(),
style: tab_style().scaled(scale),
color: if active {
crate::system_ui::theme::TEXT
} else {
crate::system_ui::theme::MUTED
},
});
list.push(DrawCommand::PopClip);
if item.rect.width >= 44.0 {
let close_hover = visual.close_hover(item.tab.id);
if close_hover > 0.0 {
list.push(DrawCommand::FillRoundedRect {
rect: scaled(close_rect(item.rect)),
radius: 5.0 * scale,
color: crate::system_ui::theme::mix(
background,
crate::system_ui::theme::mix(
crate::system_ui::theme::BAR,
crate::system_ui::theme::TEXT,
0.12,
),
close_hover,
),
});
}
list.push(DrawCommand::Text {
origin: Point::new(
(close_rect(item.rect).x
+ (close_rect(item.rect).width
- crate::text::measure("×", tab_style()).width)
/ 2.0)
* scale,
((HEIGHT - tab_style().line_height) / 2.0) * scale,
),
value: "×".into(),
style: tab_style().scaled(scale),
color: crate::system_ui::theme::MUTED,
});
}
{
list.push(DrawCommand::PopClip);
list.push(DrawCommand::PopClip);
}
}
// Quiet boundaries only between two idle tabs; the active/hovered pill owns its edges.
list.push(DrawCommand::PushClip(scaled(visual.viewport)));
for pair in tabs.windows(2) {
let left = visual.rect(pair[0].id, Rect::default());
let hover = visual.hover(pair[0].id).max(visual.hover(pair[1].id));
if !pair[0].active && !pair[1].active && hover < 1.0 {
list.push(DrawCommand::FillRoundedRect {
rect: scaled(Rect::new(
left.x + left.width - 0.5,
(HEIGHT - 12.0) / 2.0,
1.0,
12.0,
)),
radius: 0.5 * scale,
color: crate::system_ui::theme::mix(
crate::system_ui::theme::BAR,
crate::system_ui::theme::TEXT,
0.18 * (1.0 - hover),
),
});
}
}
list.push(DrawCommand::PopClip);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn insertion_gaps_share_visible_tab_geometry_and_exclude_close_drags() {
let tabs: Vec<_> = (1..=4)
.map(|id| Tab {
id,
title: id.to_string(),
developer_tool: None,
active: id == 1,
})
.collect();
assert_eq!(
insertion_index(
None,
&tabs,
LEADING + NEW_TAB_SPACE + 1000.0,
Point::new(LEADING + 10.0, 18.0)
),
Some(0)
);
assert_eq!(
insertion_index(
None,
&tabs,
LEADING + NEW_TAB_SPACE + 1000.0,
Point::new(LEADING + 215.0, 18.0)
),
Some(1)
);
assert_eq!(
insertion_index(
None,
&tabs,
LEADING + NEW_TAB_SPACE + 1000.0,
Point::new(LEADING + 990.0, 18.0)
),
Some(4)
);
assert!(
drag_anchor(
None,
&tabs,
LEADING + NEW_TAB_SPACE + 1000.0,
1,
Point::new(LEADING + 190.0, 18.0)
)
.is_none()
);
assert!(
drag_anchor(
None,
&tabs,
LEADING + NEW_TAB_SPACE + 1000.0,
1,
Point::new(LEADING + 25.0, 18.0)
)
.is_some()
);
assert_eq!(
insertion_index(
None,
&tabs,
LEADING + NEW_TAB_SPACE + 1000.0,
Point::new(LEADING + 20.0, HEIGHT)
),
None
);
assert!(
drag_anchor(
None,
&tabs,
LEADING + NEW_TAB_SPACE + 400.0,
3,
Point::new(LEADING + 390.0, 18.0)
)
.is_none()
);
assert_eq!(
insertion_index(
None,
&[],
LEADING + NEW_TAB_SPACE + 720.0,
Point::new(LEADING + 20.0, 18.0)
),
Some(0)
);
}
#[test]
fn overflow_keeps_active_page_visible_without_navigation_buttons() {
let tabs: Vec<_> = (1..=64)
.map(|id| Tab {
id,
title: format!("Page {id}"),
developer_tool: None,
active: id == 32,
})
.collect();
let visible = items(None, &tabs, LEADING + NEW_TAB_SPACE + 720.0);
assert!(visible.iter().any(|item| item.tab.active));
for item in &visible {
let point = Point::new((item.rect.x + 12.0).max(LEADING + 3.0), 18.0);
assert_eq!(
hit(None, &tabs, LEADING + NEW_TAB_SPACE + 720.0, point),
Some((item.tab.id, close_rect(item.rect).contains(point)))
);
}
let tab = visible.iter().find(|item| item.tab.active).unwrap();
assert_eq!(
hit(
None,
&tabs,
LEADING + NEW_TAB_SPACE + 720.0,
Point::new(tab.rect.x + tab.rect.width - 15.0, 18.0)
),
Some((32, true))
);
assert_eq!(
hit(
None,
&tabs,
LEADING + NEW_TAB_SPACE + 720.0,
Point::new(LEADING + 50.0, HEIGHT)
),
None
);
}
#[test]
fn drag_viewport_reaches_hidden_ends_without_changing_active_page() {
let tabs: Vec<_> = (1..=64)
.map(|id| Tab {
id,
title: id.to_string(),
developer_tool: None,
active: id == 32,
})
.collect();
let width = LEADING + NEW_TAB_SPACE + 720.0;
let mut start = None;
while let Some(next) = scroll_start(&tabs, width, start, 1) {
start = Some(next);
}
assert_eq!(visible_range(&tabs, width, start), 55..64);
assert_eq!(
edge_direction(&tabs, width, start, Point::new(LEADING + 710.0, 18.0)),
0
);
assert_eq!(
insertion_index(start, &tabs, width, Point::new(LEADING + 710.0, 18.0)),
Some(64)
);
while let Some(next) = scroll_start(&tabs, width, start, -1) {
start = Some(next);
}
assert_eq!(visible_range(&tabs, width, start), 0..9);
assert_eq!(
edge_direction(&tabs, width, start, Point::new(LEADING + 10.0, 18.0)),
0
);
assert_eq!(
insertion_index(start, &tabs, width, Point::new(LEADING + 10.0, 18.0)),
Some(0)
);
assert_eq!(
tabs.iter()
.filter(|tab| tab.active)
.map(|tab| tab.id)
.collect::<Vec<_>>(),
vec![32]
);
assert!(items(None, &tabs, width).iter().any(|item| item.tab.active));
}
#[test]
fn scrolled_hit_and_gap_geometry_survive_resize_and_list_shrink() {
let tabs: Vec<_> = (1..=16)
.map(|id| Tab {
id,
title: id.to_string(),
developer_tool: None,
active: id == 1,
})
.collect();
let start = Some(4.0 * MIN_WIDTH);
assert_eq!(
hit(
start,
&tabs,
LEADING + NEW_TAB_SPACE + 720.0,
Point::new(LEADING + 40.0, 18.0)
),
Some((5, false))
);
assert_eq!(
insertion_index(
start,
&tabs,
LEADING + NEW_TAB_SPACE + 720.0,
Point::new(LEADING + 40.0, 18.0)
),
Some(4)
);
assert_eq!(
visible_range(&tabs[..3], LEADING + NEW_TAB_SPACE + 720.0, start),
0..3
);
assert_eq!(
visible_range(&tabs, LEADING + NEW_TAB_SPACE + 1920.0, start),
0..16
);
assert_eq!(
edge_direction(
&tabs,
LEADING + NEW_TAB_SPACE + 720.0,
start,
Point::new(LEADING + 710.0, HEIGHT)
),
0
);
assert_eq!(
edge_direction(
&tabs,
LEADING + NEW_TAB_SPACE + 720.0,
start,
Point::new(LEADING + 725.0, 18.0)
),
0
);
}
}
-63
View File
@@ -1,63 +0,0 @@
//! Hover color transitions are independent of tab layout and selected state.
use super::{Point, Tab, Visual};
use std::{collections::BTreeMap, time::Instant};
#[derive(Default)]
struct Fade {
from: f32,
target: f32,
started: Option<Instant>,
}
impl Fade {
fn sample(&mut self, hovered: bool, now: Instant) -> (f32, bool) {
let t = self.started.map_or(1.0, |start| {
(now.duration_since(start).as_secs_f32() / 0.16).min(1.0)
});
let value = self.from + (self.target - self.from) * (1.0 - (1.0 - t).powi(3));
let target = if hovered { 1.0 } else { 0.0 };
if target != self.target {
// Reversing mid-fade starts at the currently visible color.
self.from = value;
self.target = target;
self.started = Some(now);
(value, true)
} else {
(value, t < 1.0)
}
}
}
#[derive(Default)]
pub(super) struct Hover {
tabs: BTreeMap<u64, (Fade, Fade)>,
plus: Fade,
}
impl Hover {
pub fn sample(
&mut self,
visual: &mut Visual,
tabs: &[Tab],
pointer: Option<Point>,
now: Instant,
) -> bool {
let hit = pointer.and_then(|point| visual.hit(point));
let (plus, mut animating) = self.plus.sample(
pointer.is_some_and(|point| visual.plus.contains(point)),
now,
);
visual.plus_hover = plus;
self.tabs
.retain(|id, _| tabs.iter().any(|tab| tab.id == *id));
visual.hovers.clear();
for tab in tabs {
let (body, close) = self.tabs.entry(tab.id).or_default();
let (body, body_animating) = body.sample(hit.is_some_and(|hit| hit.0 == tab.id), now);
let (close, close_animating) = close.sample(hit == Some((tab.id, true)), now);
visual.hovers.push((tab.id, body, close));
animating |= body_animating || close_animating;
}
animating
}
}
-207
View File
@@ -1,207 +0,0 @@
//! Interpolated chrome geometry is shared by painting and pointer hit testing.
use super::*;
use std::time::{Duration, Instant};
#[derive(Clone, Default)]
pub struct Visual {
pub rects: Vec<(u64, Rect)>,
pub exiting: Vec<(Tab, Rect)>,
pub viewport: Rect,
pub plus: Rect,
pub hovers: Vec<(u64, f32, f32)>,
pub plus_hover: f32,
}
impl Visual {
pub fn hover(&self, id: u64) -> f32 {
self.hovers
.iter()
.find(|entry| entry.0 == id)
.map_or(0.0, |entry| entry.1)
}
pub fn close_hover(&self, id: u64) -> f32 {
self.hovers
.iter()
.find(|entry| entry.0 == id)
.map_or(0.0, |entry| entry.2)
}
pub fn rect(&self, id: u64, fallback: Rect) -> Rect {
self.rects
.iter()
.find(|(key, _)| *key == id)
.map_or(fallback, |(_, rect)| *rect)
}
pub fn hit(&self, point: Point) -> Option<(u64, bool)> {
if !self.viewport.contains(point) {
return None;
}
self.rects
.iter()
.rev()
.find(|(_, rect)| pill_rect(*rect).contains(point))
.map(|(id, rect)| (*id, close_rect(*rect).contains(point)))
}
}
#[derive(Default)]
pub struct Motion {
hover: super::hover::Hover,
target: Visual,
from: Visual,
current: Visual,
published: Vec<Tab>,
initialized: bool,
direct_scroll: bool,
started: Option<Instant>,
pub offset: Option<f32>,
pub next_frame: Option<Instant>,
}
fn blend(a: Rect, b: Rect, t: f32) -> Rect {
Rect::new(
a.x + (b.x - a.x) * t,
a.y + (b.y - a.y) * t,
a.width + (b.width - a.width) * t,
a.height + (b.height - a.height) * t,
)
}
impl Motion {
pub fn sample_hover(&mut self, visual: &mut Visual, tabs: &[Tab], pointer: Option<Point>) {
let now = Instant::now();
if self.hover.sample(visual, tabs, pointer, now) {
let next = now + Duration::from_millis(16);
self.next_frame = Some(self.next_frame.map_or(next, |old| old.min(next)));
}
}
pub fn scroll_to(&mut self, offset: f32) {
self.offset = Some(offset);
self.direct_scroll = true;
}
fn advance(&mut self, now: Instant) {
let t = self.started.map_or(1.0, |start| {
(now.duration_since(start).as_secs_f32() / 0.22).min(1.0)
});
let eased = 1.0 - (1.0 - t).powi(3);
self.current = Visual {
rects: self
.target
.rects
.iter()
.map(|(id, target)| (*id, blend(self.from.rect(*id, *target), *target, eased)))
.collect(),
exiting: self
.target
.exiting
.iter()
.filter(|_| t < 1.0)
.map(|(tab, target)| {
let from = self
.from
.exiting
.iter()
.find(|(old, _)| old.id == tab.id)
.map_or(*target, |(_, rect)| *rect);
(tab.clone(), blend(from, *target, eased))
})
.collect(),
viewport: blend(self.from.viewport, self.target.viewport, eased),
plus: blend(self.from.plus, self.target.plus, eased),
..Visual::default()
};
self.next_frame = (t < 1.0).then(|| now + Duration::from_millis(16));
}
pub fn sample(&mut self, tabs: &[Tab], offset: Option<f32>, width: f32) -> Visual {
let now = Instant::now();
// Retarget from the geometry at this instant, even during rapid repeated clicks.
self.advance(now);
let mut offset = scroll_offset(tabs, width, offset.or(self.offset));
let selection_changed = self
.published
.iter()
.find(|tab| tab.active)
.map(|tab| tab.id)
!= tabs.iter().find(|tab| tab.active).map(|tab| tab.id);
if selection_changed {
let active = tabs.iter().position(|tab| tab.active).unwrap_or(0) as f32;
let tab_width = tab_width(tabs, width);
let left = active * tab_width;
let right = left + tab_width;
offset = offset.min(left).max(right - viewport(width).width).max(0.0);
}
self.offset = Some(offset);
let mut target = Visual {
rects: tab_rects(Some(offset), tabs, width),
viewport: viewport(width),
plus: plus_rect(Some(offset), tabs, width),
..Visual::default()
};
if !self.initialized || self.direct_scroll {
self.direct_scroll = false;
self.started = None;
self.next_frame = None;
// Startup is already laid out; it is not an insertion of every restored tab.
self.initialized = true;
self.current = target.clone();
self.from = target.clone();
self.target = target;
self.published = tabs.to_vec();
return self.current.clone();
}
if self.target.rects != target.rects
|| self.target.plus != target.plus
|| self.target.viewport != target.viewport
{
self.from = self.current.clone();
for (index, (id, rect)) in target.rects.iter().enumerate() {
if !self.from.rects.iter().any(|(old, _)| old == id) {
// Grow out of the previous trailing edge, not the final compressed x.
let x = target.rects[..index]
.iter()
.rev()
.find_map(|(previous, _)| {
self.from
.rects
.iter()
.find(|(old, _)| old == previous)
.map(|(_, previous)| previous.x + previous.width)
})
.unwrap_or(rect.x);
self.from
.rects
.push((*id, Rect::new(x, rect.y, 0.0, rect.height)));
}
}
for tab in &self.published {
if !tabs.iter().any(|live| live.id == tab.id) {
self.from
.exiting
.push((tab.clone(), self.current.rect(tab.id, Rect::default())));
}
}
// A closed tab shrinks with the gap; it never remains an interactive target.
target.exiting = self
.from
.exiting
.iter()
.filter(|(tab, _)| !tabs.iter().any(|live| live.id == tab.id))
.map(|(tab, rect)| {
let next = self
.published
.iter()
.position(|old| old.id == tab.id)
.and_then(|index| {
self.published[index + 1..]
.iter()
.find(|old| tabs.iter().any(|live| live.id == old.id))
});
let x = next.map_or(target.plus.x - 4.0, |next| target.rect(next.id, *rect).x);
(tab.clone(), Rect::new(x, rect.y, 0.0, rect.height))
})
.collect();
self.target = target;
self.started = Some(now);
}
self.published = tabs.to_vec();
self.advance(now);
self.current.clone()
}
}