Files
Marcos Paulo 181aad91e6 feat: sync, accounts, live editing, vault launcher, compact layout
Sync and the server
- crates/sync: revision ledger (stale writers conflict, edit beats delete), client planner, three-way merge, conflict names, path and hash gates
- apps/notescraft-sync-server: pairing, device tokens, change log with long poll, blobs, accounts with many vaults, roles, invites, audit log, quota, GC, readiness, request ids
- server history (revisions, restore, retention), chunked resumable uploads, live editing endpoints (SSE rooms, presence, flush through the ledger)
- engine: HttpRemote, sync_once, SyncWorker, sync.* commands, share.* and server.* commands, live session client, note.capture, vault catalog and vaults.* commands

Editing together
- crates/collab: operational transformation core (TextOp, transform, client state machine, room, presence)
- ui-egui: Settings > Sync, sync pill, conflicts, Share dialog, live pill and remote carets, launcher Connect and Join flows

App shell
- vault launcher (desktop and phone layouts) wired into the app host (--launcher, File > Vaults...)
- compact (phone) layout with a bottom tab bar

Verified with cargo xtask ci (fmt, clippy -D warnings, workspace tests, layers, tree, i18n). Android and iOS shells are not built: the build machine has no NDK or Xcode.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 07:46:24 -03:00

426 lines
17 KiB
Rust

