Files
Marcos Paulo 1d06b71950
ci / ci (macos-latest) (push) Has been cancelled
ci / ci (ubuntu-latest) (push) Has been cancelled
ci / ci (windows-latest) (push) Has been cancelled
feat: Publish and links section in the Share dialog
Published pages (copy, unpublish), publish this note, read-only links with expiry choices; the secret link is shown once and never in lists, logs or toasts; viewers see lists without buttons; destructive buttons click twice. Re-exports PublicationKind from the engine. Built by MiniMax M3.1 Flash (OpenCode Zen free route); verified from a clean checkout of the staged files: 908 lib tests, publish_ui 8 and share_ui 10 pass, clippy -D warnings on ui-egui and engine and xtask tree clean. Open: the shell does not pass the note into the dialog yet and the card needs to scroll on short screens.

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

512 lines
22 KiB
Rust

//! The "Publish and links" section of the Share dialog, driven the way a user
//! does: real pointer events through whole frames, over a real session with a
//! bound vault and a stub server that speaks the publish routes.
//!
//! The stub keeps the pages and the links of the vault, so an unpublish takes
//! a page away and a minted link shows up in the list without its secret.
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
use egui::{Context, Event, PointerButton, Pos2, RawInput, Rect, vec2};
use notescraft_engine::{Session, bind_folder};
use notescraft_ui_egui::theme::Tokens;
use notescraft_ui_egui::views::share_dialog::ShareDialog;
/// The token of the bound vault; it must never reach a painted text.
const TOKEN: &str = "secret-token";
/// The secret of a minted link; it shows once and never in the list.
const SECRET: &str = "link-secret-9f2";
/// The vault of the stub.
const VAULT: &str = "v-1";
/// Milliseconds of one day.
const DAY_MS: u64 = 86_400_000;
/// Seconds of thirty days, the lifetime of a month.
const MONTH_SECS: &str = "2592000";
/// The members the stub answers with: an owner and a viewer.
const MEMBERS_OWNER: &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}]"##
);
/// The members of a vault whose account is a viewer.
const MEMBERS_VIEWER: &str = r##"[{"user_id":"u-1","name":"Marcos","color":"#cba6f7","role":"viewer","last_seen_ms":1}]"##;
/// 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,
}
/// What the stub keeps: the published pages and the share links.
struct Server {
/// The members of the vault, as the server lists them.
members: String,
/// The published pages, as `(id, url path)`.
publications: Vec<(String, String)>,
/// The share links, as `(id, path)`.
links: Vec<(String, String)>,
/// Every request, in order.
seen: Vec<Request>,
}
impl Server {
/// The pages the vault publishes, as the server lists them.
fn publications_json(&self) -> String {
let rows: Vec<String> =
self.publications.iter().map(|(id, path)| format!(r#"{{"id":"{id}","kind":"note","target":"a.md","url_path":"{path}","created_ms":1}}"#)).collect();
format!("[{}]", rows.join(","))
}
/// The links of the vault, as the server lists them; never a secret.
fn links_json(&self) -> String {
let expires = now_ms() + 7 * DAY_MS;
let rows: Vec<String> =
self.links.iter().map(|(id, path)| format!(r#"{{"id":"{id}","path":"{path}","created_ms":1,"expires_ms":{expires},"revoked":false}}"#)).collect();
format!("[{}]", rows.join(","))
}
}
/// A stub server that speaks the publish routes of the sync server.
struct Stub {
/// The base URL of the stub.
base: String,
/// The state of the stub.
state: Arc<Mutex<Server>>,
/// 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 state = Arc::new(Mutex::new(Server { members: MEMBERS_OWNER.to_owned(), publications: Vec::new(), links: Vec::new(), seen: Vec::new() }));
let stop = Arc::new(AtomicBool::new(false));
let thread = (Arc::clone(&state), Arc::clone(&stop));
let handle = std::thread::spawn(move || {
while !thread.1.load(Ordering::Relaxed) {
match listener.accept() {
Ok((stream, _)) => {
let _ = stream.set_nonblocking(false);
let Ok(mut writer) = stream.try_clone() else { continue };
let state = Arc::clone(&thread.0);
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 = answer(&state, &request);
write_answer(&mut writer, answer.0, &answer.1);
}
});
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(2));
}
Err(_) => break,
}
}
});
let _ = handle;
Self { base: format!("http://127.0.0.1:{port}"), state, stop }
}
/// The state of the stub.
fn state(&self) -> MutexGuard<'_, Server> {
self.state.lock().expect("state")
}
/// Every request the stub received, as `(method, path, body)`.
fn requests(&self) -> Vec<(String, String, String)> {
self.state().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);
}
}
/// The answer of the stub for one request: the status and the body.
fn answer(state: &Mutex<Server>, request: &Request) -> (u16, String) {
let mut server = state.lock().expect("state");
server.seen.push(request.clone());
let path = request.path.as_str();
if request.method == "GET" && path == format!("/v1/vaults/{VAULT}/members") {
return (200, server.members.clone());
}
if request.method == "GET" && path == format!("/v1/vaults/{VAULT}/invites") {
return (200, "[]".to_owned());
}
if request.method == "GET" && path == format!("/v1/vaults/{VAULT}/publications") {
return (200, server.publications_json());
}
if request.method == "GET" && path == format!("/v1/vaults/{VAULT}/share-links") {
return (200, server.links_json());
}
if request.method == "POST" && path == format!("/v1/vaults/{VAULT}/publications") {
let target = field(&request.body, "target");
let id = format!("pub-{}", server.publications.len() + 1);
let url_path = format!("/p/slug/{target}");
server.publications.push((id.clone(), url_path.clone()));
return (200, format!(r#"{{"id":"{id}","slug":"slug","url_path":"{url_path}"}}"#));
}
if request.method == "POST" && path == format!("/v1/vaults/{VAULT}/share-links") {
let note = field(&request.body, "path");
let id = format!("l-{}", server.links.len() + 1);
server.links.push((id.clone(), note));
let expires = now_ms() + 7 * DAY_MS;
return (200, format!(r#"{{"id":"{id}","url_path":"/s/{SECRET}","expires_ms":{expires}}}"#));
}
if request.method == "DELETE" && path.starts_with(&format!("/v1/vaults/{VAULT}/publications/")) {
let id = path.rsplit('/').next().unwrap_or_default().to_owned();
server.publications.retain(|(page, _)| *page != id);
return (204, String::new());
}
if request.method == "DELETE" && path.starts_with(&format!("/v1/vaults/{VAULT}/share-links/")) {
let id = path.rsplit('/').next().unwrap_or_default().to_owned();
server.links.retain(|(link, _)| *link != id);
return (204, String::new());
}
(404, r#"{"error":"no such route"}"#.to_owned())
}
/// The value of a field of a JSON body, when it is there.
fn field(body: &str, name: &str) -> String {
let key = format!("\"{name}\"");
let Some(start) = body.find(&key) else { return String::new() };
let rest = body.get(start + key.len()..).unwrap_or_default();
let Some(colon) = rest.find(':') else { return String::new() };
let rest = rest.get(colon + 1..).unwrap_or_default().trim_start();
let Some(value) = rest.strip_prefix('"') else { return String::new() };
let end = value.find('"').unwrap_or_default();
value.get(..end).unwrap_or_default().to_owned()
}
/// 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 current Unix time in milliseconds.
fn now_ms() -> u64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX))
}
/// A vault bound to the stub, with one note in it.
fn bound_vault(name: &str, base: &str) -> std::path::PathBuf {
let root = std::env::temp_dir().join(format!("notescraft-publish-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).expect("vault root");
bind_folder(&root, base, VAULT, 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.
#[derive(Debug)]
struct Painted {
/// The text of the shape.
text: String,
/// Where the text starts.
pos: Pos2,
}
/// The Share dialog over a vault, driven with real events.
struct Driver {
/// The dialog under test.
dialog: ShareDialog,
/// The egui context that paints it.
ctx: Context,
/// The clock of the frames.
time: f64,
/// The commands of the frames since the last click.
commands: Vec<egui::OutputCommand>,
}
impl Driver {
/// The dialog over `vault`, about the note `note`.
fn over(vault: &std::path::Path, note: Option<&str>) -> Self {
let session = Session::open(vault).expect("session");
let dialog = ShareDialog::open_for("Project Atlas", &session, note);
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);
Driver { dialog, ctx, 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 tokens = Tokens::new(notescraft_themes::builtin("catppuccin-mocha").expect("theme"));
let input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), time: Some(self.time), events, ..Default::default() };
let dialog = &mut self.dialog;
let mut out = self.ctx.run_ui(input, |ui| {
dialog.show(ui.ctx(), &tokens);
});
out.textures_delta.clear();
self.commands.extend(out.platform_output.commands);
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()
}
/// Frames until `wanted` is painted and its place stops moving; the texts.
///
/// The card grows while the jobs answer, so a click has to wait for the
/// layout to settle.
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 self.settled(wanted);
}
std::thread::sleep(Duration::from_millis(10));
}
panic!("never painted {wanted:?}");
}
/// Frames until `wanted` is gone and its place stops moving; the texts.
fn wait_until_gone(&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!("{wanted:?} never went away");
}
/// Frames until the place of `wanted` stops moving; the last texts.
fn settled(&mut self, wanted: &str) -> Vec<Painted> {
let mut texts = Vec::new();
let mut last = None;
for _ in 0..20 {
texts = self.frame(Vec::new());
let place = texts.iter().find(|painted| painted.text.contains(wanted)).map(|painted| painted.pos);
if place.is_some() && place == last {
return texts;
}
last = place;
std::thread::sleep(Duration::from_millis(10));
}
texts
}
/// Frames with real time for the workers; 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> {
self.commands.clear();
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));
}
self.frame(Vec::new())
}
}
/// 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 }
}
/// The painted `text`, or a panic.
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 click on a painted label, as raw button events.
fn click_at(text: &Painted) -> Pos2 {
text.pos + vec2(16.0, 10.0)
}
/// The dialog lists the published pages of the vault with their URL.
#[test]
fn the_dialog_lists_the_published_pages() {
let stub = Stub::spawn();
stub.state().publications.push(("pub-1".to_owned(), "/p/slug/a.md".to_owned()));
let mut app = Driver::over(&bound_vault("list", &stub.base), Some("a.md"));
let texts = app.wait_for("/p/slug/a.md");
assert!(texts.iter().any(|painted| painted.text.contains("PUBLISH AND LINKS")), "the section is there");
assert!(texts.iter().any(|painted| painted.text == "Note"), "the kind of the page");
assert!(texts.iter().any(|painted| painted.text == "Unpublish"), "the unpublish button");
assert!(!texts.iter().any(|painted| painted.text.contains(TOKEN)), "the token never paints");
}
/// The copy button of a published page puts its URL on the clipboard.
#[test]
fn the_copy_button_puts_the_url_on_the_clipboard() {
let stub = Stub::spawn();
stub.state().publications.push(("pub-1".to_owned(), "/p/slug/a.md".to_owned()));
let mut app = Driver::over(&bound_vault("copy", &stub.base), Some("a.md"));
let texts = app.wait_for("/p/slug/a.md");
app.click(click_at(painted(&texts, "Copy")));
assert!(
app.commands.iter().any(|command| matches!(command, egui::OutputCommand::CopyText(url) if url.contains("/p/slug/a.md"))),
"copy put the url on the clipboard"
);
}
/// Publishing the note of the dialog shows its public URL.
#[test]
fn publishing_the_note_shows_its_url() {
let stub = Stub::spawn();
let mut app = Driver::over(&bound_vault("publish", &stub.base), Some("a.md"));
let texts = app.wait_for("Publish this note");
app.click(click_at(painted(&texts, "Publish this note")));
let texts = app.wait_for("/p/slug/a.md");
assert!(texts.iter().any(|painted| painted.text.contains("This page is public")), "the note that says so");
let seen = stub.requests();
assert!(
seen.iter().any(|(method, path, body)| method == "POST" && path == "/v1/vaults/v-1/publications" && body.contains("a.md")),
"the page went to the server: {seen:?}"
);
}
/// Unpublishing takes the page away and tells the server.
#[test]
fn unpublishing_takes_the_page_away() {
let stub = Stub::spawn();
stub.state().publications.push(("pub-1".to_owned(), "/p/slug/a.md".to_owned()));
let mut app = Driver::over(&bound_vault("unpublish", &stub.base), Some("a.md"));
let texts = app.wait_for("/p/slug/a.md");
app.click(click_at(painted(&texts, "Unpublish")));
let texts = app.wait_for("Click again");
app.click(click_at(painted(&texts, "Click again")));
let texts = app.wait_until_gone("/p/slug/a.md");
assert!(!texts.iter().any(|painted| painted.text == "Unpublish"), "the row is gone");
let seen = stub.requests();
assert!(
seen.iter().any(|(method, path, _body)| method == "DELETE" && path == "/v1/vaults/v-1/publications/pub-1"),
"the unpublish went to the server: {seen:?}"
);
}
/// A minted link shows its secret once; the list row never carries it.
#[test]
fn a_minted_link_shows_its_secret_once() {
let stub = Stub::spawn();
let mut app = Driver::over(&bound_vault("mint", &stub.base), Some("a.md"));
let texts = app.wait_for("Create link");
app.click(click_at(painted(&texts, "Create link")));
let texts = app.wait_for(SECRET);
assert!(texts.iter().any(|painted| painted.text.contains("shown only once")), "the note that says so");
let secrets: Vec<&Painted> = texts.iter().filter(|painted| painted.text.contains(SECRET)).collect();
assert_eq!(secrets.len(), 1, "the secret shows once: {secrets:?}");
let row = texts.iter().find(|painted| painted.text == "a.md").expect("the row of the link");
assert!(!row.text.contains(SECRET), "the row carries no secret");
}
/// The expiry of a link is the one the user picked.
#[test]
fn the_expiry_of_a_link_is_the_one_picked() {
let stub = Stub::spawn();
let mut app = Driver::over(&bound_vault("expiry", &stub.base), Some("a.md"));
let texts = app.wait_for("Create link");
app.click(click_at(painted(&texts, "30 days")));
let texts = app.wait_for("Create link");
app.click(click_at(painted(&texts, "Create link")));
app.wait_for(SECRET);
let seen = stub.requests();
let minted = seen
.iter()
.find(|(method, path, _body)| method == "POST" && path == "/v1/vaults/v-1/share-links")
.unwrap_or_else(|| panic!("the link was minted: {seen:?}"));
assert!(minted.2.contains(MONTH_SECS), "thirty days in seconds: {}", minted.2);
}
/// A viewer sees the lists but no buttons.
#[test]
fn a_viewer_sees_the_lists_without_the_buttons() {
let stub = Stub::spawn();
stub.state().members = MEMBERS_VIEWER.to_owned();
stub.state().publications.push(("pub-1".to_owned(), "/p/slug/a.md".to_owned()));
stub.state().links.push(("l-0".to_owned(), "notes/b.md".to_owned()));
let mut app = Driver::over(&bound_vault("viewer", &stub.base), Some("a.md"));
app.wait_for("Marcos");
let texts = app.wait_for("/p/slug/a.md");
assert!(texts.iter().any(|painted| painted.text.contains("PUBLISH AND LINKS")), "the section is there");
assert!(texts.iter().any(|painted| painted.text.contains("notes/b.md")), "the list of the links");
assert!(!texts.iter().any(|painted| painted.text == "Unpublish"), "no button for a viewer");
assert!(!texts.iter().any(|painted| painted.text == "Revoke"), "no button for a viewer");
assert!(!texts.iter().any(|painted| painted.text == "Create link"), "no button for a viewer");
assert!(!texts.iter().any(|painted| painted.text == "Publish this note"), "no button for a viewer");
assert!(!texts.iter().any(|painted| painted.text == "Copy"), "no button for a viewer");
}
/// A vault that is not on a server shows nothing of the section.
#[test]
fn an_unbound_vault_shows_nothing() {
let root = std::env::temp_dir().join(format!("notescraft-publish-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 = Driver::over(&root, Some("a.md"));
let texts = app.settle();
assert!(!texts.iter().any(|painted| painted.text.contains("PUBLISH AND LINKS")), "no section without a server");
assert!(texts.iter().any(|painted| painted.text.contains("not on a server yet")), "the explanation");
}