refactor: organize host modules and document architecture with UML
Verify Tessera GUI / verify (push) Failing after 2m2s

This commit is contained in:
2026-10-25 21:25:43 +08:00
parent 48fcb96f42
commit 18376793b0
85 changed files with 4450 additions and 3653 deletions
+90
View File
@@ -0,0 +1,90 @@
//! Bounded observation of this process's local HTTP API, never external traffic.
use std::{
collections::VecDeque,
sync::{Arc, Mutex},
time::{Instant, SystemTime, UNIX_EPOCH},
};
pub type Activity = Arc<Mutex<ActivityLog>>;
pub const BODY_PREVIEW: usize = 32 * 1024;
const MAX_RECORDS: usize = 80;
#[derive(Clone, Debug)]
pub struct Exchange {
pub id: u64,
pub method: String,
pub path: String,
pub origin: String,
pub timestamp: String,
pub request: String,
pub response: String,
pub status: Option<u16>,
pub elapsed_ms: u128,
pub request_headers: String,
pub response_headers: String,
started: Instant,
}
#[derive(Debug, Default)]
pub struct ActivityLog {
pub records: VecDeque<Exchange>,
next_id: u64,
}
impl ActivityLog {
pub fn begin(&mut self, method: String, path: String, origin: String, headers: String) -> u64 {
self.next_id += 1;
let id = self.next_id;
let seconds = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
% 86400;
self.records.push_back(Exchange {
id,
method,
path: preview(&path),
origin,
timestamp: format!(
"{:02}:{:02}:{:02} UTC",
seconds / 3600,
seconds / 60 % 60,
seconds % 60
),
request: String::new(),
response: String::new(),
status: None,
elapsed_ms: 0,
request_headers: preview(&headers),
response_headers: String::new(),
started: Instant::now(),
});
while self.records.len() > MAX_RECORDS {
self.records.pop_front();
}
id
}
pub fn body(&mut self, id: u64, body: &str) {
if let Some(record) = self.records.iter_mut().find(|r| r.id == id) {
record.request = preview(body);
}
}
pub fn finish(&mut self, id: u64, status: u16, body: &str, headers: String) {
if let Some(record) = self.records.iter_mut().find(|r| r.id == id) {
record.status = Some(status);
record.response = preview(body);
record.elapsed_ms = record.started.elapsed().as_millis();
record.response_headers = preview(&headers);
}
}
}
pub fn preview(value: &str) -> String {
if value.len() <= BODY_PREVIEW {
return value.to_owned();
}
let mut end = BODY_PREVIEW;
while !value.is_char_boundary(end) {
end -= 1;
}
format!("{}\n[preview truncated at 32 KiB]", &value[..end])
}
+1582
View File
File diff suppressed because it is too large Load Diff
+52
View File
@@ -0,0 +1,52 @@
//! Clipboard text is always UTF-8, including Finder/LaunchServices launches without LANG.
use anyhow::{Result, bail};
#[cfg(target_os = "macos")]
fn command(program: &str) -> std::process::Command {
let mut cmd = std::process::Command::new(program);
cmd.env("LC_ALL", "en_US.UTF-8")
.env("LC_CTYPE", "en_US.UTF-8")
.env("LANG", "en_US.UTF-8");
cmd
}
pub fn read() -> Result<String> {
#[cfg(target_os = "macos")]
{
let output = command("/usr/bin/pbpaste")
.arg("-Prefer")
.arg("txt")
.output()?;
if !output.status.success() {
bail!("system clipboard read failed");
}
// Never silently replace invalid bytes in the user's source.
Ok(String::from_utf8(output.stdout)?)
}
#[cfg(not(target_os = "macos"))]
{
bail!("system clipboard adapter is not available on this platform")
}
}
pub fn write(value: &str) -> Result<()> {
#[cfg(target_os = "macos")]
{
use std::io::Write;
let mut child = command("/usr/bin/pbcopy")
.stdin(std::process::Stdio::piped())
.spawn()?;
let mut stdin = child
.stdin
.take()
.ok_or_else(|| anyhow::anyhow!("clipboard stdin is unavailable"))?;
stdin.write_all(value.as_bytes())?;
drop(stdin);
if !child.wait()?.success() {
bail!("system clipboard write failed");
}
Ok(())
}
#[cfg(not(target_os = "macos"))]
{
let _ = value;
bail!("system clipboard adapter is not available on this platform")
}
}
File diff suppressed because it is too large Load Diff
+198
View File
@@ -0,0 +1,198 @@
use super::*;
pub(super) fn build(
p: &mut Painter,
state: &mut DeveloperToolsState,
records: &[Exchange],
viewport: Rect,
) {
let x = viewport.x;
let w = viewport.width;
let bottom = viewport.height - 22.0;
p.fill(Rect::new(x, 32.0, w, 30.0), BAR);
p.enabled_button(
Rect::new(x + 3.0, 32.0, 62.0, 29.0),
"Clear",
Action::ClearConsole,
records.iter().any(|r| {
r.id > state.console_after
&& matches!(r.method.as_str(), "PUT" | "POST" | "DELETE")
&& !r.path.ends_with("/events")
}),
);
p.button(
Rect::new(x + 68.0, 32.0, 106.0, 29.0),
if state.follow {
"Follow: on"
} else {
"Follow: off"
},
Action::Follow,
state.follow,
);
p.button(
Rect::new(x + 181.0, 32.0, 119.0, 29.0),
"Reset session",
Action::ResetSession,
false,
);
if w > 520.0 {
p.label(x + 309.0, 39.0, "app.main · live objects", MUTED, false);
}
let mut lines = Vec::new();
for r in records.iter().filter(|r| {
r.id > state.console_after
&& (r.method == "PUT" || r.method == "POST" || r.method == "DELETE")
&& !r.path.ends_with("/events")
}) {
let kind = if r.path.ends_with("/repl") {
if r.method == "DELETE" {
"RESET SESSION"
} else {
"REPL · live objects"
}
} else if r.path.ends_with("/evaluate") {
"ISOLATED API EVALUATION"
} else if r.method == "PUT" {
"FULL SOURCE · live program"
} else {
"CLEAR DOCUMENT"
};
let local = r.origin == "Console" && r.path.ends_with("/repl") && r.method == "POST";
if !local {
let mut title = Line::new(
format!("#{} {} {} {}", r.id, r.timestamp, r.origin, kind),
MUTED,
);
title.divider = Some(Divider::Accent);
title.action = Some(Action::Request(r.id));
lines.push(title);
}
for (i, line) in r.request.split('\n').enumerate() {
lines.push(Line::new(
format!("{}{line}", if i == 0 { "> " } else { " " }),
TEXT,
));
}
let color = if r.status.is_some_and(|s| s >= 400) {
ERROR
} else {
OK
};
if let Some(status) = r.status {
if !local {
lines.push(Line::new(
format!("‹ {status} · {} ms", r.elapsed_ms),
color,
));
}
console_result(&mut lines, &r.response, color);
} else {
lines.push(Line::new(" Executing…", MUTED));
}
let mut separator = Line::new("", MUTED);
separator.divider = Some(Divider::Neutral);
lines.push(separator);
}
if lines.is_empty() {
multiline(
&mut lines,
"Endor · live session\nCreate objects here; call page.render(...) to display.\n",
MUTED,
);
}
use std::hash::{Hash, Hasher};
let mut hash = std::collections::hash_map::DefaultHasher::new();
for line in &lines {
line.value.hash(&mut hash);
}
let stamp = hash.finish();
let output_changed = stamp != state.console_stamp;
state.console_stamp = stamp;
let first_input = lines.len();
let area = Rect::new(x + 4.0, 63.0, w - 5.0, (bottom - 88.0).max(1.0));
let mut input = state.input.clone();
if state.focus == Some(Focus::Input) {
input.insert_str(state.cursor, &state.preedit);
}
for (i, line) in input.split('\n').enumerate() {
let mut line = Line::new(format!("{}{line}", if i == 0 { "> " } else { " " }), TEXT);
line.selected = state.selection && state.focus == Some(Focus::Input);
lines.push(line);
}
let prefix = text::measure("> ", TextStyle::code()).width;
let before = &state.input[..state.cursor];
let row = before.matches('\n').count() as f32;
let column = before.rsplit('\n').next().unwrap_or("");
let caret_x =
prefix + text::measure(&format!("{column}{}", state.preedit), TextStyle::code()).width;
let caret_y = (first_input as f32 + row) * ROW;
let follow = state.follow && output_changed && !state.reveal_input;
if state.reveal_input {
let s = &mut state.scroll[Region::Transcript as usize];
s.y = s.y.clamp(
(caret_y + ROW + 16.0 - area.height).max(0.0).min(caret_y),
caret_y,
);
s.x = s.x.clamp((caret_x + 24.0 - area.width).max(0.0), caret_x);
state.reveal_input = false;
}
p.lines(area, Region::Transcript, &lines, state, follow);
let scroll = state.scroll[Region::Transcript as usize];
let origin = Point::new(
area.x + 8.0 + prefix - scroll.x,
area.y + 5.0 + first_input as f32 * ROW - scroll.y,
);
p.layout.input = Some(ConsoleInputLayout {
viewport: area,
origin,
});
let input_top = origin.y.max(area.y);
let input_bottom =
(origin.y + state.input.split('\n').count() as f32 * ROW).min(area.y + area.height - 9.0);
if input_bottom > input_top {
p.ui.inline_input(
Rect::new(
area.x,
input_top,
(area.width - 9.0).max(0.0),
input_bottom - input_top,
),
Action::Focus(Focus::Input),
);
}
if state.focus == Some(Focus::Input) {
p.ui.list.push(DrawCommand::PushClip(Rect::new(
area.x,
area.y,
(area.width - 9.0).max(0.0),
(area.height - 9.0).max(0.0),
)));
p.fill(
Rect::new(
area.x + 8.0 + caret_x - scroll.x,
origin.y + row * ROW + 1.0,
1.0,
ROW - 2.0,
),
TEXT,
);
p.ui.list.push(DrawCommand::PopClip);
}
p.label(
x + 10.0,
bottom - 23.0,
if state.input_error.is_empty() {
"Enter: run · Shift+Enter: newline · ⌘/Ctrl+↑↓: history"
} else {
&state.input_error
},
if state.input_error.is_empty() {
MUTED
} else {
ERROR
},
false,
);
}
+119
View File
@@ -0,0 +1,119 @@
use super::*;
pub(super) fn build(
p: &mut Painter,
state: &mut DeveloperToolsState,
records: &[Exchange],
viewport: Rect,
) {
let x = viewport.x;
let w = viewport.width;
let bottom = viewport.height - 22.0;
p.fill(Rect::new(x, 32.0, w, 30.0), BAR);
p.enabled_button(
Rect::new(x + 3.0, 32.0, 62.0, 29.0),
"Clear",
Action::ClearNetwork,
records.iter().any(|r| r.id > state.network_after),
);
let filter_area = Rect::new(x + 72.0, 35.0, (w - 85.0).max(100.0), 24.0);
p.ui.text_field(
filter_area,
Action::Focus(Focus::Filter),
state.focus == Some(Focus::Filter),
);
p.label(
filter_area.x + 7.0,
filter_area.y + 3.0,
&format!(
"Filter: {}{}",
state.filter,
if state.focus == Some(Focus::Filter) {
"│"
} else {
""
}
),
MUTED,
false,
);
p.label(
x + 10.0,
69.0,
"METHOD STATUS TIME PATH",
MUTED,
true,
);
let divider = 92.0 + (bottom - 92.0) * state.network_fraction;
let filter = state.filter.to_lowercase();
let visible = records
.iter()
.filter(|r| r.id > state.network_after)
.filter(|r| {
format!(
"{} {} {}",
r.method,
r.path,
r.status.map_or("pending".into(), |s| s.to_string())
)
.to_lowercase()
.contains(&filter)
})
.collect::<Vec<_>>();
let mut lines = Vec::new();
for r in &visible {
let mut l = Line::new(
format!(
"{:<7} {:<6} {:>5} ms {}",
r.method,
r.status.map_or("…".into(), |s| s.to_string()),
r.elapsed_ms,
r.path
),
if r.status.is_some_and(|s| s >= 400) {
ERROR
} else {
TEXT
},
);
l.selected = state.selected_request == Some(r.id);
l.action = Some(Action::Request(r.id));
lines.push(l);
}
if lines.is_empty() {
lines.push(Line::new(
"No matching requests. Listening to Tessera's local API.",
MUTED,
));
}
p.lines(
Rect::new(x + 1.0, 92.0, w - 2.0, divider - 92.0),
Region::Requests,
&lines,
state,
false,
);
p.split(Rect::new(x + 1.0, divider, w - 2.0, 1.0), Split::Network);
let selected = records
.iter()
.find(|r| Some(r.id) == state.selected_request);
let mut details = Vec::new();
if let Some(r) = selected {
request_details(&mut details, r);
} else {
multiline(
&mut details,
"Select a request to inspect headers and bodies.\n\nCapture scope: 127.0.0.1:4737 in this Tessera process.\n80 most recent requests; body previews up to 32 KiB.\nOnly Content-Type and Content-Length request headers are recorded.\nExternal browser / OS traffic is not captured.",
MUTED,
);
}
p.lines(
Rect::new(x + 1.0, divider + 5.0, w - 2.0, bottom - divider - 5.0),
Region::Details,
&details,
state,
false,
);
}
+308
View File
@@ -0,0 +1,308 @@
use super::*;
pub(super) struct Painter {
pub(super) ui: Ui<Action>,
pub(super) layout: DeveloperToolsLayout,
}
impl Painter {
pub(super) fn fill(&mut self, r: Rect, c: Color) {
self.ui.fill(r, c);
}
pub(super) fn label(&mut self, x: f32, y: f32, value: &str, c: Color, code: bool) {
self.ui.label(x, y, value, c, code);
}
pub(super) fn button(&mut self, r: Rect, label: &str, action: Action, active: bool) {
let role = match action {
Action::Follow | Action::Snapshot | Action::Cloud => Role::Toggle,
_ => Role::Button,
};
self.ui
.button(r, action, Button::new(label).selected(active).role(role));
}
pub(super) fn enabled_button(&mut self, r: Rect, label: &str, action: Action, enabled: bool) {
self.ui
.button(r, action, Button::new(label).enabled(enabled));
}
pub(super) fn split(&mut self, r: Rect, kind: Split) {
// Paint and register splitters after all pane content, in one overlay pass.
self.layout.splits.push((r, kind));
}
pub(super) fn lines(
&mut self,
area: Rect,
region: Region,
lines: &[Line],
state: &mut DeveloperToolsState,
follow: bool,
) {
let content_h = lines.len() as f32 * ROW + 12.0;
use std::hash::{Hash, Hasher};
let mut hash = std::collections::hash_map::DefaultHasher::new();
for line in lines {
line.value.hash(&mut hash);
}
let fingerprint = hash.finish();
let cache = &mut state.widths[region as usize];
let content_w = match *cache {
Some((previous, width)) if previous == fingerprint => width,
_ => {
let width = lines
.iter()
.map(|line| text::measure(&line.value, TextStyle::code()).width + 20.0)
.fold(0.0_f32, f32::max);
*cache = Some((fingerprint, width));
width
}
};
let s = &mut state.scroll[region as usize];
s.y = if follow {
(content_h - area.height + 12.0).max(0.0)
} else {
s.y.clamp(0.0, (content_h - area.height + 12.0).max(0.0))
};
s.x = s.x.clamp(0.0, (content_w - area.width + 12.0).max(0.0));
self.ui.list.push(DrawCommand::PushClip(Rect::new(
area.x,
area.y,
(area.width - 9.0).max(0.0),
(area.height - 9.0).max(0.0),
)));
if region == Region::Source {
let values = lines
.iter()
.map(|line| line.value.chars().skip(7).collect::<String>())
.collect::<Vec<_>>();
state.source_selection.set_lines(&values);
self.layout.source = Some((
area,
Point::new(
area.x + 8.0 - s.x + text::measure(" ", TextStyle::code()).width,
area.y + 5.0 - s.y,
),
values,
));
}
let first = (s.y / ROW).floor() as usize;
let count = (area.height / ROW).ceil() as usize + 2;
for (i, line) in lines.iter().enumerate().skip(first).take(count) {
let y = area.y + 5.0 + i as f32 * ROW - s.y;
if let Some(divider) = line.divider {
self.fill(
Rect::new(area.x, y, area.width, 1.0),
match divider {
Divider::Accent => self.ui.theme.accent,
Divider::Neutral => BORDER,
},
);
}
let paint = Rect::new(area.x, y, area.width, ROW);
if let Some(action) = &line.action {
let top = y.max(area.y);
let bottom = (y + ROW).min(area.y + area.height - 9.0);
if bottom > top {
self.ui.row(
paint,
Rect::new(area.x, top, area.width - 9.0, bottom - top),
action.clone(),
line.selected,
);
}
} else if line.selected {
self.fill(paint, self.ui.theme.soft());
}
if region == Region::Source
&& let Some((_, origin, values)) = &self.layout.source
&& let Some((left, right)) = state.source_selection.span(
i,
state.selection && state.focus == Some(Focus::Source),
values,
)
{
self.fill(
Rect::new(origin.x + left, y, right - left, ROW),
self.ui.theme.hover(),
);
}
self.label(area.x + 8.0 - s.x, y, &line.value, line.color, true);
}
self.ui.list.push(DrawCommand::PopClip);
self.layout
.regions
.push((area, region, content_w, content_h));
self.scrollbar(area, region, false, s.y, content_h);
self.scrollbar(area, region, true, s.x, content_w);
}
pub(super) fn scrollbar(
&mut self,
r: Rect,
region: Region,
h: bool,
offset: f32,
content: f32,
) {
let viewport = if h { r.width } else { r.height } - 10.0;
if content <= viewport || viewport <= 0.0 {
return;
}
let length = (viewport * viewport / content).max(24.0).min(viewport);
let travel = (viewport - length).max(1.0);
let maximum = (content - viewport).max(1.0);
let position = (offset / maximum).clamp(0.0, 1.0) * travel;
let track = if h {
Rect::new(r.x, r.y + r.height - 8.0, viewport, 8.0)
} else {
Rect::new(r.x + r.width - 8.0, r.y, 8.0, viewport)
};
self.fill(track, BAR);
let thumb = if h {
Rect::new(track.x + position, track.y + 1.0, length, 6.0)
} else {
Rect::new(track.x + 1.0, track.y + position, 6.0, length)
};
self.ui.scrollbar(
thumb,
WidgetId::new(("scroll", region, h)),
if h { Axis::Horizontal } else { Axis::Vertical },
);
self.layout
.thumbs
.push((thumb, region, h, maximum / travel));
}
}
#[derive(Clone)]
pub(super) struct Line {
pub(super) value: String,
pub(super) color: Color,
pub(super) divider: Option<Divider>,
pub(super) selected: bool,
pub(super) action: Option<Action>,
}
#[derive(Clone, Copy)]
pub(super) enum Divider {
Accent,
Neutral,
}
impl Line {
pub(super) fn new(value: impl Into<String>, color: Color) -> Self {
Self {
value: value.into(),
color,
divider: None,
selected: false,
action: None,
}
}
}
pub(super) fn multiline(out: &mut Vec<Line>, value: &str, color: Color) {
out.extend(
value
.replace('\t', " ")
.split('\n')
.map(|s| Line::new(s, color)),
);
}
pub(super) fn console_result(out: &mut Vec<Line>, body: &str, color: Color) {
if let Ok(value) = serde_json::from_str::<serde_json::Value>(body) {
if value["execution"] == "repl" {
out.push(Line::new(
if value["rendered"] == true {
format!(
"Rendered revision {} · session {}",
value["revision"], value["session"]
)
} else {
format!(
"Session {} · retained in memory; page unchanged",
value["session"]
)
},
MUTED,
));
}
if value["session_reset"] == true {
multiline(
out,
value["message"]
.as_str()
.or(value["error"].as_str())
.unwrap_or("Session reset"),
color,
);
return;
}
if let Some(result) = value["value"].as_str() {
multiline(out, result, color);
return;
}
if let Some(diagnostics) = value["diagnostics"].as_array()
&& !diagnostics.is_empty()
{
for d in diagnostics {
if let Some(line) = d["line"].as_u64() {
out.push(Line::new(
format!("Error · line {line}, column {}", d["column"]),
color,
));
}
multiline(
out,
d["message"].as_str().unwrap_or("Execution failed"),
color,
);
}
return;
}
if let Some(error) = value["error"].as_str() {
multiline(out, error, color);
return;
}
if let Some(revision) = value["revision"].as_u64() {
out.push(Line::new(format!("Committed revision {revision}"), color));
return;
}
}
multiline(out, body, color);
}
pub(super) fn flatten<'a>(node: &'a CodeNode, depth: usize, out: &mut Vec<(usize, &'a CodeNode)>) {
out.push((depth, node));
for child in &node.children {
flatten(child, depth + 1, out);
}
}
pub(super) fn request_details(out: &mut Vec<Line>, r: &Exchange) {
multiline(
out,
&format!(
"#{} {} {}\n{} · {} · {} ms\nStatus: {}",
r.id,
r.method,
r.path,
r.timestamp,
r.origin,
r.elapsed_ms,
r.status.map_or("pending".into(), |s| s.to_string())
),
TEXT,
);
for (title, body) in [
("REQUEST HEADERS", &r.request_headers),
("REQUEST BODY", &r.request),
("RESPONSE HEADERS", &r.response_headers),
("RESPONSE BODY", &r.response),
] {
out.push(Line::new("", MUTED));
let mut l = Line::new(title, MUTED);
l.divider = Some(Divider::Accent);
out.push(l);
multiline(
out,
if body.is_empty() { "(empty)" } else { body },
if title == "RESPONSE BODY" && r.status.is_some_and(|s| s >= 400) {
ERROR
} else {
TEXT
},
);
}
}
+151
View File
@@ -0,0 +1,151 @@
//! Read-only, grapheme-aware source selection, independent of console editing.
use crate::{
geometry::Point,
text::{self, TextStyle},
};
use unicode_segmentation::UnicodeSegmentation;
#[derive(Debug, Default)]
pub(super) struct SourceSelection {
lines: Vec<String>,
anchor: (usize, usize),
end: (usize, usize),
pub dragging: bool,
}
impl SourceSelection {
pub fn set_lines(&mut self, lines: &[String]) {
if self.lines != lines {
self.lines = lines.to_vec();
self.anchor = (0, 0);
self.end = (0, 0);
self.dragging = false;
}
}
fn locate(p: Point, origin: Point, lines: &[String]) -> (usize, usize) {
let row = (((p.y - origin.y) / super::ROW).floor().max(0.0) as usize)
.min(lines.len().saturating_sub(1));
let Some(line) = lines.get(row) else {
return (0, 0);
};
let x = (p.x - origin.x).max(0.0);
let mut byte = line.len();
for (i, g) in line.grapheme_indices(true) {
let left = text::measure(&line[..i], TextStyle::code()).width;
let right = text::measure(&line[..i + g.len()], TextStyle::code()).width;
if x < (left + right) * 0.5 {
byte = i;
break;
}
}
(row, byte)
}
pub fn begin(&mut self, p: Point, origin: Point, lines: &[String]) {
self.anchor = Self::locate(p, origin, lines);
self.end = self.anchor;
self.dragging = true;
}
pub fn extend(&mut self, p: Point, origin: Point, lines: &[String]) {
self.end = Self::locate(p, origin, lines);
}
pub fn navigate(
&mut self,
key: &winit::keyboard::NamedKey,
shift: bool,
command: bool,
) -> Option<usize> {
use winit::keyboard::NamedKey::*;
let (mut row, mut byte) = self.end;
let line = self.lines.get(row)?;
match key {
ArrowLeft => {
if byte > 0 {
byte = line[..byte]
.grapheme_indices(true)
.next_back()
.map_or(0, |(i, _)| i);
} else if row > 0 {
row -= 1;
byte = self.lines[row].len();
}
}
ArrowRight => {
if byte < line.len() {
byte += line[byte..].graphemes(true).next().map_or(0, str::len);
} else if row + 1 < self.lines.len() {
row += 1;
byte = 0;
}
}
ArrowUp | ArrowDown => {
let col = line[..byte].graphemes(true).count();
row = if *key == ArrowUp {
row.saturating_sub(1)
} else {
(row + 1).min(self.lines.len() - 1)
};
byte = self.lines[row]
.graphemes(true)
.take(col)
.map(str::len)
.sum();
}
Home => {
if command {
row = 0;
}
byte = 0;
}
End => {
if command {
row = self.lines.len() - 1;
}
byte = self.lines[row].len();
}
_ => return None,
}
self.end = (row, byte);
if !shift {
self.anchor = self.end;
}
Some(row)
}
fn range(&self, all: bool) -> ((usize, usize), (usize, usize)) {
if all {
return (
(0, 0),
(
self.lines.len().saturating_sub(1),
self.lines.last().map_or(0, String::len),
),
);
}
(self.anchor.min(self.end), self.anchor.max(self.end))
}
pub fn text(&self, all: bool) -> String {
let (a, b) = self.range(all);
self.lines
.iter()
.enumerate()
.filter(|(i, _)| *i >= a.0 && *i <= b.0)
.map(|(i, line)| {
let start = if i == a.0 { a.1 } else { 0 };
let end = if i == b.0 { b.1 } else { line.len() };
line.get(start..end).unwrap_or("").to_owned()
})
.collect::<Vec<_>>()
.join("\n")
}
pub fn span(&self, row: usize, all: bool, lines: &[String]) -> Option<(f32, f32)> {
let (a, b) = self.range(all);
if row < a.0 || row > b.0 || a == b {
return None;
}
let line = lines.get(row)?;
let start = if row == a.0 { a.1 } else { 0 };
let end = if row == b.0 { b.1 } else { line.len() };
Some((
text::measure(line.get(..start)?, TextStyle::code()).width,
text::measure(line.get(..end)?, TextStyle::code()).width,
))
}
}
+63
View File
@@ -0,0 +1,63 @@
use super::*;
pub(super) fn build(p: &mut Painter, state: &mut DeveloperToolsState, viewport: Rect) {
let x = viewport.x;
let w = viewport.width;
p.label(x + 24.0, 62.0, "Appearance", TEXT, false);
p.label(
x + 24.0,
90.0,
"Accent color · tabs, focus and execution separators",
MUTED,
false,
);
for (i, color) in PALETTE.iter().enumerate() {
let r = Rect::new(x + 24.0 + i as f32 * 44.0, 122.0, 32.0, 32.0);
p.ui.swatch(r, Action::Theme(i), *color, *color == state.accent);
}
p.label(
x + 24.0,
176.0,
"Custom hex · Enter to apply (bright colors adjusted)",
MUTED,
false,
);
let custom = Rect::new(x + 24.0, 204.0, 200.0, 32.0);
p.ui.text_field(
custom,
Action::Focus(Focus::Custom),
state.focus == Some(Focus::Custom),
);
p.label(
custom.x + 10.0,
custom.y + 6.0,
&format!(
"{}{}",
state.custom,
if state.focus == Some(Focus::Custom) {
"│"
} else {
""
}
),
TEXT,
true,
);
if !state.input_error.is_empty() {
p.label(x + 24.0, 245.0, &state.input_error, ERROR, false);
}
p.fill(Rect::new(x + 24.0, 285.0, w - 48.0, 1.0), BORDER);
p.label(x + 24.0, 305.0, "Theme preview", TEXT, false);
p.fill(Rect::new(x + 24.0, 340.0, w - 48.0, 2.0), state.accent);
p.label(x + 32.0, 353.0, "› \"Hello\"", TEXT, true);
p.label(x + 32.0, 380.0, "‹ \"Hello\"", OK, true);
p.label(
x + 24.0,
430.0,
"Settings last for this window session. Source is not persisted.",
MUTED,
false,
);
}
+145
View File
@@ -0,0 +1,145 @@
use super::*;
pub(super) fn build(
p: &mut Painter,
state: &mut DeveloperToolsState,
doc: &RenderDocument,
viewport: Rect,
) {
let x = viewport.x;
let w = viewport.width;
let width = viewport.x + viewport.width;
let bottom = viewport.height - 22.0;
p.fill(Rect::new(x, 32.0, w, 30.0), BAR);
p.button(
Rect::new(x + 3.0, 32.0, 139.0, 29.0),
"Current snapshot",
Action::Snapshot,
!state.cloud,
);
p.button(
Rect::new(x + 145.0, 32.0, 107.0, 29.0),
"Cloud files",
Action::Cloud,
state.cloud,
);
if state.cloud {
p.button(
Rect::new(width - 92.0, 32.0, 88.0, 29.0),
"Refresh",
Action::CloudRefresh,
false,
);
let tree = state.tree_width.clamp(120.0, (w - 180.0).max(120.0));
let code_x = x + tree + 2.0;
p.label(x + 10.0, 69.0, "CLOUD FILES", MUTED, false);
let file_lines = state
.cloud_sources
.files
.iter()
.map(|file| {
let mut l = Line::new(&file.path, TEXT);
l.action = Some(Action::CloudOpen(file.id.clone()));
l
})
.collect::<Vec<_>>();
p.lines(
Rect::new(x + 1.0, 92.0, tree - 1.0, bottom - 92.0),
Region::Tree,
&file_lines,
state,
false,
);
p.split(Rect::new(x + tree, 63.0, 1.0, bottom - 63.0), Split::Tree);
let mut source_lines = Vec::new();
if let Some(source) = &state.cloud_sources.opened {
p.label(code_x + 10.0, 69.0, &source.path, MUTED, false);
for (i, line) in source.code.split('\n').enumerate() {
source_lines.push(Line::new(format!("{:>5} {}", i + 1, line), TEXT));
}
} else {
multiline(
&mut source_lines,
"No cloud file open\n\nNo provider connected.\nCloud files will open here as full source.\nCurrent snapshot contains your last successful script.",
MUTED,
);
}
if !state.cloud_sources.error.is_empty() {
source_lines.push(Line::new(&state.cloud_sources.error, ERROR));
}
p.lines(
Rect::new(code_x, 92.0, width - code_x, bottom - 92.0),
Region::Source,
&source_lines,
state,
false,
);
} else {
let tree = state.tree_width.clamp(120.0, (w - 180.0).max(120.0));
let code_x = x + tree + 2.0;
p.label(x + 10.0, 69.0, "ASTER AST", MUTED, false);
p.label(
code_x + 10.0,
69.0,
&format!(
"{} · {} lines · read only",
if doc
.root
.as_ref()
.is_some_and(|root| root.kind == "repl-session")
{
"Console transcript"
} else {
"app.main.endor"
},
doc.source.split('\n').count()
),
MUTED,
false,
);
let mut tree_lines = Vec::new();
if let Some(root) = &doc.root {
let mut flat = Vec::new();
flatten(root, 0, &mut flat);
for (depth, n) in flat {
let mut l = Line::new(format!("{}{} {}", " ".repeat(depth), n.kind, n.name), TEXT);
l.selected = state.selected_node_id.as_deref() == Some(&n.id);
l.action = Some(Action::Node(n.id.clone(), n.start_line));
tree_lines.push(l);
}
} else {
tree_lines.push(Line::new("No submitted source", MUTED));
}
p.lines(
Rect::new(x + 1.0, 92.0, tree - 1.0, bottom - 92.0),
Region::Tree,
&tree_lines,
state,
false,
);
p.split(Rect::new(x + tree, 63.0, 1.0, bottom - 63.0), Split::Tree);
let selected = state
.selected_node_id
.as_deref()
.and_then(|id| doc.node(id));
let code_lines = doc
.source
.replace("\r\n", "\n")
.split('\n')
.enumerate()
.map(|(i, s)| {
let mut l = Line::new(format!("{:>5} {}", i + 1, s.replace('\t', " ")), TEXT);
l.selected = selected.is_some_and(|n| i + 1 >= n.start_line && i < n.end_line);
l
})
.collect::<Vec<_>>();
p.lines(
Rect::new(code_x, 92.0, width - code_x, bottom - 92.0),
Region::Source,
&code_lines,
state,
false,
);
}
}
+10
View File
@@ -0,0 +1,10 @@
// Module ownership follows the directory; crate-root aliases keep internal call sites stable.
pub(crate) mod activity;
pub(crate) mod app;
pub(crate) mod clipboard;
pub(crate) mod developer_tools;
#[cfg(target_os = "macos")]
pub(crate) mod native_chrome;
pub(crate) mod sources;
pub(crate) mod system_ui;
pub(crate) mod tabs;
+97
View File
@@ -0,0 +1,97 @@
//! Keep AppKit's real window buttons aligned with the custom tab strip.
use objc2_app_kit::{NSApplication, NSView, NSWindowButton, NSWindowStyleMask};
use objc2_foundation::{MainThreadMarker, NSPoint, NSString, NSUserDefaults};
use winit::{
raw_window_handle::{HasWindowHandle, RawWindowHandle},
window::Window,
};
/// The custom draggable row does not receive AppKit's titlebar double-click
/// action automatically. Use the native click count and native window actions.
pub fn titlebar_double_click(window: &Window) -> bool {
let Some(main_thread) = MainThreadMarker::new() else {
return false;
};
let Ok(handle) = window.window_handle() else {
return false;
};
let RawWindowHandle::AppKit(handle) = handle.as_raw() else {
return false;
};
// SAFETY: called on the event-loop thread during a left-button press, with
// a live winit-owned NSView. No native object outlives the Window borrow.
unsafe {
let Some(event) = NSApplication::sharedApplication(main_thread).currentEvent() else {
return false;
};
if event.clickCount() != 2 {
return false;
}
let view = &*handle.ns_view.as_ptr().cast::<NSView>();
let Some(native) = view.window() else {
return false;
};
if native.styleMask().contains(NSWindowStyleMask::FullScreen) {
return true;
}
let action = NSUserDefaults::standardUserDefaults()
.stringForKey(&NSString::from_str("AppleActionOnDoubleClick"))
.map(|value| value.to_string());
match action.as_deref() {
Some("Minimize") => native.performMiniaturize(None),
None | Some("Maximize" | "Fill") => native.performZoom(None),
// Respect disabled/unrecognized system actions without moving it.
_ => {}
}
}
true
}
/// Called only on winit's main thread, after native creation and before drawing.
/// AppKit can restore its default button positions when laying out the title bar.
pub fn align_controls(window: &Window) {
let Ok(handle) = window.window_handle() else {
return;
};
let RawWindowHandle::AppKit(handle) = handle.as_raw() else {
return;
};
// SAFETY: winit owns this NSView for the lifetime of the borrowed Window.
// All AppKit access is on the event-loop thread; no native pointers escape.
unsafe {
let view = &*handle.ns_view.as_ptr().cast::<NSView>();
let Some(native) = view.window() else {
return;
};
// Fullscreen traffic lights belong to AppKit's separate floating toolbar.
if native.styleMask().contains(NSWindowStyleMask::FullScreen) {
return;
}
let bounds = view.bounds();
let center = f64::from(crate::tabs::HEIGHT) / 2.0;
let content_y = if view.isFlipped() {
bounds.origin.y + center
} else {
bounds.origin.y + bounds.size.height - center
};
for kind in [
NSWindowButton::NSWindowCloseButton,
NSWindowButton::NSWindowMiniaturizeButton,
NSWindowButton::NSWindowZoomButton,
] {
let Some(button) = native.standardWindowButton(kind) else {
continue;
};
let Some(parent) = button.superview() else {
continue;
};
let target = parent.convertPoint_fromView(NSPoint::new(0.0, content_y), Some(view));
let frame = button.frame();
let y = target.y - frame.size.height / 2.0;
// Preserve native button size, horizontal spacing and behavior.
if (frame.origin.y - y).abs() > 0.01 {
button.setFrameOrigin(NSPoint::new(frame.origin.x, y));
}
}
}
}
+53
View File
@@ -0,0 +1,53 @@
//! Cloud source integration seam. The host installs a provider when one exists;
//! the default workspace stays disconnected and never fabricates or stores files.
use anyhow::Result;
#[derive(Clone, Debug)]
pub struct SourceFile {
pub id: String,
pub path: String,
}
#[derive(Clone, Debug)]
pub struct OpenedSource {
pub path: String,
pub code: String,
}
pub trait CloudSourceProvider: std::fmt::Debug + Send {
fn list_files(&mut self) -> Result<Vec<SourceFile>>;
fn open_file(&mut self, id: &str) -> Result<OpenedSource>;
}
#[derive(Debug, Default)]
pub struct SourceWorkspace {
pub provider: Option<Box<dyn CloudSourceProvider>>,
pub files: Vec<SourceFile>,
pub opened: Option<OpenedSource>,
pub error: String,
}
impl SourceWorkspace {
pub fn refresh(&mut self) {
let Some(provider) = &mut self.provider else {
self.error = "No cloud file provider configured".into();
return;
};
match provider.list_files() {
Ok(files) => {
self.files = files;
self.error.clear();
}
Err(error) => self.error = error.to_string(),
}
}
pub fn open(&mut self, id: &str) {
let Some(provider) = &mut self.provider else {
return;
};
match provider.open_file(id) {
Ok(source) => {
self.opened = Some(source);
self.error.clear();
}
Err(error) => self.error = error.to_string(),
}
}
}
+66
View File
@@ -0,0 +1,66 @@
# Tessera System UI
An internal Rust widget library for Tessera's own management windows and developer
tools. It is independent of Endor's `ui` global, `UiNode`, AST and VM. Guest scripts
cannot construct or control these management widgets. Only geometry, font shaping
and display-list rendering are shared with the page renderer.
## Modules
- `interaction.rs`: stable semantic widget IDs, hit testing, pointer capture,
release-inside activation, drag-out cancellation, keyboard focus traversal,
Enter/Space activation, disabled controls and cursor roles.
- `theme.rs`: neutral/error/success colors, accent presets, readable custom accents
and shared idle/hover/pressed/selected colors.
- `widgets.rs`: button, tab, toggle, text field chrome, borderless inline prompt target, selectable row, color swatch,
splitter and scrollbar thumb. Text is clipped to its widget bounds. Hover, pressed,
selection, keyboard focus and disabled states compose consistently.
- `mod.rs`: public interface used by management surfaces.
## Frame contract
All widget coordinates are logical pixels. Build a `Ui<Action>` from the current
`Theme` and a clone of retained `Interaction`. Actions are host-defined, `Hash`able
values; IDs come from semantic action keys, never screen coordinates or changing
labels. Explicit decoration IDs are scoped by widget kind and region.
```rust,ignore
let mut ui = Ui::new(Theme::new(accent), interaction.clone());
ui.button(bounds, Action::Refresh,
Button::new("Refresh").enabled(can_refresh));
ui.button(tab_bounds, Action::SelectTab(Tab::Sources),
Button::new("Sources").role(Role::Tab).selected(is_sources));
ui.text_field(input_bounds, Action::FocusEditor, editor_focused);
```
Store `ui.targets` with the newly produced layout and render `ui.list` through the
native display-list backend. Reconcile retained interaction against the new targets;
request one more redraw when a target moves, disappears or changes enabled state.
This settles hover under a stationary pointer after a layout change without a timer
or continuous rendering loop. Paint and register splitters after pane content and
toolbars so neither their appearance nor their hit regions are obscured.
Preserve clipping and scale every primitive, including
focus outlines, when converting logical coordinates to physical pixels.
Dispatch pointer movement, press and release to `Interaction`. Press establishes
capture; a button action is returned only when released inside the same enabled
widget. Text fields focus on press, while drag handles perform host-side resizing
or scrolling during capture. Pointer exit clears hover, focus loss cancels all
capture, and disabled targets block click-through to controls behind them.
Tab / Shift-Tab traverse enabled controls; Enter / Space activate a focused button
on key release. The host's editor keeps plain Tab for indentation and Shift-Tab for
leaving the editor. Rows and drag handles are excluded from Tab traversal. Text
editing, clipboard and IME remain host adapters; the widget layer owns their chrome
and focus presentation. `inline_input` registers a text-input target without a
background or focus border; a terminal-style host draws its own caret in the same
scrollable stream as output. `src/shell/clipboard.rs` guarantees UTF-8 for macOS clipboard
subprocesses, independent of Finder's locale.
Tessera's developer tools are the first consumer. Domain actions, HTTP calls,
source navigation and Console execution remain in `developer_tools.rs` and its page modules; none of
those concepts enter this library. The library currently renders synchronously
with immediate state feedback; it is not an Endor component implementation, an
OS accessibility bridge or a separately published Cargo crate.
The built-in start page lives in `ui_bridge/start_page.endor` and uses the ordinary guest Page/Block renderer. System UI no longer paints a welcome overlay. Native window chrome uses the same neutral palette, while each tool Page has its own interaction state.
+204
View File
@@ -0,0 +1,204 @@
use crate::geometry::{Point, Rect};
use std::hash::{Hash, Hasher};
/// Stable across frames, resizing and text changes. Use semantic keys, never row indices.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct WidgetId(u64);
impl WidgetId {
pub fn new(key: impl Hash) -> Self {
let mut hash = std::collections::hash_map::DefaultHasher::new();
key.hash(&mut hash);
Self(hash.finish())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Axis {
Horizontal,
Vertical,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Role {
Button,
Tab,
Toggle,
TextField,
Row,
Swatch,
Splitter(Axis),
Scrollbar(Axis),
}
impl Role {
fn focusable(self) -> bool {
!matches!(self, Self::Splitter(_) | Self::Scrollbar(_) | Self::Row)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cursor {
Default,
Pointer,
Text,
ResizeHorizontal,
ResizeVertical,
Grab,
Disabled,
}
#[derive(Clone, Debug)]
pub struct Target<A> {
pub id: WidgetId,
pub rect: Rect,
pub role: Role,
pub enabled: bool,
pub action: Option<A>,
}
#[derive(Clone, Copy, Debug)]
pub struct VisualState {
pub hovered: bool,
pub pressed: bool,
pub focused: bool,
pub selected: bool,
pub enabled: bool,
}
/// Retained input state for an immediate-mode frame. Actions fire on release inside
/// the same enabled control, so dragging away cancels a click.
#[derive(Clone, Debug, Default)]
pub struct Interaction {
pointer: Option<Point>,
hovered: Option<WidgetId>,
pointer_active: Option<WidgetId>,
key_active: Option<WidgetId>,
focused: Option<WidgetId>,
keyboard_focus: bool,
}
impl Interaction {
pub fn hit<'a, A>(&self, targets: &'a [Target<A>]) -> Option<&'a Target<A>> {
let p = self.pointer?;
targets.iter().rev().find(|t| t.rect.contains(p))
}
pub fn pointer_moved<A>(&mut self, p: Point, targets: &[Target<A>]) {
self.pointer = Some(p);
self.hovered = self.hit(targets).map(|t| t.id);
}
pub fn pointer_left(&mut self) {
self.pointer = None;
self.hovered = None;
}
pub fn press<A: Clone>(&mut self, targets: &[Target<A>]) -> Option<Target<A>> {
self.key_active = None;
self.keyboard_focus = false;
let target = self.hit(targets).filter(|t| t.enabled).cloned();
self.pointer_active = target.as_ref().map(|t| t.id);
self.focused = target.as_ref().filter(|t| t.role.focusable()).map(|t| t.id);
target
}
pub fn release<A: Clone>(&mut self, targets: &[Target<A>]) -> Option<A> {
let active = self.pointer_active.take()?;
self.hit(targets)
.filter(|t| t.enabled && t.id == active && t.role != Role::TextField)
.and_then(|t| t.action.clone())
}
pub fn cancel(&mut self) {
self.pointer_active = None;
self.key_active = None;
}
pub fn blur(&mut self) {
self.cancel();
self.focused = None;
self.keyboard_focus = false;
self.pointer_left();
}
pub fn reconcile<A>(&mut self, targets: &[Target<A>]) -> bool {
let before = (
self.hovered,
self.pointer_active,
self.focused,
self.key_active,
);
let exists = |id| targets.iter().any(|t| t.id == id && t.enabled);
self.focused = self.focused.filter(|id| exists(*id));
self.pointer_active = self.pointer_active.filter(|id| exists(*id));
self.key_active = self.key_active.filter(|id| exists(*id));
self.hovered = self.hit(targets).map(|t| t.id);
before
!= (
self.hovered,
self.pointer_active,
self.focused,
self.key_active,
)
}
pub fn focused<'a, A>(&self, targets: &'a [Target<A>]) -> Option<&'a Target<A>> {
targets
.iter()
.find(|t| Some(t.id) == self.focused && t.enabled)
}
pub fn focus_next<A: Clone>(&mut self, targets: &[Target<A>], back: bool) -> Option<Target<A>> {
self.cancel();
self.keyboard_focus = true;
let candidates = targets
.iter()
.filter(|t| t.enabled && t.role.focusable())
.collect::<Vec<_>>();
if candidates.is_empty() {
self.focused = None;
return None;
}
let current = candidates.iter().position(|t| Some(t.id) == self.focused);
let index = match current {
Some(i) if back => (i + candidates.len() - 1) % candidates.len(),
Some(i) => (i + 1) % candidates.len(),
None if back => candidates.len() - 1,
None => 0,
};
let target = candidates[index];
self.focused = Some(target.id);
Some(target.clone())
}
pub fn key_press<A>(&mut self, targets: &[Target<A>]) {
self.key_active = self
.focused(targets)
.filter(|t| t.role != Role::TextField)
.map(|t| t.id);
}
pub fn key_release<A: Clone>(&mut self, targets: &[Target<A>]) -> Option<A> {
let active = self.key_active.take()?;
self.focused(targets)
.filter(|t| t.id == active)
.and_then(|t| t.action.clone())
}
pub fn visual(&self, id: WidgetId, selected: bool, enabled: bool) -> VisualState {
let hovered = enabled && self.hovered == Some(id);
VisualState {
hovered,
pressed: enabled
&& (self.key_active == Some(id) || (hovered && self.pointer_active == Some(id))),
focused: enabled && self.keyboard_focus && self.focused == Some(id),
selected,
enabled,
}
}
pub fn captured(&self, id: WidgetId) -> bool {
self.pointer_active == Some(id)
}
pub fn cursor<A>(&self, targets: &[Target<A>]) -> Cursor {
let target = self
.pointer_active
.and_then(|id| {
targets.iter().find(|t| {
t.id == id && matches!(t.role, Role::Splitter(_) | Role::Scrollbar(_))
})
})
.or_else(|| self.hit(targets));
match target {
Some(t) if !t.enabled => Cursor::Disabled,
Some(t) => match t.role {
Role::TextField => Cursor::Text,
Role::Splitter(Axis::Horizontal) => Cursor::ResizeHorizontal,
Role::Splitter(Axis::Vertical) => Cursor::ResizeVertical,
Role::Scrollbar(_) => Cursor::Grab,
_ => Cursor::Pointer,
},
None => Cursor::Default,
}
}
}
+7
View File
@@ -0,0 +1,7 @@
//! Tessera's host management widgets. No Endor AST, VM, UiNode or ui_bridge dependency.
//! Shares only low-level drawing, font shaping and geometry with guest content.
mod interaction;
pub mod theme;
mod widgets;
pub use interaction::{Axis, Cursor, Interaction, Role, Target, VisualState, WidgetId};
pub use widgets::{Button, Ui};
+56
View File
@@ -0,0 +1,56 @@
use crate::display_list::Color;
pub const BG: Color = Color::rgb(255, 255, 255);
// A visibly separate chrome layer against the warm, near-white content canvas.
pub const BAR: Color = Color::rgb(230, 233, 237);
pub const BORDER: Color = Color::rgb(226, 226, 226);
pub const TEXT: Color = Color::rgb(35, 42, 53);
pub const MUTED: Color = Color::rgb(103, 114, 130);
pub const ERROR: Color = Color::rgb(175, 42, 49);
pub const OK: Color = Color::rgb(31, 121, 80);
pub const PALETTE: [Color; 6] = [
Color::rgb(22, 113, 213),
Color::rgb(0, 132, 143),
Color::rgb(115, 76, 189),
Color::rgb(180, 68, 115),
Color::rgb(168, 94, 24),
Color::rgb(52, 123, 78),
];
#[derive(Clone, Copy, Debug)]
pub struct Theme {
pub accent: Color,
}
impl Theme {
pub fn new(accent: Color) -> Self {
Self {
accent: readable_accent(accent),
}
}
pub fn soft(self) -> Color {
mix(BG, self.accent, 0.10)
}
pub fn hover(self) -> Color {
mix(BG, self.accent, 0.17)
}
pub fn pressed(self) -> Color {
mix(BG, self.accent, 0.29)
}
}
pub fn mix(a: Color, b: Color, amount: f32) -> Color {
let channel =
|a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * amount.clamp(0.0, 1.0)).round() as u8;
Color::rgb(
channel(a.red, b.red),
channel(a.green, b.green),
channel(a.blue, b.blue),
)
}
pub fn readable_accent(mut c: Color) -> Color {
while (c.red as u32 * 299 + c.green as u32 * 587 + c.blue as u32 * 114) / 1000 > 155 {
c = Color::rgb(
(c.red as f32 * 0.94) as u8,
(c.green as f32 * 0.94) as u8,
(c.blue as f32 * 0.94) as u8,
);
}
c
}
+290
View File
@@ -0,0 +1,290 @@
use super::{
Axis, Interaction, Role, Target, VisualState, WidgetId,
theme::{self, Theme},
};
use crate::{
display_list::{Color, DisplayList, DrawCommand},
geometry::{Point, Rect},
text::{self, TextStyle},
};
use std::hash::Hash;
pub struct Button<'a> {
pub label: &'a str,
pub selected: bool,
pub enabled: bool,
pub role: Role,
}
impl<'a> Button<'a> {
pub fn new(label: &'a str) -> Self {
Self {
label,
selected: false,
enabled: true,
role: Role::Button,
}
}
pub fn selected(mut self, value: bool) -> Self {
self.selected = value;
self
}
pub fn enabled(mut self, value: bool) -> Self {
self.enabled = value;
self
}
pub fn role(mut self, value: Role) -> Self {
self.role = value;
self
}
}
pub struct Ui<A> {
pub list: DisplayList,
pub targets: Vec<Target<A>>,
pub theme: Theme,
interaction: Interaction,
}
impl<A: Hash> Ui<A> {
pub fn new(theme: Theme, interaction: Interaction) -> Self {
Self {
list: DisplayList::default(),
targets: Vec::new(),
theme,
interaction,
}
}
pub fn fill(&mut self, r: Rect, color: Color) {
self.list.push(DrawCommand::FillRoundedRect {
rect: r,
radius: 0.0,
color,
});
}
fn outline(&mut self, r: Rect, color: Color, width: f32) {
self.list.push(DrawCommand::StrokeRoundedRect {
rect: Rect::new(
r.x + width / 2.0,
r.y + width / 2.0,
(r.width - width).max(0.0),
(r.height - width).max(0.0),
),
radius: 3.0,
width,
color,
});
}
pub fn label(&mut self, x: f32, y: f32, value: &str, color: Color, code: bool) {
self.list.push(DrawCommand::Text {
origin: Point::new(x, y),
value: value.into(),
style: if code {
TextStyle::code()
} else {
TextStyle {
font_size: 12.0,
line_height: 18.0,
..TextStyle::ui(1)
}
},
color,
});
}
fn register(
&mut self,
id: WidgetId,
rect: Rect,
role: Role,
action: Option<A>,
selected: bool,
enabled: bool,
) -> VisualState {
let response = self.interaction.visual(id, selected, enabled);
self.targets.push(Target {
id,
rect,
role,
enabled,
action,
});
response
}
fn surface(&mut self, rect: Rect, s: VisualState, base: Option<Color>) {
let color = if !s.enabled {
base
} else if s.pressed {
Some(self.theme.pressed())
} else if s.hovered {
Some(self.theme.hover())
} else if s.selected {
Some(self.theme.soft())
} else {
base
};
if let Some(color) = color {
self.fill(rect, color);
}
if s.focused {
self.outline(rect, self.theme.accent, 1.5);
}
}
pub fn button(&mut self, rect: Rect, action: A, button: Button<'_>) -> VisualState {
let id = WidgetId::new(&action);
let s = self.register(
id,
rect,
button.role,
Some(action),
button.selected,
button.enabled,
);
self.surface(rect, s, None);
self.list.push(DrawCommand::PushClip(rect));
let label = text::fit(
button.label,
(rect.width - 16.0).max(0.0),
TextStyle {
font_size: 12.0,
line_height: 18.0,
..TextStyle::ui(1)
},
);
self.label(
rect.x + 8.0,
rect.y + (rect.height - 18.0) / 2.0,
&label,
if s.enabled {
theme::TEXT
} else {
Color::rgb(151, 160, 172)
},
false,
);
if s.selected && button.role == Role::Tab {
self.fill(
Rect::new(rect.x, rect.y + rect.height - 2.0, rect.width, 2.0),
self.theme.accent,
);
}
self.list.push(DrawCommand::PopClip);
s
}
pub fn text_field(&mut self, rect: Rect, action: A, focused: bool) {
let s = self.register(
WidgetId::new(&action),
rect,
Role::TextField,
Some(action),
false,
true,
);
self.surface(rect, s, Some(theme::BG));
self.outline(
rect,
if focused || s.focused {
self.theme.accent
} else if s.hovered {
theme::MUTED
} else {
theme::BORDER
},
if focused || s.focused { 1.5 } else { 1.0 },
);
}
/// A terminal prompt shares its surface with output; its caret is the focus cue.
pub fn inline_input(&mut self, rect: Rect, action: A) {
self.register(
WidgetId::new(&action),
rect,
Role::TextField,
Some(action),
false,
true,
);
}
pub fn row(&mut self, paint: Rect, hit: Rect, action: A, selected: bool) {
let s = self.register(
WidgetId::new(&action),
hit,
Role::Row,
Some(action),
selected,
true,
);
self.surface(paint, s, None);
}
pub fn swatch(&mut self, rect: Rect, action: A, color: Color, selected: bool) {
let s = self.register(
WidgetId::new(&action),
rect,
Role::Swatch,
Some(action),
selected,
true,
);
self.fill(
rect,
if s.pressed {
theme::mix(color, theme::TEXT, 0.2)
} else {
color
},
);
if s.hovered || s.focused || selected {
self.outline(
Rect::new(
rect.x - 3.0,
rect.y - 3.0,
rect.width + 6.0,
rect.height + 6.0,
),
if s.focused {
self.theme.accent
} else {
theme::TEXT
},
if s.pressed { 3.0 } else { 1.5 },
);
}
if selected {
self.label(rect.x + 10.0, rect.y + 6.0, "✓", theme::BG, false);
}
}
pub fn splitter(&mut self, rect: Rect, id: WidgetId, axis: Axis) {
let hit = Rect::new(
rect.x - 3.0,
rect.y - 3.0,
rect.width + 6.0,
rect.height + 6.0,
);
let mut s = self.register(id, hit, Role::Splitter(axis), None, false, true);
s.pressed |= self.interaction.captured(id);
let color = if s.pressed || s.hovered {
self.theme.accent
} else {
theme::BORDER
};
let line = if s.hovered || s.pressed {
match axis {
Axis::Horizontal => Rect::new(rect.x - 1.0, rect.y, 3.0, rect.height),
Axis::Vertical => Rect::new(rect.x, rect.y - 1.0, rect.width, 3.0),
}
} else {
rect
};
self.fill(line, color);
}
pub fn scrollbar(&mut self, rect: Rect, id: WidgetId, axis: Axis) {
let mut s = self.register(id, rect, Role::Scrollbar(axis), None, false, true);
s.pressed |= self.interaction.captured(id);
self.fill(
rect,
if s.pressed {
self.theme.accent
} else if s.hovered {
theme::mix(theme::MUTED, self.theme.accent, 0.55)
} else {
Color::rgb(161, 173, 190)
},
);
}
}
+679
View File
@@ -0,0 +1,679 @@
//! Immutable tab chrome. IDs are session-local projections, never heap handles.
use crate::{
display_list::{Color, DisplayList, DrawCommand},
geometry::{Point, Rect},
text::TextStyle,
};
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,
pub title: String,
pub active: bool,
#[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
@@ -0,0 +1,63 @@
//! 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
@@ -0,0 +1,207 @@
//! 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()
}
}