//! The vault launcher, driven the way a user does: real pointer and keyboard
//! events through whole frames, plus the `format_ago` cases.
use std::sync::Arc;
use egui::{Context, Event, Key, PointerButton, Pos2, RawInput, Rect, vec2};
use notescraft_engine::{SyncBadge, VaultRow};
use notescraft_ui_egui::launcher::{Launcher, LauncherAction, format_ago};
use notescraft_ui_egui::{fonts, motion, style, theme::Tokens};
/// 2026-10-20T00:00:00Z in Unix milliseconds: the fixed "now" of the tests (a Monday).
/// Noon, so that "30 seconds ago" is still the same calendar day.
const NOW: u64 = 1_792_454_400_000 + 43_200_000;
/// Unix milliseconds of one day.
const DAY: u64 = 86_400_000;
struct Driver {
launcher: Launcher,
ctx: Context,
tokens: Tokens,
time: f64,
action: Option<LauncherAction>,
size: (f32, f32),
}
/// A painted text: what it says, where it starts and its galley (for positions and widths).
struct Painted {
text: String,
pos: Pos2,
galley: Arc<egui::Galley>,
}
/// A frame's painted content: texts and filled rects.
type FrameOut = (Vec<Painted>, Vec<Rect>);
/// A launcher row on disk.
fn row(name: &str, path: &str, pinned: bool, last_opened_ms: u64, sync: SyncBadge, exists: bool) -> VaultRow {
VaultRow { path: path.to_owned(), name: name.to_owned(), pinned, last_opened_ms, exists, sync, server: None, role: None }
}
/// A row with a rename (the launcher shows this name, not the folder name) and a server role.
fn renamed(name: &str, path: &str, last_opened_ms: u64, role: &str) -> VaultRow {
VaultRow {
path: path.to_owned(),
name: name.to_owned(),
pinned: false,
last_opened_ms,
exists: true,
sync: SyncBadge::Synced,
server: Some(String::from("sync.example.net")),
role: Some(role.to_owned()),
}
}
/// A row whose folder is gone.
fn missing(name: &str, path: &str, last_opened_ms: u64) -> VaultRow {
VaultRow {
path: path.to_owned(),
name: name.to_owned(),
pinned: false,
last_opened_ms,
exists: false,
sync: SyncBadge::NotSynced,
server: None,
role: None,
}
}
/// A server-only row (no path yet: it lives on the server and connects from there).
fn server_only(name: &str, role: &str) -> VaultRow {
VaultRow {
path: String::new(),
name: name.to_owned(),
pinned: false,
last_opened_ms: 0,
exists: false,
sync: SyncBadge::NotSynced,
server: Some(String::from("sync.example.net")),
role: Some(role.to_owned()),
}
}
/// The twelve reference rows: 2 pinned, 1 renamed, 1 missing, the rest newest first.
fn rows() -> Vec<VaultRow> {
vec![
renamed_with(row("Journal", "~/Notes/Journal", true, NOW - 3_600_000, SyncBadge::Synced, true), None),
row("Work", "/Volumes/Storage/Work", true, NOW - 5 * 3_600_000, SyncBadge::NotSynced, true),
renamed("Atlas Project", "~/Notes/Atlas", NOW - DAY, "Editor"),
missing("Old course notes", "/Volumes/USB/Course", NOW - 17 * DAY),
renamed_with(row("Borealis", "~/Notes/Borealis", false, NOW - 2 * DAY, SyncBadge::Waiting(2), true), None),
row("Cedar", "~/Notes/Cedar", false, NOW - 3 * DAY, SyncBadge::Error, true),
row("Delta", "~/Notes/Delta", false, NOW - 4 * DAY, SyncBadge::Synced, true),
row("Echo", "~/Notes/Echo", false, NOW - 5 * DAY, SyncBadge::NotSynced, true),
row("Foxtrot", "~/Notes/Foxtrot", false, NOW - 6 * DAY, SyncBadge::NotSynced, true),
row("Grove", "~/Notes/Grove", false, NOW - 7 * DAY, SyncBadge::NotSynced, true),
row("Haven", "~/Notes/Haven", false, NOW - 8 * DAY, SyncBadge::NotSynced, true),
row("Iris", "~/Notes/Iris", false, NOW - 9 * DAY, SyncBadge::NotSynced, true),
]
}
/// Marks a row with an optional server binding.
fn renamed_with(mut row: VaultRow, server: Option<&str>) -> VaultRow {
row.server = server.map(str::to_owned);
row
}
/// Four rows for the phone: two local (one shared) and two server-only.
fn phone_rows() -> Vec<VaultRow> {
vec![
row("Journal", "~/Notes/Journal", false, NOW - 3_600_000, SyncBadge::Synced, true),
renamed("Project Atlas", "~/Notes/Atlas", NOW - DAY, "Editor"),
server_only("Dinner plans", "Viewer"),
server_only("Recipes", "Owner"),
]
}
impl Driver {
/// A launcher over `rows` at `size`, animations off.
fn with(rows: Vec<VaultRow>, size: (f32, f32)) -> Driver {
let tokens = Tokens::new(notescraft_themes::builtin("catppuccin-mocha").expect("theme"));
let ctx = Context::default();
fonts::install(&ctx);
motion::set_enabled(&ctx, false);
ctx.all_styles_mut(|theme| theme.animation_time = 0.0);
style::apply(&ctx, &tokens);
Driver { launcher: Launcher::new(rows, NOW), ctx, tokens, time: 1.0, action: None, size }
}
/// A desktop launcher with the twelve reference rows.
fn desktop() -> Driver {
Self::with(rows(), (1440.0, 900.0))
}
/// A phone launcher.
fn phone() -> Driver {
Self::with(phone_rows(), (390.0, 844.0))
}
/// One frame with `events`; what it painted. Keeps the last non-None action.
fn frame(&mut self, events: Vec<Event>) -> FrameOut {
self.time += 0.05;
let input = RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(self.size.0, self.size.1))),
time: Some(self.time),
events,
..Default::default()
};
let launcher = &mut self.launcher;
let tokens = self.tokens.clone();
let mut texts = Vec::new();
let mut rects = Vec::new();
let mut out = self.ctx.run_ui(input, |ui| {
let action = launcher.show(ui.ctx(), &tokens);
if action.is_some() {
self.action = action;
}
});
out.textures_delta.clear();
for shape in &out.shapes {
match &shape.shape {
egui::Shape::Text(text) if !text.galley.text().is_empty() => {
texts.push(Painted { text: text.galley.text().to_owned(), pos: text.pos, galley: text.galley.clone() });
}
egui::Shape::Rect(rect) if rect.fill != egui::Color32::TRANSPARENT => rects.push(rect.rect),
_ => {}
}
}
(texts, rects)
}
/// Six frames so popups and focus land.
fn settle(&mut self) -> FrameOut {
let mut last: FrameOut = (Vec::new(), Vec::new());
for _ in 0..6 {
last = self.frame(Vec::new());
}
last
}
/// Moves the pointer to `point`, presses and releases, then settles.
fn click(&mut self, point: Pos2) -> FrameOut {
let _ = self.frame(vec![Event::PointerMoved(point)]);
let _ = self.button(point, true);
let _ = self.button(point, false);
self.settle()
}
fn button(&mut self, at: Pos2, pressed: bool) -> FrameOut {
self.frame(vec![Event::PointerMoved(at), Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }])
}
fn key(&mut self, key: Key, modifiers: egui::Modifiers) -> FrameOut {
self.frame(vec![Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }])
}
fn text(&mut self, text: &str) -> FrameOut {
self.frame(vec![Event::Text(text.to_owned())])
}
}
fn names(texts: &[Painted]) -> Vec<&str> {
texts.iter().map(|painted| painted.text.as_str()).collect()
}
fn painted<'a>(texts: &'a [Painted], wanted: &str) -> &'a Painted {
texts.iter().find(|painted| painted.text == wanted).unwrap_or_else(|| panic!("no {wanted:?} among {:?}", names(texts)))
}
/// The painted y of the rows named in `wanted` (name lines, one per row).
fn row_order(texts: &[Painted], wanted: &[&str]) -> Vec<f32> {
wanted.iter().map(|name| painted(texts, name).pos.y).collect()
}
#[test]
fn twelve_rows_render_pinned_first_then_newest_first() {
let mut d = Driver::desktop();
let (texts, _) = d.settle();
let order = row_order(&texts, &["Journal", "Work", "Atlas Project", "Old course notes", "Borealis", "Cedar"]);
let mut sorted = order.clone();
sorted.sort_by(f32::total_cmp);
assert_eq!(order, sorted, "pinned first then newest first: {order:?}");
assert!(texts.iter().any(|painted| painted.text.contains("folder not found")), "the missing row is marked: {:?}", names(&texts));
}
#[test]
fn the_four_action_cards_report_their_actions() {
let mut d = Driver::desktop();
let (texts, _) = d.settle();
for (title, expected) in [
("Open folder as vault", LauncherAction::OpenFolder),
("Create new vault", LauncherAction::CreateVault),
("Connect to server", LauncherAction::ConnectToServer),
("Join with a code", LauncherAction::JoinWithCode),
] {
let at = painted(&texts, title).pos + vec2(8.0, 6.0);
d.action = None;
let _ = d.click(at);
assert_eq!(d.action.clone().expect("card click"), expected.clone(), "at {title:?}");
if expected == LauncherAction::ConnectToServer || expected == LauncherAction::JoinWithCode {
// The two cards also open their dialog; Escape dismisses it again.
assert!(d.launcher.dialog_open(), "at {title:?}");
let _ = d.key(egui::Key::Escape, egui::Modifiers::NONE);
let _ = d.settle();
assert!(!d.launcher.dialog_open(), "at {title:?}");
}
}
}
#[test]
fn double_clicking_a_row_opens_it() {
let mut d = Driver::desktop();
let (texts, _) = d.settle();
let at = painted(&texts, "Borealis").pos + vec2(8.0, 8.0);
let _ = d.button(at, true);
let _ = d.button(at, false);
let _ = d.button(at, true);
let _ = d.button(at, false);
let _ = d.settle();
assert_eq!(d.action.clone().expect("the row opened"), LauncherAction::Open { path: String::from("~/Notes/Borealis"), new_window: false });
}
#[test]
fn the_row_menu_pins_a_vault() {
let mut d = Driver::desktop();
let (texts, _) = d.settle();
let label = painted(&texts, "2 changes waiting").pos;
// The "..." button sits right of the pill: pill text width, the cluster gap and half the button.
let width = painted(&texts, "2 changes waiting").galley.size().x;
let menu_at = Pos2::new(label.x + width + 12.0 + 16.0, label.y + 8.0);
let _ = d.click(menu_at);
let (menu, _) = d.settle();
let pin = painted(&menu, "Pin").pos + vec2(8.0, 8.0);
d.action = None;
let _ = d.click(pin);
assert_eq!(d.action.clone().expect("pin"), LauncherAction::Pin { path: String::from("~/Notes/Borealis"), pinned: true });
}
#[test]
fn a_missing_row_never_opens_but_its_remove_button_reports_remove() {
let mut d = Driver::desktop();
let (texts, _) = d.settle();
let at = painted(&texts, "Old course notes").pos + vec2(8.0, 8.0);
let _ = d.button(at, true);
let _ = d.button(at, false);
let _ = d.button(at, true);
let _ = d.button(at, false);
let _ = d.settle();
assert_eq!(d.action, None, "a missing row never opens");
let remove_at = painted(&texts, "Remove from list").pos + vec2(8.0, 8.0);
d.action = None;
let _ = d.click(remove_at);
assert_eq!(d.action.clone().expect("remove"), LauncherAction::Remove { path: String::from("/Volumes/USB/Course") });
}
#[test]
fn the_rename_flow_reports_the_committed_name() {
let mut d = Driver::desktop();
let (texts, _) = d.settle();
let label = painted(&texts, "2 changes waiting").pos;
let width = painted(&texts, "2 changes waiting").galley.size().x;
let _ = d.click(Pos2::new(label.x + width + 28.0, label.y + 8.0));
let (menu, _) = d.settle();
let rename_at = painted(&menu, "Rename").pos + vec2(8.0, 8.0);
let _ = d.click(rename_at);
let _ = d.settle();
let _ = d.text("XXX");
let _ = d.settle();
d.action = None;
let _ = d.key(Key::Enter, egui::Modifiers::NONE);
let _ = d.settle();
let committed = match d.action.clone().expect("rename") {
LauncherAction::Rename { path, name } => {
assert_eq!(path, "~/Notes/Borealis");
assert!(name != "Borealis", "the typed text landed: {name:?}");
assert!(name.contains("XXX"), "the typed text is in the field: {name:?}");
name
}
other => panic!("not a rename: {other:?}"),
};
// Escape cancels the field, and the row keeps the committed name.
d.action = None;
let (texts, _) = d.settle();
let label = painted(&texts, "2 changes waiting").pos;
let width = painted(&texts, "2 changes waiting").galley.size().x;
let _ = d.click(Pos2::new(label.x + width + 28.0, label.y + 8.0));
let (menu, _) = d.settle();
let _ = d.click(painted(&menu, "Rename").pos + vec2(8.0, 8.0));
let _ = d.settle();
let _ = d.text("YYY");
let _ = d.key(Key::Escape, egui::Modifiers::NONE);
let (texts, _) = d.settle();
assert!(texts.iter().any(|painted| painted.text == committed), "Esc keeps the committed name");
assert_eq!(d.action, None, "Esc never reports an action");
}
#[test]
fn the_filter_narrows_rows_case_insensitively_on_name_and_path() {
let mut d = Driver::desktop();
let _ = d.key(Key::F, egui::Modifiers::COMMAND);
let _ = d.settle();
let _ = d.text("BORE");
let (texts, _) = d.settle();
assert!(texts.iter().any(|painted| painted.text == "Borealis"), "matches the name");
assert!(texts.iter().all(|painted| painted.text != "Cedar"), "{:?}", names(&texts));
for _ in 0..4 {
let _ = d.key(Key::Backspace, egui::Modifiers::NONE);
}
let _ = d.text("VOL");
let (texts, _) = d.settle();
assert!(texts.iter().any(|painted| painted.text == "Old course notes"), "matches the path: {:?}", names(&texts));
assert!(texts.iter().all(|painted| painted.text != "Borealis"), "unrelated rows drop out");
}
#[test]
fn pressing_delete_twice_removes_the_selected_row_from_the_list() {
let mut d = Driver::desktop();
let _ = d.settle();
d.action = None;
let _ = d.key(Key::Delete, egui::Modifiers::NONE);
let (texts, _) = d.settle();
assert_eq!(d.action, None, "the first Delete only asks");
assert_eq!(texts.iter().filter(|painted| painted.text == "Remove from list").count(), 2, "the armed row asks in the UI: {:?}", names(&texts));
let _ = d.key(Key::Delete, egui::Modifiers::NONE);
let _ = d.settle();
assert_eq!(d.action.clone().expect("confirmed"), LauncherAction::Remove { path: String::from("~/Notes/Journal") });
}
#[test]
fn up_down_select_and_enter_opens_but_never_a_missing_row() {
let mut d = Driver::desktop();
let _ = d.settle();
d.action = None;
let _ = d.key(Key::ArrowDown, egui::Modifiers::NONE);
let _ = d.key(Key::ArrowDown, egui::Modifiers::NONE);
let _ = d.settle();
let _ = d.key(Key::Enter, egui::Modifiers::NONE);
let _ = d.settle();
assert_eq!(d.action.clone().expect("enter opens"), LauncherAction::Open { path: String::from("~/Notes/Atlas"), new_window: false });
let mut d = Driver::desktop();
let _ = d.settle();
d.action = None;
for _ in 0..3 {
let _ = d.key(Key::ArrowDown, egui::Modifiers::NONE);
}
let _ = d.settle();
let _ = d.key(Key::Enter, egui::Modifiers::NONE);
let _ = d.settle();
assert_eq!(d.action, None, "the missing row never opens");
}
#[test]
fn the_phone_layout_shows_one_column_and_the_two_bottom_buttons() {
let mut d = Driver::phone();
let (texts, rects) = d.settle();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(390.0, 844.0));
for name in ["ON THIS PHONE", "ON YOUR SERVER", "New vault", "Join"] {
assert!(texts.iter().any(|painted| painted.text == name), "{name:?}: {:?}", names(&texts));
}
for painted in &texts {
let visible = Rect::from_min_size(painted.pos, painted.galley.size()).intersect(screen);
assert!(!visible.is_negative(), "text outside the screen: {:?}", painted.text);
}
for rect in &rects {
assert!(!rect.intersect(screen).is_negative(), "paint outside the screen: {rect:?}");
}
// The two bottom buttons sit inside the screen and reach the touch floor.
let buttons: Vec<Rect> =
rects.iter().filter(|rect| rect.height() >= 50.0 && rect.height() < 200.0 && rect.max.y > screen.bottom() - 120.0).copied().collect();
assert_eq!(buttons.len(), 2, "two bottom buttons: {:?}", rect_debug(&buttons));
assert!(buttons.iter().all(|rect| screen.contains_rect(*rect)), "{:?}", rect_debug(&buttons));
assert!(buttons.iter().all(|rect| rect.height() >= 44.0), "{:?}", rect_debug(&buttons));
}
fn rect_debug(rects: &[Rect]) -> Vec<(f32, f32, f32, f32)> {
rects.iter().map(|rect| (rect.min.x, rect.min.y, rect.max.x, rect.max.y)).collect()
}
#[test]
fn the_age_of_a_last_open_line_reads_from_the_i18n_table() {
assert_eq!(format_ago(NOW, NOW - 30_000), "Today");
assert_eq!(format_ago(NOW, NOW - DAY), "Yesterday");
assert_eq!(format_ago(NOW, NOW - 3 * DAY), "Sat", "the weekday of that day");
assert_eq!(format_ago(NOW, NOW - 17 * DAY), "Oct 3", "an older date");
assert_eq!(format_ago(NOW, NOW + DAY), "Today", "a clock that runs ahead is not shown as the past");
assert_eq!(format_ago(NOW, NOW - 357 * DAY), "Oct 28", "last year renders as a date");
}