Files
Marcos Paulo 77d538dd97
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: Bases Cards, List, embeds, Map view, Maps settings and inline cell editing
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 04:45:32 -03:00

231 lines
9.4 KiB
Rust

//! The Cards and List views, driven headless over a fixture vault: an `![[a.png]]` cover resolves
//! to the attachment and paints its picture, a `#hex` value paints a colour block, a remote
//! address paints a placeholder and asks the engine for nothing, a click opens the note (Cmd-click
//! in a new tab), and the View settings popover writes the list and card keys.
use std::time::Duration;
use egui::{Color32, Vec2};
use egui_kittest::kittest::Queryable;
use notescraft_engine::{Registry, Session, register_core};
use notescraft_themes::builtin;
use notescraft_ui_egui::base_view::{self, BaseView};
use notescraft_ui_egui::theme::Tokens;
use serde_json::Value;
type Calls = std::rc::Rc<std::cell::RefCell<Vec<(String, Value)>>>;
struct Tab {
view: BaseView,
text: String,
tokens: Tokens,
session: Session,
registry: Registry<Session>,
warmed: bool,
calls: Calls,
opened: Vec<(String, bool)>,
}
const BASE: &str = "views:
- type: cards
name: Gallery
order:
- file.name
- note.year
image: note.cover
cardSize: 200
imageAspectRatio: 0.5
- type: list
name: Titles
order:
- file.name
- note.year
markers: numbers
";
const PICTURE_A: &[u8] = include_bytes!("fixtures/cover-a.png");
const PICTURE_B: &[u8] = include_bytes!("fixtures/cover-b.png");
const BLUE: Color32 = Color32::from_rgb(0x33, 0x66, 0x99);
fn vault(name: &str) -> std::path::PathBuf {
let root = std::env::temp_dir().join(format!("notescraft-base-cards-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("Books")).expect("books folder");
std::fs::create_dir_all(root.join("Pics")).expect("pics folder");
std::fs::write(root.join("Pics/a.png"), PICTURE_A).expect("picture a");
std::fs::write(root.join("Pics/b.png"), PICTURE_B).expect("picture b");
let notes = [
("dune", "1965", "\"![[a.png]]\""),
("emma", "1815", "\"#336699\""),
("faust", "1808", "\"https://example.com/faust.png\""),
("gone", "1900", "\"![[missing.png]]\""),
("plain", "1999", "\"Pics/b.png\""),
];
for (name, year, cover) in notes {
std::fs::write(root.join(format!("Books/{name}.md")), format!("---\nyear: {year}\ncover: {cover}\n---\n{name}\n")).expect("book");
}
std::fs::write(root.join("Books/bare.md"), "---\nyear: 2001\n---\nbare\n").expect("bare");
root
}
fn tab(name: &str) -> egui_kittest::Harness<'static, Tab> {
let session = Session::open(&vault(name)).expect("the vault opens");
let mut registry = Registry::new();
register_core(&mut registry).expect("commands register");
let state = Tab {
view: BaseView::new("Gallery.base"),
text: BASE.to_owned(),
tokens: Tokens::new(builtin("catppuccin-mocha").expect("theme")),
session,
registry,
warmed: false,
calls: Calls::default(),
opened: Vec::new(),
};
egui_kittest::Harness::builder().with_size(Vec2::new(1000.0, 700.0)).with_max_steps(300).build_ui_state(
|ui, tab: &mut Tab| {
if !tab.warmed {
notescraft_ui_egui::fonts::install(ui.ctx());
egui_extras::install_image_loaders(ui.ctx());
tab.warmed = true;
return;
}
let shown = base_view::show(ui, &tab.tokens, &mut tab.view, &mut tab.text, true);
tab.opened.extend(shown.open.map(|link| (link.target, link.new_tab)));
let Tab { view, session, registry, calls, .. } = tab;
let ran = view.pump(&mut |id, params| {
calls.borrow_mut().push((id.to_owned(), params.clone()));
registry.run(id, session, params).map_err(|error| error.to_string())
});
if ran {
ui.ctx().request_repaint();
}
},
state,
)
}
/// Frames until `done` holds; the pictures decode on worker threads, so frames wait for them.
fn settle(h: &mut egui_kittest::Harness<'_, Tab>, done: impl Fn(&Tab) -> bool) {
for _ in 0..300 {
h.run();
if done(h.state()) {
return;
}
std::thread::sleep(Duration::from_millis(10));
}
}
fn painted(tab: &Tab, path: &str) -> Vec<base_view::Painted> {
let Some(data) = tab.view.data() else { return Vec::new() };
tab.view.covers_painted().iter().filter(|(ordinal, _)| data.row(*ordinal).is_some_and(|row| row.path == path)).map(|(_, kind)| kind.clone()).collect()
}
fn pictures_ready(tab: &Tab) -> bool {
painted(tab, "Books/dune.md").iter().any(|p| matches!(p, base_view::Painted::Image(_)))
&& painted(tab, "Books/plain.md").iter().any(|p| matches!(p, base_view::Painted::Image(_)))
}
#[test]
fn a_wiki_link_cover_resolves_to_the_attachment_and_paints_it() {
let mut h = tab("link");
settle(&mut h, pictures_ready);
assert_eq!(painted(h.state(), "Books/dune.md"), [base_view::Painted::Image("Pics/a.png".into())]);
assert_eq!(painted(h.state(), "Books/plain.md"), [base_view::Painted::Image("Pics/b.png".into())], "a plain path is a target too");
assert_eq!(painted(h.state(), "Books/gone.md"), [base_view::Painted::Missing], "no such file");
assert_eq!(painted(h.state(), "Books/bare.md"), [base_view::Painted::Blank], "no value, no cover");
let asked: Vec<Value> = h.state().calls.borrow().iter().filter(|(id, _)| id == "base.resolve").map(|(_, params)| params["targets"][0].clone()).collect();
assert!(asked.contains(&Value::from("a.png")) && asked.contains(&Value::from("Pics/b.png")), "{asked:?}");
}
#[test]
fn a_hex_value_paints_a_colour_block() {
let mut h = tab("hex");
settle(&mut h, pictures_ready);
assert_eq!(painted(h.state(), "Books/emma.md"), [base_view::Painted::Colour(BLUE)]);
let image = h.render().expect("renders");
let blue = image.pixels().filter(|pixel| pixel.0[..3] == [BLUE.r(), BLUE.g(), BLUE.b()]).count();
assert!(blue > 2000, "the block fills a cover: {blue} pixels");
}
#[test]
fn a_remote_address_is_a_placeholder_and_nothing_is_fetched() {
let mut h = tab("remote");
settle(&mut h, pictures_ready);
assert_eq!(painted(h.state(), "Books/faust.md"), [base_view::Painted::Remote("example.com".into())]);
let calls = h.state().calls.borrow();
assert!(calls.iter().all(|(_, params)| !params.to_string().contains("example.com") || params["yaml"].is_string()), "the engine never saw the address");
assert!(calls.iter().filter(|(id, _)| id == "base.resolve").all(|(_, params)| !params["targets"][0].as_str().unwrap_or_default().starts_with("http")));
assert_eq!(h.state().view.covers_cached(), 2, "only the two vault pictures were decoded");
}
#[test]
fn a_click_opens_the_note_and_cmd_click_a_new_tab() {
let mut h = tab("click");
settle(&mut h, pictures_ready);
h.get_by_label("Books/dune.md").click();
h.run();
assert_eq!(h.state().opened, [("Books/dune.md".to_owned(), false)]);
assert_eq!(h.state().view.selected_row(), h.state().view.data().and_then(|d| (0..d.total).find(|i| d.row(*i).is_some_and(|r| r.path == "Books/dune.md"))));
h.get_by_label("Books/emma.md").click_modifiers(egui::Modifiers::COMMAND);
h.run();
assert_eq!(h.state().opened.last(), Some(&("Books/emma.md".to_owned(), true)));
}
#[test]
fn the_view_settings_popover_writes_the_list_and_card_keys() {
let mut h = tab("settings");
settle(&mut h, pictures_ready);
h.get_by_label("View settings").click();
h.run();
h.run();
h.get_by_label("Large").click();
h.run();
assert!(h.state().text.contains("cardSize: 320"), "{}", h.state().text);
h.get_by_label("Contain").click();
h.run();
assert!(h.state().text.contains("imageFit: contain"), "{}", h.state().text);
h.get_by_label("View settings").click();
h.run();
h.state_mut().view.view = 1;
settle(&mut h, |tab| tab.view.data().is_some());
h.run();
assert!(h.state().view.rows_painted() >= 6, "the list paints its rows: {}", h.state().view.rows_painted());
h.get_by_label("View settings").click();
h.run();
h.run();
h.get_by_label("Bullets").click();
h.run();
assert!(h.state().text.contains("markers: bullets"), "{}", h.state().text);
h.get_by_label("On").click();
h.run();
assert!(h.state().text.contains("indentProperties: true"), "{}", h.state().text);
}
fn save(h: &mut egui_kittest::Harness<'_, Tab>, dir: &str, name: &str) {
let image = h.render().expect("renders");
std::fs::create_dir_all(dir).expect("dir");
image.save(std::path::Path::new(dir).join(name)).expect("png");
}
/// Renders the layouts to PNGs for a visual check: `NOTESCRAFT_BASE_PNG_DIR=<dir> cargo test --test base_cards -- --ignored`.
#[test]
#[ignore = "writes PNGs for a visual check"]
fn render_pngs() {
let Ok(dir) = std::env::var("NOTESCRAFT_BASE_PNG_DIR") else { return };
let mut h = tab("png");
settle(&mut h, pictures_ready);
save(&mut h, &dir, "cards.png");
h.state_mut().text = BASE.replace("imageAspectRatio: 0.5\n", "imageAspectRatio: 1.5\n imageFit: contain\n").replace("cardSize: 200", "cardSize: 150");
settle(&mut h, pictures_ready);
save(&mut h, &dir, "cards-contain.png");
h.state_mut().view.view = 1;
h.run();
h.run();
save(&mut h, &dir, "list-numbers.png");
h.state_mut().text = BASE.replace("markers: numbers", "indentProperties: true\n markers: none");
h.run();
h.run();
save(&mut h, &dir, "list-indent.png");
}