181aad91e6
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>
629 lines
26 KiB
Rust
629 lines
26 KiB
Rust
//! The Share dialog and the two launcher dialogs, driven the way a user does:
|
|
//! real pointer and keyboard events through whole frames, over a real
|
|
//! [`notescraft_engine::Session`] with a bound vault and a stub HTTP server
|
|
//! (the stub of `crates/engine/tests/share_commands.rs`, shrunk).
|
|
|
|
use std::io::{BufRead, BufReader, Read, Write};
|
|
use std::net::{TcpListener, TcpStream};
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::Duration;
|
|
|
|
use egui::{Context, Event, Key, PointerButton, Pos2, RawInput, Rect, vec2};
|
|
use notescraft_engine::{Session, SyncBadge, VaultRow, bind_folder};
|
|
use notescraft_ui_egui::app::NotesApp;
|
|
use notescraft_ui_egui::launcher::{Launcher, LauncherAction};
|
|
use notescraft_ui_egui::theme::Tokens;
|
|
|
|
/// The token of the bound vault; it must never reach a painted text.
|
|
const TOKEN: &str = "secret-token";
|
|
|
|
/// One request the stub answered: method, path, status and body.
|
|
type Route = (String, String, u16, String);
|
|
|
|
/// One request the stub received.
|
|
#[derive(Clone)]
|
|
struct Request {
|
|
/// The method of the request line.
|
|
method: String,
|
|
/// The path of the request line.
|
|
path: String,
|
|
/// The body of the request.
|
|
body: String,
|
|
}
|
|
|
|
/// A stub server that answers canned JSON and remembers what it was asked.
|
|
struct Stub {
|
|
/// The base URL of the stub.
|
|
base: String,
|
|
/// Every request, in order.
|
|
seen: Arc<Mutex<Vec<Request>>>,
|
|
/// The canned answers, by method and path.
|
|
routes: Arc<Mutex<Vec<Route>>>,
|
|
/// Whether the listener thread should stop.
|
|
stop: Arc<AtomicBool>,
|
|
}
|
|
|
|
impl Stub {
|
|
/// Starts a stub on an ephemeral port.
|
|
fn spawn() -> Self {
|
|
let listener = TcpListener::bind("127.0.0.1:0").expect("bind the stub");
|
|
listener.set_nonblocking(true).expect("nonblocking");
|
|
let port = listener.local_addr().expect("addr").port();
|
|
let seen: Arc<Mutex<Vec<Request>>> = Arc::new(Mutex::new(Vec::new()));
|
|
let routes: Arc<Mutex<Vec<Route>>> = Arc::new(Mutex::new(Vec::new()));
|
|
let stop = Arc::new(AtomicBool::new(false));
|
|
let thread = (Arc::clone(&seen), Arc::clone(&routes), Arc::clone(&stop));
|
|
let listener_handle = std::thread::spawn(move || {
|
|
while !thread.2.load(Ordering::Relaxed) {
|
|
match listener.accept() {
|
|
Ok((stream, _)) => {
|
|
// An accepted socket inherits the listener's non-blocking mode on some platforms:
|
|
// a read that beats the request bytes would then end the connection.
|
|
let _ = stream.set_nonblocking(false);
|
|
let Ok(mut writer) = stream.try_clone() else { continue };
|
|
let seen = Arc::clone(&thread.0);
|
|
let routes = Arc::clone(&thread.1);
|
|
std::thread::spawn(move || {
|
|
let mut reader = BufReader::new(stream);
|
|
let _ = reader.get_ref().set_read_timeout(Some(Duration::from_secs(20)));
|
|
while let Some(request) = read_request(&mut reader) {
|
|
let answer = routes
|
|
.lock()
|
|
.expect("routes")
|
|
.iter()
|
|
.find(|(method, path, _status, _body)| *method == request.method && *path == request.path)
|
|
.map(|(_m, _p, status, body)| (*status, body.clone()));
|
|
seen.lock().expect("seen").push(request);
|
|
let (status, body) = answer.unwrap_or((404, "{\"error\":\"no such route\"}".to_owned()));
|
|
write_answer(&mut writer, status, &body);
|
|
}
|
|
});
|
|
}
|
|
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
|
|
std::thread::sleep(Duration::from_millis(2));
|
|
}
|
|
Err(_) => break,
|
|
}
|
|
}
|
|
});
|
|
let _ = listener_handle;
|
|
Self { base: format!("http://127.0.0.1:{port}"), seen, routes, stop }
|
|
}
|
|
|
|
/// Adds a canned answer.
|
|
fn route(&self, method: &str, path: &str, status: u16, body: &str) {
|
|
self.routes.lock().expect("routes").push((method.to_owned(), path.to_owned(), status, body.to_owned()));
|
|
}
|
|
|
|
/// Every request the stub received, as `(method, path, body)`.
|
|
fn requests(&self) -> Vec<(String, String, String)> {
|
|
self.seen.lock().expect("seen").iter().map(|request| (request.method.clone(), request.path.clone(), request.body.clone())).collect()
|
|
}
|
|
}
|
|
|
|
impl Drop for Stub {
|
|
fn drop(&mut self) {
|
|
self.stop.store(true, Ordering::Relaxed);
|
|
}
|
|
}
|
|
|
|
/// Reads one request of a connection.
|
|
fn read_request(reader: &mut BufReader<TcpStream>) -> Option<Request> {
|
|
let mut line = String::new();
|
|
reader.read_line(&mut line).ok()?;
|
|
let mut parts = line.split_whitespace();
|
|
let method = parts.next()?.to_owned();
|
|
let path = parts.next()?.to_owned();
|
|
let mut length = 0_usize;
|
|
loop {
|
|
let mut header = String::new();
|
|
if reader.read_line(&mut header).ok()? == 0 {
|
|
break;
|
|
}
|
|
if header.trim_end().is_empty() {
|
|
break;
|
|
}
|
|
if let Some((name, value)) = header.trim_end().split_once(':')
|
|
&& name.trim().eq_ignore_ascii_case("content-length")
|
|
{
|
|
length = value.trim().parse().unwrap_or(0);
|
|
}
|
|
}
|
|
let mut body = vec![0_u8; length];
|
|
if length > 0 {
|
|
reader.read_exact(&mut body).ok()?;
|
|
}
|
|
Some(Request { method, path, body: String::from_utf8_lossy(&body).into_owned() })
|
|
}
|
|
|
|
/// Writes one answer of the stub.
|
|
fn write_answer(stream: &mut TcpStream, status: u16, body: &str) {
|
|
let head = format!("HTTP/1.1 {status} S\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n", body.len());
|
|
let _ = stream.write_all(head.as_bytes());
|
|
let _ = stream.write_all(body.as_bytes());
|
|
let _ = stream.flush();
|
|
}
|
|
|
|
/// The members the stub answers for the bound vault `v-1`.
|
|
const MEMBERS: &str = concat!(
|
|
r##"[{"user_id":"u-1","name":"Marcos","color":"#cba6f7","role":"owner","last_seen_ms":1},"##,
|
|
r##"{"user_id":"u-2","name":"Ana","color":"#94e2d5","role":"viewer","last_seen_ms":2},"##,
|
|
r##"{"user_id":"u-3","name":"Rui","color":"#f5c2e7","role":"owner","last_seen_ms":3}]"##
|
|
);
|
|
|
|
/// The open invite the stub answers with.
|
|
const INVITES: &str = r#"[{"id":"i-1","role":"editor","created_ms":1,"expires_ms":2}]"#;
|
|
|
|
/// A vault bound to the stub, for the app and launcher tests.
|
|
fn bound_vault(name: &str, base: &str) -> std::path::PathBuf {
|
|
let root = std::env::temp_dir().join(format!("notescraft-share-{name}-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&root);
|
|
std::fs::create_dir_all(&root).expect("vault root");
|
|
bind_folder(&root, base, "v-1", TOKEN, "d-1", Some("u-1")).expect("bind the vault");
|
|
std::fs::write(root.join("a.md"), "# A\n").expect("seed");
|
|
root
|
|
}
|
|
|
|
/// A painted text and where it started.
|
|
struct Painted {
|
|
text: String,
|
|
pos: Pos2,
|
|
}
|
|
|
|
/// The texts painted with the events of one frame at `size`.
|
|
fn paint_texts(
|
|
ctx: &mut Context,
|
|
size: (f32, f32),
|
|
time: f64,
|
|
events: Vec<Event>,
|
|
draw: &mut dyn FnMut(&mut egui::Ui),
|
|
) -> (Vec<Painted>, Vec<egui::OutputCommand>) {
|
|
let input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(size.0, size.1))), time: Some(time), events, ..Default::default() };
|
|
let mut out = ctx.run_ui(input, draw);
|
|
out.textures_delta.clear();
|
|
let texts = out
|
|
.shapes
|
|
.iter()
|
|
.filter_map(|shape| match &shape.shape {
|
|
egui::Shape::Text(text) if !text.galley.text().is_empty() => Some(Painted { text: text.galley.text().to_owned(), pos: text.pos }),
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
(texts, out.platform_output.commands)
|
|
}
|
|
|
|
/// The `text` painted, and where.
|
|
fn painted<'a>(texts: &'a [Painted], text: &str) -> &'a Painted {
|
|
texts.iter().find(|painted| painted.text == text).unwrap_or_else(|| panic!("no {text:?} painted"))
|
|
}
|
|
|
|
/// The rightmost `text` painted (a chip sits at a row's right edge).
|
|
/// The painted `text` nearest to `at`: a popup item sits beside its button.
|
|
fn nearest<'a>(texts: &'a [Painted], text: &str, at: Pos2) -> &'a Painted {
|
|
let distance = |painted: &Painted| (painted.pos.x - at.x) * (painted.pos.x - at.x) + (painted.pos.y - at.y) * (painted.pos.y - at.y);
|
|
texts
|
|
.iter()
|
|
.filter(|painted| painted.text == text)
|
|
.min_by(|left, right| distance(left).total_cmp(&distance(right)))
|
|
.unwrap_or_else(|| panic!("no {text:?} near {at:?}"))
|
|
}
|
|
|
|
fn rightmost<'a>(texts: &'a [Painted], text: &str) -> &'a Painted {
|
|
let rightmost = texts.iter().filter(|painted| painted.text.contains(text)).max_by(|left, right| left.pos.x.total_cmp(&right.pos.x));
|
|
rightmost.unwrap_or_else(|| panic!("no {text:?} painted"))
|
|
}
|
|
|
|
/// One pointer button event at `at`.
|
|
fn button(at: Pos2, pressed: bool) -> Event {
|
|
Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }
|
|
}
|
|
|
|
/// Types `text` into the focused field.
|
|
fn type_text(text: &str) -> Vec<Event> {
|
|
vec![Event::Text(text.to_owned())]
|
|
}
|
|
|
|
/// One key press.
|
|
fn press(key: Key) -> Vec<Event> {
|
|
vec![Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }]
|
|
}
|
|
|
|
/// An app over a vault, with animations off.
|
|
struct AppDriver {
|
|
app: NotesApp,
|
|
ctx: Context,
|
|
time: f64,
|
|
commands: Vec<egui::OutputCommand>,
|
|
}
|
|
|
|
impl AppDriver {
|
|
/// An app over `vault`, set to its own settings dir.
|
|
fn over(vault: &std::path::Path) -> Self {
|
|
let mut session = Session::open(vault).expect("session");
|
|
session.use_settings_dir(vault.join("config"));
|
|
let mut app = NotesApp::new(session, notescraft_themes::builtin("catppuccin-mocha").expect("theme"));
|
|
app.state.animations = false;
|
|
AppDriver { app, ctx: Context::default(), time: 1.0, commands: Vec::new() }
|
|
}
|
|
|
|
/// One frame with `events`; the texts it painted.
|
|
fn frame(&mut self, events: Vec<Event>) -> Vec<Painted> {
|
|
self.time += 0.05;
|
|
let app = &mut self.app;
|
|
let (texts, commands) = paint_texts(&mut self.ctx, (1440.0, 900.0), self.time, events, &mut |ui| app.ui(ui.ctx()));
|
|
self.commands = commands;
|
|
texts
|
|
}
|
|
|
|
/// Frames until `wanted` is painted, with real time for the workers.
|
|
fn wait_for(&mut self, wanted: &str) -> Vec<Painted> {
|
|
for _ in 0..100 {
|
|
let texts = self.frame(Vec::new());
|
|
if texts.iter().any(|painted| painted.text.contains(wanted)) {
|
|
return texts;
|
|
}
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
panic!("never painted {wanted:?}");
|
|
}
|
|
|
|
/// Sets frames running so workers answer; the last texts.
|
|
fn settle(&mut self) -> Vec<Painted> {
|
|
let mut texts = Vec::new();
|
|
for _ in 0..12 {
|
|
texts = self.frame(Vec::new());
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
texts
|
|
}
|
|
|
|
/// Clicks `at` and lets the frame land: move, press and release as their
|
|
/// own frames, like a real pointer.
|
|
fn click(&mut self, at: Pos2) -> Vec<Painted> {
|
|
let _ = self.frame(vec![Event::PointerMoved(at)]);
|
|
let _ = self.frame(vec![Event::PointerMoved(at), button(at, true)]);
|
|
let _ = self.frame(vec![Event::PointerMoved(at), button(at, false)]);
|
|
self.settle()
|
|
}
|
|
}
|
|
|
|
/// A launcher over rows, driven the way `tests/launcher.rs` drives it.
|
|
struct LauncherDriver {
|
|
launcher: Launcher,
|
|
ctx: Context,
|
|
time: f64,
|
|
action: Option<LauncherAction>,
|
|
}
|
|
|
|
impl LauncherDriver {
|
|
/// A launcher over `rows`.
|
|
fn over(rows: Vec<VaultRow>) -> Self {
|
|
let ctx = Context::default();
|
|
notescraft_ui_egui::fonts::install(&ctx);
|
|
notescraft_ui_egui::motion::set_enabled(&ctx, false);
|
|
ctx.all_styles_mut(|theme| theme.animation_time = 0.0);
|
|
let tokens = Tokens::new(notescraft_themes::builtin("catppuccin-mocha").expect("theme"));
|
|
notescraft_ui_egui::style::apply(&ctx, &tokens);
|
|
LauncherDriver { launcher: Launcher::new(rows, 1_792_454_400_000), ctx, time: 1.0, action: None }
|
|
}
|
|
|
|
/// One frame with `events`; keeps the last non-None action.
|
|
fn frame(&mut self, events: Vec<Event>) -> (Vec<Painted>, Vec<egui::OutputCommand>) {
|
|
self.time += 0.05;
|
|
let launcher = &mut self.launcher;
|
|
let tokens = Tokens::new(notescraft_themes::builtin("catppuccin-mocha").expect("theme"));
|
|
let time = self.time;
|
|
let action = &mut self.action;
|
|
let (texts, rects) = paint_texts(&mut self.ctx, (1440.0, 900.0), time, events, &mut |ui| {
|
|
let answered = launcher.show(ui.ctx(), &tokens);
|
|
if answered.is_some() {
|
|
*action = answered;
|
|
}
|
|
});
|
|
(texts, rects)
|
|
}
|
|
|
|
/// Frames until `wanted` is painted, with real time for the workers.
|
|
fn wait_for(&mut self, wanted: &str) -> Vec<Painted> {
|
|
for _ in 0..100 {
|
|
let (texts, _commands) = self.frame(Vec::new());
|
|
if texts.iter().any(|painted| painted.text.contains(wanted)) {
|
|
return texts;
|
|
}
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
let (texts, _commands) = self.frame(Vec::new());
|
|
panic!("never painted {wanted:?}; painted: {:?}", texts.iter().map(|painted| painted.text.as_str()).collect::<Vec<_>>());
|
|
}
|
|
|
|
/// Clicks `at` and settles: move, press and release as their own frames.
|
|
fn click(&mut self, at: Pos2) {
|
|
let _ = self.frame(vec![Event::PointerMoved(at)]);
|
|
let _ = self.frame(vec![Event::PointerMoved(at), button(at, true)]);
|
|
let _ = self.frame(vec![Event::PointerMoved(at), button(at, false)]);
|
|
for _ in 0..10 {
|
|
let _ = self.frame(Vec::new());
|
|
std::thread::sleep(Duration::from_millis(5));
|
|
}
|
|
}
|
|
|
|
/// Types `text` (into the focused field) and settles.
|
|
fn type_text(&mut self, text: &str) {
|
|
let _ = self.frame(type_text(text));
|
|
let _ = self.frame(Vec::new());
|
|
}
|
|
}
|
|
/// Opens the Share dialog of the app and settles it.
|
|
fn open_share(app: &mut AppDriver) {
|
|
app.app.run_command("ui.share", &serde_json::Value::Null);
|
|
let _ = app.settle();
|
|
}
|
|
|
|
/// The click on a painted label, focused for clicks, as raw button events.
|
|
fn click_at(text: &Painted) -> Pos2 {
|
|
text.pos + vec2(16.0, 10.0)
|
|
}
|
|
|
|
/// The members and the invites the stub answers for the bound vault.
|
|
fn stub_for_dialog() -> Stub {
|
|
let stub = Stub::spawn();
|
|
stub.route("GET", "/v1/vaults/v-1/members", 200, MEMBERS);
|
|
stub.route("GET", "/v1/vaults/v-1/invites", 200, INVITES);
|
|
stub.route("POST", "/v1/vaults/v-1/invites", 200, r#"{"code":"abcd-efgh-ijkl","expires_in_s":172800}"#);
|
|
stub.route("PATCH", "/v1/vaults/v-1/members/u-2", 204, "");
|
|
stub.route("DELETE", "/v1/vaults/v-1/members/u-2", 204, "");
|
|
stub
|
|
}
|
|
|
|
/// The dialog lists the members of the stub: names, chips and the invites.
|
|
#[test]
|
|
fn the_dialog_lists_the_members_of_the_stub() {
|
|
let stub = stub_for_dialog();
|
|
let mut app = AppDriver::over(&bound_vault("members", &stub.base));
|
|
open_share(&mut app);
|
|
let texts = app.frame(Vec::new());
|
|
assert!(texts.iter().any(|painted| painted.text.contains("Share \"")), "title");
|
|
for wanted in ["Marcos", "Ana", "Rui", "Owner", "INVITE SOMEONE", "Create invite", "PENDING INVITES", "Revoke"] {
|
|
assert!(texts.iter().any(|painted| painted.text.contains(wanted)), "missing {wanted}");
|
|
}
|
|
assert!(!texts.iter().any(|painted| painted.text.contains(TOKEN)), "the token never paints");
|
|
}
|
|
|
|
/// Create invite shows the code once and Copy puts it on the clipboard.
|
|
#[test]
|
|
fn create_invite_shows_the_code_and_copy_puts_it_on_the_clipboard() {
|
|
let stub = stub_for_dialog();
|
|
let mut app = AppDriver::over(&bound_vault("invite", &stub.base));
|
|
open_share(&mut app);
|
|
let texts = app.frame(Vec::new());
|
|
let at = painted(&texts, "Create invite").pos + vec2(48.0, 14.0);
|
|
app.click(at);
|
|
let texts = app.wait_for("abcd-efgh-ijkl");
|
|
assert!(texts.iter().any(|painted| painted.text.contains("works once and expires in 48 hours")));
|
|
let at = click_at(painted(&texts, "Copy"));
|
|
let _ = app.frame(vec![Event::PointerMoved(at)]);
|
|
let _ = app.frame(vec![Event::PointerMoved(at), button(at, true)]);
|
|
let _ = app.frame(vec![Event::PointerMoved(at), button(at, false)]);
|
|
assert!(
|
|
app.commands.iter().any(|command| matches!(command, egui::OutputCommand::CopyText(code) if code.contains("abcd-efgh-ijkl"))),
|
|
"copy put the code on the clipboard"
|
|
);
|
|
}
|
|
|
|
/// An owner changes a member's role and removes them; the stub confirms what
|
|
/// went to the server.
|
|
#[test]
|
|
fn set_role_and_remove_send_the_right_requests() {
|
|
let stub = stub_for_dialog();
|
|
let mut app = AppDriver::over(&bound_vault("role", &stub.base));
|
|
open_share(&mut app);
|
|
let texts = app.wait_for("Ana");
|
|
// The role chip of Ana (the rightmost "Viewer"), then Editor in its popup.
|
|
let chip = click_at(rightmost(&texts, "Viewer"));
|
|
app.click(chip);
|
|
let texts = app.settle();
|
|
app.click(click_at(nearest(&texts, "Editor", chip)));
|
|
let _ = app.wait_for("Rui");
|
|
let settled = stub.requests();
|
|
assert!(
|
|
settled.iter().any(|(method, path, body)| method == "PATCH" && path == "/v1/vaults/v-1/members/u-2" && body.contains("editor")),
|
|
"the role change went to the server: {settled:?}"
|
|
);
|
|
// The remove arms on a click and fires on the second one.
|
|
let texts = app.frame(Vec::new());
|
|
let remove = click_at(rightmost(&texts, "Remove"));
|
|
app.click(remove);
|
|
let texts = app.wait_for("Remove again");
|
|
app.click(click_at(painted(&texts, "Remove again")));
|
|
let _ = app.wait_for("Ana");
|
|
let settled = stub.requests();
|
|
assert!(
|
|
settled.iter().any(|(method, path, _body)| method == "DELETE" && path == "/v1/vaults/v-1/members/u-2"),
|
|
"the removal went to the server: {settled:?}"
|
|
);
|
|
}
|
|
|
|
/// A failing ask shows the server's own error text.
|
|
#[test]
|
|
fn a_server_error_text_is_shown() {
|
|
let stub = Stub::spawn();
|
|
stub.route("GET", "/v1/vaults/v-1/members", 200, MEMBERS);
|
|
stub.route("GET", "/v1/vaults/v-1/invites", 200, INVITES);
|
|
stub.route("POST", "/v1/vaults/v-1/invites", 500, r#"{"error":"no more invites today"}"#);
|
|
let mut app = AppDriver::over(&bound_vault("error", &stub.base));
|
|
open_share(&mut app);
|
|
let texts = app.frame(Vec::new());
|
|
app.click(click_at(painted(&texts, "Create invite")));
|
|
app.wait_for("no more invites today");
|
|
}
|
|
|
|
/// A vault that is not on a server shows the explanation and no list.
|
|
#[test]
|
|
fn an_unbound_vault_gets_the_explanation() {
|
|
let root = std::env::temp_dir().join(format!("notescraft-share-plain-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&root);
|
|
std::fs::create_dir_all(&root).expect("vault root");
|
|
std::fs::write(root.join("a.md"), "# A\n").expect("seed");
|
|
let mut app = AppDriver::over(&root);
|
|
open_share(&mut app);
|
|
let texts = app.settle();
|
|
assert!(texts.iter().any(|painted| painted.text.contains("not on a server yet")));
|
|
assert!(!texts.iter().any(|painted| painted.text.contains("People with access")));
|
|
// The connect button closes the dialog and opens the Sync page of the settings.
|
|
let texts = app.frame(Vec::new());
|
|
app.click(click_at(painted(&texts, "Connect to a server")));
|
|
assert!(app.app.share_dialog.is_none(), "the dialog closed");
|
|
}
|
|
|
|
/// Escape closes the dialog.
|
|
#[test]
|
|
fn escape_closes_a_dialog() {
|
|
let stub = stub_for_dialog();
|
|
let mut app = AppDriver::over(&bound_vault("escape", &stub.base));
|
|
open_share(&mut app);
|
|
assert!(app.app.share_dialog.is_some(), "the dialog is open");
|
|
let _ = app.frame(press(Key::Escape));
|
|
let _ = app.settle();
|
|
assert!(app.app.share_dialog.is_none(), "the dialog closed");
|
|
}
|
|
|
|
/// One launcher row: a local vault that exists on disk.
|
|
fn row_for(path: &str) -> VaultRow {
|
|
VaultRow {
|
|
path: path.to_owned(),
|
|
name: String::from("Notes"),
|
|
pinned: false,
|
|
last_opened_ms: 0,
|
|
exists: true,
|
|
sync: SyncBadge::Synced,
|
|
server: None,
|
|
role: None,
|
|
}
|
|
}
|
|
|
|
/// The pair and the vault list the stub answers for the connect flow.
|
|
fn stub_for_connect() -> Stub {
|
|
let stub = Stub::spawn();
|
|
stub.route("POST", "/v1/devices", 200, r#"{"device_id":"d-9","vault_id":"v-1","token":"secret-token"}"#);
|
|
stub.route(
|
|
"GET",
|
|
"/v1/vaults",
|
|
200,
|
|
r#"[{"id":"v-1","name":"Project Atlas","role":"owner","members":1,"bytes_used":10,"quota_bytes":null,"head_seq":1,"last_change_ms":1}]"#,
|
|
);
|
|
stub
|
|
}
|
|
|
|
/// Clicks the labelled launcher card.
|
|
fn click_card(launcher: &mut LauncherDriver, label: &str) {
|
|
let (texts, _commands) = launcher.frame(Vec::new());
|
|
let at = painted(&texts, label).pos + vec2(30.0, 10.0);
|
|
launcher.click(at);
|
|
}
|
|
|
|
/// Types `text` into the field under the painted `label`.
|
|
fn type_field(launcher: &mut LauncherDriver, label: &str, text: &str) {
|
|
let (texts, _commands) = launcher.frame(Vec::new());
|
|
// The field paints its hint (or its text) right after the label: click that, it is inside the field.
|
|
let index = texts.iter().position(|painted| painted.text == label);
|
|
let target = index.and_then(|index| texts.get(index + 1)).unwrap_or_else(|| painted(&texts, label));
|
|
launcher.click(target.pos + vec2(4.0, 4.0));
|
|
launcher.type_text(text);
|
|
}
|
|
|
|
/// Typing the fields and pressing Connect shows the vault list from the stub;
|
|
/// picking one and a folder returns the folder for the host.
|
|
#[test]
|
|
fn the_connect_flow_picks_a_vault_and_returns_the_folder() {
|
|
let stub = stub_for_connect();
|
|
let temp = std::env::temp_dir().join(format!("notescraft-connect-folder-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&temp);
|
|
let vault = bound_vault("connect", &stub.base);
|
|
let mut launcher = LauncherDriver::over(vec![row_for(vault.to_string_lossy().as_ref())]);
|
|
let _ = launcher.frame(Vec::new());
|
|
click_card(&mut launcher, "Connect to server");
|
|
type_field(&mut launcher, "Server", &stub.base);
|
|
type_field(&mut launcher, "Pairing code", "0000");
|
|
type_field(&mut launcher, "Folder", temp.to_string_lossy().as_ref());
|
|
click_card(&mut launcher, "Connect");
|
|
launcher.wait_for("Project Atlas");
|
|
// The vault row of the list, then the Connect of the bind step.
|
|
let (texts, _commands) = launcher.frame(Vec::new());
|
|
let at = painted(&texts, "Project Atlas").pos + vec2(40.0, 10.0);
|
|
launcher.click(at);
|
|
click_card(&mut launcher, "Connect");
|
|
launcher.wait_for("Connected to Project Atlas");
|
|
let action = launcher.action.clone().expect("the folder went to the host");
|
|
let LauncherAction::ConnectedFolder { path } = action else { panic!("expected the folder, got {action:?}") };
|
|
let binding = std::path::PathBuf::from(&path).join(".notescraft/sync/binding.json");
|
|
assert!(binding.exists(), "the folder is bound at {binding:?}");
|
|
}
|
|
|
|
/// Joining with a good code shows the preview and the folder; a bad code
|
|
/// shows the error and stays open.
|
|
#[test]
|
|
fn joining_shows_the_preview_and_returns_the_folder() {
|
|
let stub = Stub::spawn();
|
|
stub.route("POST", "/v1/invites/accept", 200, r#"{"vault_id":"v-9","name":"Project Atlas","role":"editor"}"#);
|
|
let vault = bound_vault("join", &stub.base);
|
|
let folder = std::env::temp_dir().join(format!("notescraft-join-folder-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&folder);
|
|
let mut launcher = LauncherDriver::over(vec![row_for(vault.to_string_lossy().as_ref())]);
|
|
let _ = launcher.frame(Vec::new());
|
|
click_card(&mut launcher, "Join with a code");
|
|
// Opening the dialog returned `JoinWithCode`; what follows is judged on its own.
|
|
launcher.action = None;
|
|
type_field(&mut launcher, "Invite code", "k7f2-9qxd-m3ta");
|
|
type_field(&mut launcher, "Folder", folder.to_string_lossy().as_ref());
|
|
click_card(&mut launcher, "Join and mount");
|
|
launcher.wait_for("you are Editor");
|
|
// The dialog shows the preview for one frame, then hands the folder to the host.
|
|
for _ in 0..3 {
|
|
let _ = launcher.frame(Vec::new());
|
|
}
|
|
let action = launcher.action.clone().expect("the folder went to the host");
|
|
let LauncherAction::ConnectedFolder { path } = action else { panic!("expected the folder, got {action:?}") };
|
|
assert_eq!(std::path::Path::new(&path), folder.as_path());
|
|
}
|
|
|
|
/// A bad code answers with the server's own error and the dialog stays open.
|
|
#[test]
|
|
fn a_bad_code_shows_the_error_and_stays_open() {
|
|
let stub = Stub::spawn();
|
|
stub.route("POST", "/v1/invites/accept", 401, r#"{"error":"invite is not valid"}"#);
|
|
let vault = bound_vault("bad-code", &stub.base);
|
|
let folder = std::env::temp_dir().join(format!("notescraft-bad-folder-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&folder);
|
|
let mut launcher = LauncherDriver::over(vec![row_for(vault.to_string_lossy().as_ref())]);
|
|
let _ = launcher.frame(Vec::new());
|
|
click_card(&mut launcher, "Join with a code");
|
|
// Opening the dialog returned `JoinWithCode`; what follows is judged on its own.
|
|
launcher.action = None;
|
|
type_field(&mut launcher, "Invite code", "k7f2-9qxd-m3ta");
|
|
type_field(&mut launcher, "Folder", folder.to_string_lossy().as_ref());
|
|
click_card(&mut launcher, "Join and mount");
|
|
launcher.wait_for("invite is not valid");
|
|
assert!(launcher.launcher.dialog_open(), "the dialog stayed open");
|
|
assert!(launcher.action.is_none(), "nothing returned on a bad code");
|
|
}
|
|
|
|
/// Escape closes the dialogs.
|
|
#[test]
|
|
fn escape_closes_a_dialog_launcher() {
|
|
let stub = stub_for_connect();
|
|
let vault = bound_vault("escape-connect", &stub.base);
|
|
let mut launcher = LauncherDriver::over(vec![row_for(vault.to_string_lossy().as_ref())]);
|
|
let _ = launcher.frame(Vec::new());
|
|
click_card(&mut launcher, "Connect to server");
|
|
assert!(launcher.launcher.dialog_open(), "the dialog opened");
|
|
let _ = launcher.frame(press(Key::Escape));
|
|
let _ = launcher.frame(Vec::new());
|
|
assert!(!launcher.launcher.dialog_open(), "escape closed the dialog");
|
|
click_card(&mut launcher, "Join with a code");
|
|
assert!(launcher.launcher.dialog_open());
|
|
let _ = launcher.frame(press(Key::Escape));
|
|
let _ = launcher.frame(Vec::new());
|
|
assert!(!launcher.launcher.dialog_open(), "escape closed the join dialog");
|
|
}
|