feat: finishing of M0
This commit is contained in:
@@ -28,7 +28,7 @@ impl Database {
|
||||
}
|
||||
|
||||
/// Run all pending migrations.
|
||||
pub fn migrate(&self) -> Result<(), Box<dyn std::error::Error>> {
|
||||
pub fn migrate(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
migrations::run_migrations(&self.conn)
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,35 @@
|
||||
use deunicode::deunicode;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// Pre-process German characters to match TypeScript `transliteration` npm output.
|
||||
/// deunicode maps ä→a, ö→o, ü→u but TypeScript produces ä→ae, ö→oe, ü→ue.
|
||||
/// We replace these before deunicode so the slug output is compatible.
|
||||
fn german_transliterate(input: &str) -> String {
|
||||
let mut result = String::with_capacity(input.len() + 16);
|
||||
for c in input.chars() {
|
||||
match c {
|
||||
'ä' => result.push_str("ae"),
|
||||
'ö' => result.push_str("oe"),
|
||||
'ü' => result.push_str("ue"),
|
||||
'Ä' => result.push_str("Ae"),
|
||||
'Ö' => result.push_str("Oe"),
|
||||
'Ü' => result.push_str("Ue"),
|
||||
_ => result.push(c),
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Generate a URL-safe slug from a title string.
|
||||
///
|
||||
/// Transliterates Unicode to ASCII, lowercases, replaces non-alphanumeric
|
||||
/// chars with hyphens, and collapses/trims hyphens.
|
||||
///
|
||||
/// German umlauts (ä/ö/ü/Ä/Ö/Ü) are pre-processed to ae/oe/ue/Ae/Oe/Ue
|
||||
/// to match TypeScript `transliteration` npm output. ß→ss is handled by deunicode.
|
||||
pub fn slugify(input: &str) -> String {
|
||||
let ascii = deunicode(input);
|
||||
let preprocessed = german_transliterate(input);
|
||||
let ascii = deunicode(&preprocessed);
|
||||
let lowered = ascii.to_lowercase();
|
||||
let mut slug = String::with_capacity(lowered.len());
|
||||
let mut prev_hyphen = true; // avoid leading hyphen
|
||||
@@ -61,7 +84,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn unicode_slug() {
|
||||
assert_eq!(slugify("Über die Brücke"), "uber-die-brucke");
|
||||
assert_eq!(slugify("Über die Brücke"), "ueber-die-bruecke");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -102,6 +125,58 @@ mod tests {
|
||||
assert_eq!(slug, "hello-4");
|
||||
}
|
||||
|
||||
// German umlaut tests — spec: "only German and English letters are used.
|
||||
// Verify deunicode handles ä/ö/ü/ß/ÄÖÜ correctly against transliteration npm."
|
||||
// Pre-processing maps ä→ae, ö→oe, ü→ue to match TypeScript transliteration npm.
|
||||
// ß→ss is handled correctly by deunicode without pre-processing.
|
||||
|
||||
#[test]
|
||||
fn german_umlaut_ae() {
|
||||
assert_eq!(slugify("Ärger"), "aerger");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn german_umlaut_oe() {
|
||||
assert_eq!(slugify("Öffnung"), "oeffnung");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn german_umlaut_ue() {
|
||||
assert_eq!(slugify("Über"), "ueber");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn german_eszett() {
|
||||
assert_eq!(slugify("Straße"), "strasse");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn german_mixed_umlauts() {
|
||||
assert_eq!(slugify("Größe über Maße"), "groesse-ueber-masse");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn german_uppercase_umlauts() {
|
||||
assert_eq!(slugify("ÄÖÜ Test"), "aeoeue-test");
|
||||
}
|
||||
|
||||
// spec: CreatePost uses Slug.generate(title ?? "untitled")
|
||||
// When title is empty/whitespace, slugify should produce "untitled" equivalent
|
||||
#[test]
|
||||
fn whitespace_only_input() {
|
||||
assert_eq!(slugify(" "), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leading_trailing_special() {
|
||||
assert_eq!(slugify("---hello---"), "hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_only() {
|
||||
assert_eq!(slugify("2024"), "2024");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ensure_unique_all_999_taken() {
|
||||
let slug = ensure_unique("x", |s| {
|
||||
|
||||
561
crates/bds-core/tests/fixture_readability.rs
Normal file
561
crates/bds-core/tests/fixture_readability.rs
Normal file
@@ -0,0 +1,561 @@
|
||||
//! Integration tests that open the real fixture DB extracted from the TypeScript bDS app
|
||||
//! and verify every table can be read correctly into Rust model structs.
|
||||
//!
|
||||
//! This validates the compatibility contract: the Rust app MUST read databases
|
||||
//! created by the TypeScript app without modification.
|
||||
|
||||
use rusqlite::{Connection, OpenFlags};
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn fixture_db() -> Connection {
|
||||
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../fixtures/compatibility-projects/rfc1437-sample/bds.db");
|
||||
assert!(path.exists(), "fixture DB not found at {}", path.display());
|
||||
Connection::open_with_flags(&path, OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap()
|
||||
}
|
||||
|
||||
const PROJECT_ID: &str = "1979237c-034d-41f6-99a0-f35eb57b3f6c";
|
||||
|
||||
// ── Project ─────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn read_project() {
|
||||
let conn = fixture_db();
|
||||
let (id, name, slug, data_path, is_active): (String, String, String, String, bool) = conn
|
||||
.query_row(
|
||||
"SELECT id, name, slug, data_path, is_active FROM projects WHERE id = ?1",
|
||||
[PROJECT_ID],
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(id, PROJECT_ID);
|
||||
assert_eq!(name, "rfc1437");
|
||||
assert_eq!(slug, "rfc1437");
|
||||
assert!(data_path.contains("rfc1437.de"));
|
||||
assert!(is_active);
|
||||
}
|
||||
|
||||
// ── Posts ────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn read_published_post_has_null_content() {
|
||||
let conn = fixture_db();
|
||||
let (title, slug, status, content): (String, String, String, Option<String>) = conn
|
||||
.query_row(
|
||||
"SELECT title, slug, status, content FROM posts WHERE slug = 'esmeralda'",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(title, "Esmeralda");
|
||||
assert_eq!(slug, "esmeralda");
|
||||
assert_eq!(status, "published");
|
||||
assert!(content.is_none(), "published posts must have NULL content in DB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_draft_post_has_content() {
|
||||
let conn = fixture_db();
|
||||
let (title, slug, status, content): (String, String, String, Option<String>) = conn
|
||||
.query_row(
|
||||
"SELECT title, slug, status, content FROM posts WHERE slug = 'draft-fixture-post'",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(title, "Draft Fixture Post");
|
||||
assert_eq!(slug, "draft-fixture-post");
|
||||
assert_eq!(status, "draft");
|
||||
assert!(content.is_some(), "draft posts must have content in DB");
|
||||
assert!(content.unwrap().contains("**body**"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_all_posts_count() {
|
||||
let conn = fixture_db();
|
||||
let count: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM posts", [], |row| row.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(count, 4); // 3 published + 1 draft
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn published_posts_have_file_paths() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT slug, file_path FROM posts WHERE status = 'published'")
|
||||
.unwrap();
|
||||
let rows: Vec<(String, String)> = stmt
|
||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
assert_eq!(rows.len(), 3);
|
||||
for (slug, path) in &rows {
|
||||
assert!(!path.is_empty(), "published post '{slug}' must have a file_path");
|
||||
assert!(path.ends_with(&format!("{slug}.md")), "file_path must end with {slug}.md");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_tags_are_json_arrays() {
|
||||
let conn = fixture_db();
|
||||
let tags_json: Option<String> = conn
|
||||
.query_row(
|
||||
"SELECT tags FROM posts WHERE slug = 'esmeralda'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
if let Some(json) = tags_json {
|
||||
let parsed: Vec<String> = serde_json::from_str(&json).unwrap();
|
||||
assert!(!parsed.is_empty());
|
||||
}
|
||||
// tags can also be NULL — both are valid
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_timestamps_are_unix_integers() {
|
||||
let conn = fixture_db();
|
||||
let (created_at, updated_at): (i64, i64) = conn
|
||||
.query_row(
|
||||
"SELECT created_at, updated_at FROM posts WHERE slug = 'esmeralda'",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Sanity: timestamps should be in reasonable Unix range (year 2000+)
|
||||
assert!(created_at > 946_684_800, "created_at should be after year 2000");
|
||||
assert!(updated_at > 946_684_800, "updated_at should be after year 2000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_unique_constraint_on_project_slug() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT project_id, slug, COUNT(*) FROM posts GROUP BY project_id, slug HAVING COUNT(*) > 1")
|
||||
.unwrap();
|
||||
let dupes: Vec<(String, String, i64)> = stmt
|
||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
assert!(dupes.is_empty(), "found duplicate (project_id, slug) pairs: {dupes:?}");
|
||||
}
|
||||
|
||||
// ── Post Translations ───────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn read_post_translations() {
|
||||
let conn = fixture_db();
|
||||
let count: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM post_translations", [], |row| row.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(count, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translation_references_valid_post() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT pt.id, pt.translation_for FROM post_translations pt \
|
||||
LEFT JOIN posts p ON pt.translation_for = p.id \
|
||||
WHERE p.id IS NULL",
|
||||
)
|
||||
.unwrap();
|
||||
let orphans: Vec<(String, String)> = stmt
|
||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
assert!(orphans.is_empty(), "orphan translations referencing missing posts: {orphans:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn published_translations_have_null_content() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT id, content FROM post_translations WHERE status = 'published'")
|
||||
.unwrap();
|
||||
let rows: Vec<(String, Option<String>)> = stmt
|
||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
for (id, content) in &rows {
|
||||
assert!(content.is_none(), "published translation {id} must have NULL content");
|
||||
}
|
||||
}
|
||||
|
||||
// ── Post Links ──────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn read_post_links() {
|
||||
let conn = fixture_db();
|
||||
let (source, target, text): (String, String, Option<String>) = conn
|
||||
.query_row(
|
||||
"SELECT source_post_id, target_post_id, link_text FROM post_links LIMIT 1",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// ghostty links to cmux
|
||||
assert_eq!(source, "6745981d-da41-4cfd-80ec-95ad339acf6f");
|
||||
assert_eq!(target, "2665bfaa-8251-468d-a710-a4cf34dd81e2");
|
||||
assert!(text.is_some());
|
||||
}
|
||||
|
||||
// ── Post Media ──────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn read_post_media() {
|
||||
let conn = fixture_db();
|
||||
let (post_id, media_id, sort_order): (String, String, i32) = conn
|
||||
.query_row(
|
||||
"SELECT post_id, media_id, sort_order FROM post_media LIMIT 1",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// esmeralda <-> spider photo
|
||||
assert_eq!(post_id, "40a83ab1-423d-4310-aac4-642d84675007");
|
||||
assert_eq!(media_id, "eb0cf9d7-6fbd-4b74-9be3-759d6e16f240");
|
||||
assert_eq!(sort_order, 0);
|
||||
}
|
||||
|
||||
// ── Media ───────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn read_media() {
|
||||
let conn = fixture_db();
|
||||
let (id, filename, original_name, mime_type, title, alt): (
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
) = conn
|
||||
.query_row(
|
||||
"SELECT id, filename, original_name, mime_type, title, alt FROM media LIMIT 1",
|
||||
[],
|
||||
|row| {
|
||||
Ok((
|
||||
row.get(0)?,
|
||||
row.get(1)?,
|
||||
row.get(2)?,
|
||||
row.get(3)?,
|
||||
row.get(4)?,
|
||||
row.get(5)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(id, "eb0cf9d7-6fbd-4b74-9be3-759d6e16f240");
|
||||
assert!(filename.ends_with(".jpg"));
|
||||
assert_eq!(original_name, "CRW_1121.jpg");
|
||||
assert_eq!(mime_type, "image/jpeg");
|
||||
assert!(title.is_some());
|
||||
assert!(alt.is_some());
|
||||
}
|
||||
|
||||
// ── Tags ────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn read_tags() {
|
||||
let conn = fixture_db();
|
||||
let count: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM tags", [], |row| row.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(count, 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tag_names_are_expected() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn.prepare("SELECT name FROM tags ORDER BY name").unwrap();
|
||||
let names: Vec<String> = stmt
|
||||
.query_map([], |row| row.get(0))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
assert_eq!(names, vec!["fotografie", "mac-os-x", "natur", "programmierung", "sysadmin"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tag_unique_constraint_on_project_name() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT project_id, name, COUNT(*) FROM tags GROUP BY project_id, name HAVING COUNT(*) > 1")
|
||||
.unwrap();
|
||||
let dupes: Vec<(String, String, i64)> = stmt
|
||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
assert!(dupes.is_empty(), "found duplicate (project_id, name) tag pairs: {dupes:?}");
|
||||
}
|
||||
|
||||
// ── Templates ───────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn read_template() {
|
||||
let conn = fixture_db();
|
||||
let (slug, title, kind, enabled, status, content): (
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
bool,
|
||||
String,
|
||||
Option<String>,
|
||||
) = conn
|
||||
.query_row(
|
||||
"SELECT slug, title, kind, enabled, status, content FROM templates LIMIT 1",
|
||||
[],
|
||||
|row| {
|
||||
Ok((
|
||||
row.get(0)?,
|
||||
row.get(1)?,
|
||||
row.get(2)?,
|
||||
row.get(3)?,
|
||||
row.get(4)?,
|
||||
row.get(5)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(slug, "testvorlage");
|
||||
assert_eq!(title, "Testvorlage");
|
||||
assert_eq!(kind, "post");
|
||||
assert!(enabled);
|
||||
assert_eq!(status, "published");
|
||||
assert!(content.is_none(), "published template content should be NULL in DB");
|
||||
}
|
||||
|
||||
// ── Scripts ─────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn read_scripts() {
|
||||
let conn = fixture_db();
|
||||
let count: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM scripts", [], |row| row.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(count, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_script_fields() {
|
||||
let conn = fixture_db();
|
||||
let (slug, title, kind, entrypoint, enabled, status): (
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
bool,
|
||||
String,
|
||||
) = conn
|
||||
.query_row(
|
||||
"SELECT slug, title, kind, entrypoint, enabled, status FROM scripts WHERE slug = 'bgg_link'",
|
||||
[],
|
||||
|row| {
|
||||
Ok((
|
||||
row.get(0)?,
|
||||
row.get(1)?,
|
||||
row.get(2)?,
|
||||
row.get(3)?,
|
||||
row.get(4)?,
|
||||
row.get(5)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(slug, "bgg_link");
|
||||
assert_eq!(title, "bgg link");
|
||||
assert_eq!(kind, "transform");
|
||||
assert_eq!(entrypoint, "normalize_blogmark");
|
||||
assert!(enabled);
|
||||
assert_eq!(status, "published");
|
||||
}
|
||||
|
||||
// ── Settings ────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn read_settings() {
|
||||
let conn = fixture_db();
|
||||
let count: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM settings", [], |row| row.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(count, 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_are_key_value_pairs() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn.prepare("SELECT key, value FROM settings").unwrap();
|
||||
let pairs: Vec<(String, String)> = stmt
|
||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
for (key, value) in &pairs {
|
||||
assert!(!key.is_empty());
|
||||
assert!(!value.is_empty());
|
||||
}
|
||||
// All setting keys should contain the project ID (namespaced)
|
||||
let project_keys: Vec<_> = pairs.iter().filter(|(k, _)| k.contains(PROJECT_ID)).collect();
|
||||
assert_eq!(project_keys.len(), 5);
|
||||
}
|
||||
|
||||
// ── AI Catalog ──────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn read_ai_tables() {
|
||||
let conn = fixture_db();
|
||||
|
||||
let providers: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM ai_providers", [], |row| row.get(0))
|
||||
.unwrap();
|
||||
let models: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM ai_models", [], |row| row.get(0))
|
||||
.unwrap();
|
||||
let meta: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM ai_catalog_meta", [], |row| row.get(0))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(providers, 1);
|
||||
assert_eq!(models, 1);
|
||||
assert_eq!(meta, 2);
|
||||
}
|
||||
|
||||
// ── Generated File Hashes ───────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn read_generated_file_hashes_via_settings() {
|
||||
// The fixture stores generation hashes as settings keys
|
||||
let conn = fixture_db();
|
||||
let count: i64 = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM settings WHERE key LIKE '%generation-hash%'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(count > 0, "expected generation hash entries in settings");
|
||||
}
|
||||
|
||||
// ── Cross-table referential integrity ───────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn all_posts_belong_to_existing_project() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT p.id FROM posts p \
|
||||
LEFT JOIN projects pr ON p.project_id = pr.id \
|
||||
WHERE pr.id IS NULL",
|
||||
)
|
||||
.unwrap();
|
||||
let orphans: Vec<String> = stmt
|
||||
.query_map([], |row| row.get(0))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
assert!(orphans.is_empty(), "posts referencing missing projects: {orphans:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_tags_belong_to_existing_project() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT t.id FROM tags t \
|
||||
LEFT JOIN projects pr ON t.project_id = pr.id \
|
||||
WHERE pr.id IS NULL",
|
||||
)
|
||||
.unwrap();
|
||||
let orphans: Vec<String> = stmt
|
||||
.query_map([], |row| row.get(0))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
assert!(orphans.is_empty(), "tags referencing missing projects: {orphans:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_media_belong_to_existing_project() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT m.id FROM media m \
|
||||
LEFT JOIN projects pr ON m.project_id = pr.id \
|
||||
WHERE pr.id IS NULL",
|
||||
)
|
||||
.unwrap();
|
||||
let orphans: Vec<String> = stmt
|
||||
.query_map([], |row| row.get(0))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
assert!(orphans.is_empty(), "media referencing missing projects: {orphans:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_links_reference_valid_posts() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT pl.id, pl.source_post_id, pl.target_post_id FROM post_links pl \
|
||||
LEFT JOIN posts s ON pl.source_post_id = s.id \
|
||||
LEFT JOIN posts t ON pl.target_post_id = t.id \
|
||||
WHERE s.id IS NULL OR t.id IS NULL",
|
||||
)
|
||||
.unwrap();
|
||||
let orphans: Vec<(String, String, String)> = stmt
|
||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
assert!(orphans.is_empty(), "post_links with invalid references: {orphans:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_media_references_valid_entities() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT pm.id FROM post_media pm \
|
||||
LEFT JOIN posts p ON pm.post_id = p.id \
|
||||
LEFT JOIN media m ON pm.media_id = m.id \
|
||||
WHERE p.id IS NULL OR m.id IS NULL",
|
||||
)
|
||||
.unwrap();
|
||||
let orphans: Vec<String> = stmt
|
||||
.query_map([], |row| row.get(0))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
assert!(orphans.is_empty(), "post_media with invalid references: {orphans:?}");
|
||||
}
|
||||
505
crates/bds-core/tests/spec_claims.rs
Normal file
505
crates/bds-core/tests/spec_claims.rs
Normal file
@@ -0,0 +1,505 @@
|
||||
//! Tests that verify allium spec claims against the Rust model and DB code.
|
||||
//!
|
||||
//! Each test is annotated with the spec invariant or rule it validates.
|
||||
|
||||
use rusqlite::{Connection, OpenFlags};
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn fixture_db() -> Connection {
|
||||
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../fixtures/compatibility-projects/rfc1437-sample/bds.db");
|
||||
Connection::open_with_flags(&path, OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap()
|
||||
}
|
||||
|
||||
fn memory_db() -> Connection {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
conn.execute_batch("PRAGMA foreign_keys=ON;").unwrap();
|
||||
bds_core::db::run_migrations(&conn).unwrap();
|
||||
conn
|
||||
}
|
||||
|
||||
// ── spec: post.allium — PostStatus serde matches DB string values ────
|
||||
|
||||
#[test]
|
||||
fn post_status_serde_matches_db_values() {
|
||||
// spec: status: draft | published | archived
|
||||
use bds_core::model::PostStatus;
|
||||
|
||||
assert_eq!(serde_json::to_string(&PostStatus::Draft).unwrap(), "\"draft\"");
|
||||
assert_eq!(serde_json::to_string(&PostStatus::Published).unwrap(), "\"published\"");
|
||||
assert_eq!(serde_json::to_string(&PostStatus::Archived).unwrap(), "\"archived\"");
|
||||
|
||||
// round-trip
|
||||
let d: PostStatus = serde_json::from_str("\"draft\"").unwrap();
|
||||
assert_eq!(d, PostStatus::Draft);
|
||||
let p: PostStatus = serde_json::from_str("\"published\"").unwrap();
|
||||
assert_eq!(p, PostStatus::Published);
|
||||
let a: PostStatus = serde_json::from_str("\"archived\"").unwrap();
|
||||
assert_eq!(a, PostStatus::Archived);
|
||||
}
|
||||
|
||||
// ── spec: schema.allium — Template kind: post | list | not_found | partial ──
|
||||
|
||||
#[test]
|
||||
fn template_kind_serde_matches_db_values() {
|
||||
use bds_core::model::TemplateKind;
|
||||
|
||||
assert_eq!(serde_json::to_string(&TemplateKind::Post).unwrap(), "\"post\"");
|
||||
assert_eq!(serde_json::to_string(&TemplateKind::List).unwrap(), "\"list\"");
|
||||
assert_eq!(serde_json::to_string(&TemplateKind::NotFound).unwrap(), "\"not_found\"");
|
||||
assert_eq!(serde_json::to_string(&TemplateKind::Partial).unwrap(), "\"partial\"");
|
||||
|
||||
let nf: TemplateKind = serde_json::from_str("\"not_found\"").unwrap();
|
||||
assert_eq!(nf, TemplateKind::NotFound);
|
||||
}
|
||||
|
||||
// ── spec: schema.allium — Template status: draft | published ──
|
||||
|
||||
#[test]
|
||||
fn template_status_serde_matches_db_values() {
|
||||
use bds_core::model::TemplateStatus;
|
||||
|
||||
assert_eq!(serde_json::to_string(&TemplateStatus::Draft).unwrap(), "\"draft\"");
|
||||
assert_eq!(serde_json::to_string(&TemplateStatus::Published).unwrap(), "\"published\"");
|
||||
}
|
||||
|
||||
// ── spec: schema.allium — Script kind: macro | utility | transform ──
|
||||
|
||||
#[test]
|
||||
fn script_kind_serde_matches_db_values() {
|
||||
use bds_core::model::ScriptKind;
|
||||
|
||||
assert_eq!(serde_json::to_string(&ScriptKind::Macro).unwrap(), "\"macro\"");
|
||||
assert_eq!(serde_json::to_string(&ScriptKind::Utility).unwrap(), "\"utility\"");
|
||||
assert_eq!(serde_json::to_string(&ScriptKind::Transform).unwrap(), "\"transform\"");
|
||||
|
||||
let t: ScriptKind = serde_json::from_str("\"transform\"").unwrap();
|
||||
assert_eq!(t, ScriptKind::Transform);
|
||||
}
|
||||
|
||||
// ── spec: schema.allium — Script status: draft | published ──
|
||||
|
||||
#[test]
|
||||
fn script_status_serde_matches_db_values() {
|
||||
use bds_core::model::ScriptStatus;
|
||||
|
||||
assert_eq!(serde_json::to_string(&ScriptStatus::Draft).unwrap(), "\"draft\"");
|
||||
assert_eq!(serde_json::to_string(&ScriptStatus::Published).unwrap(), "\"published\"");
|
||||
}
|
||||
|
||||
// ── spec: post.allium — content_location invariant ──
|
||||
// "if status = published: file_path else: content"
|
||||
// Published posts have NULL content in DB; draft posts have content in DB.
|
||||
|
||||
#[test]
|
||||
fn content_location_published_posts_null_content_in_fixture() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT slug, content FROM posts WHERE status = 'published'")
|
||||
.unwrap();
|
||||
let rows: Vec<(String, Option<String>)> = stmt
|
||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
assert!(!rows.is_empty());
|
||||
for (slug, content) in &rows {
|
||||
assert!(content.is_none(), "spec: published post '{slug}' must have NULL content in DB");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_location_draft_posts_have_content_in_fixture() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT slug, content FROM posts WHERE status = 'draft'")
|
||||
.unwrap();
|
||||
let rows: Vec<(String, Option<String>)> = stmt
|
||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
assert!(!rows.is_empty());
|
||||
for (slug, content) in &rows {
|
||||
assert!(content.is_some(), "spec: draft post '{slug}' must have content in DB");
|
||||
}
|
||||
}
|
||||
|
||||
// ── spec: post.allium — all status transitions allowed ──
|
||||
// draft -> published, draft -> archived, published -> draft,
|
||||
// published -> archived, archived -> draft, archived -> published
|
||||
|
||||
#[test]
|
||||
fn post_status_transitions_all_valid() {
|
||||
let conn = memory_db();
|
||||
conn.execute(
|
||||
"INSERT INTO projects (id, name, slug, created_at, updated_at, is_active) \
|
||||
VALUES ('p1', 'test', 'test', 1000, 1000, 1)",
|
||||
[],
|
||||
).unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO posts (id, project_id, title, slug, status, file_path, created_at, updated_at) \
|
||||
VALUES ('post1', 'p1', 'Test', 'test', 'draft', '', 1000, 1000)",
|
||||
[],
|
||||
).unwrap();
|
||||
|
||||
let transitions = [
|
||||
("draft", "published"),
|
||||
("published", "draft"),
|
||||
("draft", "archived"),
|
||||
("archived", "draft"),
|
||||
("draft", "published"),
|
||||
("published", "archived"),
|
||||
("archived", "published"),
|
||||
];
|
||||
|
||||
for (from, to) in transitions {
|
||||
// Set to 'from' state first
|
||||
conn.execute("UPDATE posts SET status = ?1 WHERE id = 'post1'", [from]).unwrap();
|
||||
// Transition to 'to' state
|
||||
conn.execute("UPDATE posts SET status = ?1 WHERE id = 'post1'", [to]).unwrap();
|
||||
let status: String = conn
|
||||
.query_row("SELECT status FROM posts WHERE id = 'post1'", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(status, to, "transition {from} -> {to} failed");
|
||||
}
|
||||
}
|
||||
|
||||
// ── spec: post.allium — is_slug_frozen: published_at != null ──
|
||||
// Slug changes only allowed before first publish
|
||||
|
||||
#[test]
|
||||
fn slug_frozen_after_publish_semantics() {
|
||||
let conn = memory_db();
|
||||
conn.execute(
|
||||
"INSERT INTO projects (id, name, slug, created_at, updated_at, is_active) \
|
||||
VALUES ('p1', 'test', 'test', 1000, 1000, 1)",
|
||||
[],
|
||||
).unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO posts (id, project_id, title, slug, status, file_path, created_at, updated_at, published_at) \
|
||||
VALUES ('post1', 'p1', 'Test', 'test', 'published', 'posts/2024/01/test.md', 1000, 1000, 1000)",
|
||||
[],
|
||||
).unwrap();
|
||||
|
||||
// published_at is set — slug should be considered frozen
|
||||
let published_at: Option<i64> = conn
|
||||
.query_row("SELECT published_at FROM posts WHERE id = 'post1'", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert!(published_at.is_some(), "spec: is_slug_frozen = published_at != null");
|
||||
|
||||
// A never-published draft has no published_at — slug is mutable
|
||||
conn.execute(
|
||||
"INSERT INTO posts (id, project_id, title, slug, status, file_path, created_at, updated_at) \
|
||||
VALUES ('post2', 'p1', 'Draft', 'draft-post', 'draft', '', 1000, 1000)",
|
||||
[],
|
||||
).unwrap();
|
||||
let draft_published_at: Option<i64> = conn
|
||||
.query_row("SELECT published_at FROM posts WHERE id = 'post2'", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert!(draft_published_at.is_none(), "spec: unpublished draft has no published_at");
|
||||
}
|
||||
|
||||
// ── spec: project.allium — SingleActiveProject invariant ──
|
||||
// "Exactly one project is active at any time"
|
||||
|
||||
#[test]
|
||||
fn single_active_project_in_fixture() {
|
||||
let conn = fixture_db();
|
||||
let active_count: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM projects WHERE is_active = 1", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(active_count, 1, "spec: exactly one project is active");
|
||||
}
|
||||
|
||||
// ── spec: project.allium — UniqueProjectSlug invariant ──
|
||||
|
||||
#[test]
|
||||
fn unique_project_slug_in_fixture() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT slug, COUNT(*) FROM projects GROUP BY slug HAVING COUNT(*) > 1")
|
||||
.unwrap();
|
||||
let dupes: Vec<(String, i64)> = stmt
|
||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
assert!(dupes.is_empty(), "spec: project slug must be unique");
|
||||
}
|
||||
|
||||
// ── spec: translation.allium — UniqueTranslationPerLanguage ──
|
||||
// "post_translations must have unique (translation_for, language)"
|
||||
|
||||
#[test]
|
||||
fn unique_translation_per_post_language_in_fixture() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT translation_for, language, COUNT(*) FROM post_translations \
|
||||
GROUP BY translation_for, language HAVING COUNT(*) > 1",
|
||||
)
|
||||
.unwrap();
|
||||
let dupes: Vec<(String, String, i64)> = stmt
|
||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
assert!(dupes.is_empty(), "spec: translation unique per (post, language)");
|
||||
}
|
||||
|
||||
// ── spec: schema.allium — Post defaults ──
|
||||
// status default 'draft', do_not_translate default false, file_path default ''
|
||||
|
||||
#[test]
|
||||
fn post_defaults_match_spec() {
|
||||
let conn = memory_db();
|
||||
conn.execute(
|
||||
"INSERT INTO projects (id, name, slug, created_at, updated_at, is_active) \
|
||||
VALUES ('p1', 'test', 'test', 1000, 1000, 1)",
|
||||
[],
|
||||
).unwrap();
|
||||
// Insert with minimal columns to test defaults
|
||||
conn.execute(
|
||||
"INSERT INTO posts (id, project_id, title, slug, created_at, updated_at) \
|
||||
VALUES ('min1', 'p1', 'Minimal', 'minimal', 1000, 1000)",
|
||||
[],
|
||||
).unwrap();
|
||||
|
||||
let (status, do_not_translate, file_path): (String, bool, String) = conn
|
||||
.query_row(
|
||||
"SELECT status, do_not_translate, file_path FROM posts WHERE id = 'min1'",
|
||||
[],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(status, "draft", "spec: default status is draft");
|
||||
assert!(!do_not_translate, "spec: default do_not_translate is false");
|
||||
assert_eq!(file_path, "", "spec: default file_path is empty string");
|
||||
}
|
||||
|
||||
// ── spec: schema.allium — Script defaults ──
|
||||
// kind default 'utility', entrypoint default 'render', enabled default true,
|
||||
// version default 1, status default 'published'
|
||||
|
||||
#[test]
|
||||
fn script_defaults_match_spec() {
|
||||
let conn = memory_db();
|
||||
conn.execute(
|
||||
"INSERT INTO projects (id, name, slug, created_at, updated_at, is_active) \
|
||||
VALUES ('p1', 'test', 'test', 1000, 1000, 1)",
|
||||
[],
|
||||
).unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO scripts (id, project_id, slug, title, file_path, created_at, updated_at) \
|
||||
VALUES ('s1', 'p1', 'test', 'Test', 'scripts/test.lua', 1000, 1000)",
|
||||
[],
|
||||
).unwrap();
|
||||
|
||||
let (kind, entrypoint, enabled, version, status): (String, String, bool, i32, String) = conn
|
||||
.query_row(
|
||||
"SELECT kind, entrypoint, enabled, version, status FROM scripts WHERE id = 's1'",
|
||||
[],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(kind, "utility", "spec: default kind is utility");
|
||||
assert_eq!(entrypoint, "render", "spec: default entrypoint is 'render'");
|
||||
assert!(enabled, "spec: default enabled is true");
|
||||
assert_eq!(version, 1, "spec: default version is 1");
|
||||
assert_eq!(status, "published", "spec: default status is published");
|
||||
}
|
||||
|
||||
// ── spec: schema.allium — Template defaults ──
|
||||
// kind default 'post', enabled default true, version default 1, status default 'published'
|
||||
|
||||
#[test]
|
||||
fn template_defaults_match_spec() {
|
||||
let conn = memory_db();
|
||||
conn.execute(
|
||||
"INSERT INTO projects (id, name, slug, created_at, updated_at, is_active) \
|
||||
VALUES ('p1', 'test', 'test', 1000, 1000, 1)",
|
||||
[],
|
||||
).unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO templates (id, project_id, slug, title, file_path, created_at, updated_at) \
|
||||
VALUES ('t1', 'p1', 'test', 'Test', 'templates/test.liquid', 1000, 1000)",
|
||||
[],
|
||||
).unwrap();
|
||||
|
||||
let (kind, enabled, version, status): (String, bool, i32, String) = conn
|
||||
.query_row(
|
||||
"SELECT kind, enabled, version, status FROM templates WHERE id = 't1'",
|
||||
[],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(kind, "post", "spec: default kind is post");
|
||||
assert!(enabled, "spec: default enabled is true");
|
||||
assert_eq!(version, 1, "spec: default version is 1");
|
||||
assert_eq!(status, "published", "spec: default status is published");
|
||||
}
|
||||
|
||||
// ── spec: tag.allium — UniqueTagNamePerProject (case-insensitive) ──
|
||||
|
||||
#[test]
|
||||
fn tag_unique_name_per_project_enforced() {
|
||||
let conn = memory_db();
|
||||
conn.execute(
|
||||
"INSERT INTO projects (id, name, slug, created_at, updated_at, is_active) \
|
||||
VALUES ('p1', 'test', 'test', 1000, 1000, 1)",
|
||||
[],
|
||||
).unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO tags (id, project_id, name, created_at, updated_at) \
|
||||
VALUES ('t1', 'p1', 'rust', 1000, 1000)",
|
||||
[],
|
||||
).unwrap();
|
||||
|
||||
// Same name, same project — must fail
|
||||
let result = conn.execute(
|
||||
"INSERT INTO tags (id, project_id, name, created_at, updated_at) \
|
||||
VALUES ('t2', 'p1', 'rust', 1000, 1000)",
|
||||
[],
|
||||
);
|
||||
assert!(result.is_err(), "spec: duplicate tag name in same project must fail");
|
||||
}
|
||||
|
||||
// ── spec: post.allium — Slug generation algorithm ──
|
||||
// "transliterate unicode to ASCII, lowercase, replace [^a-z0-9]+ with hyphens,
|
||||
// strip leading/trailing hyphens"
|
||||
|
||||
#[test]
|
||||
fn slug_generation_matches_spec_algorithm() {
|
||||
use bds_core::util::slugify;
|
||||
|
||||
// Basic: lowercase + hyphen separation
|
||||
assert_eq!(slugify("Hello World"), "hello-world");
|
||||
|
||||
// Non-alphanumeric replaced with single hyphen
|
||||
assert_eq!(slugify("a --- b"), "a-b");
|
||||
|
||||
// Leading/trailing hyphens stripped
|
||||
assert_eq!(slugify("---hello---"), "hello");
|
||||
|
||||
// Unicode transliteration
|
||||
assert_eq!(slugify("café"), "cafe");
|
||||
|
||||
// German umlauts (spec: "only German and English letters used")
|
||||
assert_eq!(slugify("über"), "ueber");
|
||||
assert_eq!(slugify("Ärger"), "aerger");
|
||||
assert_eq!(slugify("Öffnung"), "oeffnung");
|
||||
assert_eq!(slugify("Straße"), "strasse");
|
||||
}
|
||||
|
||||
// ── spec: post.allium — Slug uniqueness algorithm ──
|
||||
// "tries base, then {slug}-2 .. {slug}-999, then {slug}-{timestamp}"
|
||||
|
||||
#[test]
|
||||
fn slug_uniqueness_matches_spec() {
|
||||
use bds_core::util::ensure_unique;
|
||||
|
||||
// Base available
|
||||
assert_eq!(ensure_unique("test", |_| false), "test");
|
||||
|
||||
// Base taken → -2
|
||||
assert_eq!(ensure_unique("test", |s| s == "test"), "test-2");
|
||||
|
||||
// -2 and -3 taken → -4
|
||||
assert_eq!(
|
||||
ensure_unique("test", |s| s == "test" || s == "test-2" || s == "test-3"),
|
||||
"test-4"
|
||||
);
|
||||
}
|
||||
|
||||
// ── spec: frontmatter.allium — PostFileLayout ──
|
||||
// "posts/{YYYY}/{MM}/{slug}.md"
|
||||
|
||||
#[test]
|
||||
fn published_post_file_paths_follow_date_layout() {
|
||||
let conn = fixture_db();
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT slug, file_path, created_at FROM posts WHERE status = 'published' AND file_path != ''")
|
||||
.unwrap();
|
||||
let rows: Vec<(String, String, i64)> = stmt
|
||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
|
||||
.unwrap()
|
||||
.map(|r| r.unwrap())
|
||||
.collect();
|
||||
|
||||
for (slug, path, _created_at) in &rows {
|
||||
// Path should end with {slug}.md
|
||||
assert!(
|
||||
path.ends_with(&format!("{slug}.md")),
|
||||
"spec: file_path must end with {{slug}}.md, got: {path}"
|
||||
);
|
||||
// Path should contain posts/YYYY/MM/ pattern
|
||||
assert!(
|
||||
path.contains("/posts/"),
|
||||
"spec: file_path must contain /posts/, got: {path}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── spec: cli_sync.allium — DbNotification entity_type values ──
|
||||
|
||||
#[test]
|
||||
fn notification_entity_serde_matches_db_values() {
|
||||
use bds_core::model::{NotificationEntity, NotificationAction};
|
||||
|
||||
assert_eq!(serde_json::to_string(&NotificationEntity::Post).unwrap(), "\"post\"");
|
||||
assert_eq!(serde_json::to_string(&NotificationEntity::Media).unwrap(), "\"media\"");
|
||||
assert_eq!(serde_json::to_string(&NotificationEntity::Script).unwrap(), "\"script\"");
|
||||
assert_eq!(serde_json::to_string(&NotificationEntity::Template).unwrap(), "\"template\"");
|
||||
|
||||
assert_eq!(serde_json::to_string(&NotificationAction::Created).unwrap(), "\"created\"");
|
||||
assert_eq!(serde_json::to_string(&NotificationAction::Updated).unwrap(), "\"updated\"");
|
||||
assert_eq!(serde_json::to_string(&NotificationAction::Deleted).unwrap(), "\"deleted\"");
|
||||
}
|
||||
|
||||
// ── spec: generation.allium / publishing.allium — SshMode values ──
|
||||
|
||||
#[test]
|
||||
fn ssh_mode_serde_matches_spec() {
|
||||
use bds_core::model::SshMode;
|
||||
|
||||
assert_eq!(serde_json::to_string(&SshMode::Scp).unwrap(), "\"scp\"");
|
||||
assert_eq!(serde_json::to_string(&SshMode::Rsync).unwrap(), "\"rsync\"");
|
||||
}
|
||||
|
||||
// ── spec: i18n.allium — SplitLocalization ──
|
||||
// Verify that the 5 supported UI languages exist as config
|
||||
|
||||
#[test]
|
||||
fn supported_languages_match_spec() {
|
||||
// spec: en, de, fr, it, es — the 5 supported UI languages
|
||||
let supported = ["en", "de", "fr", "it", "es"];
|
||||
assert_eq!(supported.len(), 5);
|
||||
// This test documents the spec constraint; actual locale loading
|
||||
// will be tested when i18n module is implemented in M2+
|
||||
}
|
||||
|
||||
// ── spec: schema.allium — FTS5 virtual tables exist in fixture ──
|
||||
|
||||
#[test]
|
||||
fn fts5_tables_exist_in_fixture() {
|
||||
let conn = fixture_db();
|
||||
|
||||
// posts_fts
|
||||
let result = conn.query_row(
|
||||
"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='posts_fts'",
|
||||
[],
|
||||
|r| r.get::<_, i64>(0),
|
||||
);
|
||||
assert_eq!(result.unwrap(), 1, "spec: posts_fts virtual table must exist");
|
||||
|
||||
// media_fts
|
||||
let result = conn.query_row(
|
||||
"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='media_fts'",
|
||||
[],
|
||||
|r| r.get::<_, i64>(0),
|
||||
);
|
||||
assert_eq!(result.unwrap(), 1, "spec: media_fts virtual table must exist");
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
use ropey::Rope;
|
||||
|
||||
/// Rope-based text buffer with edit operations.
|
||||
/// Rope-based text buffer with edit operations and cursor management.
|
||||
pub struct EditorBuffer {
|
||||
rope: Rope,
|
||||
/// Cursor byte offset within the rope.
|
||||
cursor_line: usize,
|
||||
cursor_col: usize,
|
||||
/// Vertical scroll offset in lines.
|
||||
scroll_offset: usize,
|
||||
}
|
||||
|
||||
impl EditorBuffer {
|
||||
@@ -14,6 +15,7 @@ impl EditorBuffer {
|
||||
rope: Rope::from_str(text),
|
||||
cursor_line: 0,
|
||||
cursor_col: 0,
|
||||
scroll_offset: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +43,10 @@ impl EditorBuffer {
|
||||
(self.cursor_line, self.cursor_col)
|
||||
}
|
||||
|
||||
pub fn scroll_offset(&self) -> usize {
|
||||
self.scroll_offset
|
||||
}
|
||||
|
||||
pub fn set_cursor(&mut self, line: usize, col: usize) {
|
||||
self.cursor_line = line.min(self.line_count().saturating_sub(1));
|
||||
let line_len = self.current_line_len();
|
||||
@@ -51,7 +57,6 @@ impl EditorBuffer {
|
||||
pub fn insert(&mut self, text: &str) {
|
||||
let char_idx = self.cursor_char_idx();
|
||||
self.rope.insert(char_idx, text);
|
||||
// Advance cursor past inserted text
|
||||
for c in text.chars() {
|
||||
if c == '\n' {
|
||||
self.cursor_line += 1;
|
||||
@@ -69,12 +74,11 @@ impl EditorBuffer {
|
||||
self.rope.remove(char_idx - 1..char_idx);
|
||||
self.cursor_col -= 1;
|
||||
} else if self.cursor_line > 0 {
|
||||
// Join with previous line
|
||||
let prev_line_len = self
|
||||
.rope
|
||||
.line(self.cursor_line - 1)
|
||||
.len_chars()
|
||||
.saturating_sub(1); // subtract newline
|
||||
.saturating_sub(1);
|
||||
let char_idx = self.cursor_char_idx();
|
||||
self.rope.remove(char_idx - 1..char_idx);
|
||||
self.cursor_line -= 1;
|
||||
@@ -82,6 +86,85 @@ impl EditorBuffer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete one character after the cursor (delete key).
|
||||
pub fn delete_forward(&mut self) {
|
||||
let char_idx = self.cursor_char_idx();
|
||||
if char_idx < self.rope.len_chars() {
|
||||
self.rope.remove(char_idx..char_idx + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Move cursor up one line.
|
||||
pub fn move_up(&mut self) {
|
||||
if self.cursor_line > 0 {
|
||||
self.cursor_line -= 1;
|
||||
let line_len = self.current_line_len();
|
||||
self.cursor_col = self.cursor_col.min(line_len);
|
||||
}
|
||||
}
|
||||
|
||||
/// Move cursor down one line.
|
||||
pub fn move_down(&mut self) {
|
||||
if self.cursor_line + 1 < self.line_count() {
|
||||
self.cursor_line += 1;
|
||||
let line_len = self.current_line_len();
|
||||
self.cursor_col = self.cursor_col.min(line_len);
|
||||
}
|
||||
}
|
||||
|
||||
/// Move cursor left one character.
|
||||
pub fn move_left(&mut self) {
|
||||
if self.cursor_col > 0 {
|
||||
self.cursor_col -= 1;
|
||||
} else if self.cursor_line > 0 {
|
||||
self.cursor_line -= 1;
|
||||
self.cursor_col = self.current_line_len();
|
||||
}
|
||||
}
|
||||
|
||||
/// Move cursor right one character.
|
||||
pub fn move_right(&mut self) {
|
||||
let line_len = self.current_line_len();
|
||||
if self.cursor_col < line_len {
|
||||
self.cursor_col += 1;
|
||||
} else if self.cursor_line + 1 < self.line_count() {
|
||||
self.cursor_line += 1;
|
||||
self.cursor_col = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Move cursor to start of line.
|
||||
pub fn move_home(&mut self) {
|
||||
self.cursor_col = 0;
|
||||
}
|
||||
|
||||
/// Move cursor to end of line.
|
||||
pub fn move_end(&mut self) {
|
||||
self.cursor_col = self.current_line_len();
|
||||
}
|
||||
|
||||
/// Scroll so the cursor is visible within the given viewport height (in lines).
|
||||
pub fn ensure_cursor_visible(&mut self, visible_lines: usize) {
|
||||
if visible_lines == 0 {
|
||||
return;
|
||||
}
|
||||
if self.cursor_line < self.scroll_offset {
|
||||
self.scroll_offset = self.cursor_line;
|
||||
} else if self.cursor_line >= self.scroll_offset + visible_lines {
|
||||
self.scroll_offset = self.cursor_line - visible_lines + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Scroll by a delta (positive = down, negative = up).
|
||||
pub fn scroll_by(&mut self, delta: isize) {
|
||||
let max_scroll = self.line_count().saturating_sub(1);
|
||||
if delta < 0 {
|
||||
self.scroll_offset = self.scroll_offset.saturating_sub((-delta) as usize);
|
||||
} else {
|
||||
self.scroll_offset = (self.scroll_offset + delta as usize).min(max_scroll);
|
||||
}
|
||||
}
|
||||
|
||||
fn cursor_char_idx(&self) -> usize {
|
||||
let line_start = self.rope.line_to_char(self.cursor_line);
|
||||
line_start + self.cursor_col
|
||||
@@ -91,7 +174,6 @@ impl EditorBuffer {
|
||||
if self.cursor_line < self.rope.len_lines() {
|
||||
let line = self.rope.line(self.cursor_line);
|
||||
let len = line.len_chars();
|
||||
// Subtract trailing newline if present
|
||||
if len > 0 && line.char(len - 1) == '\n' {
|
||||
len - 1
|
||||
} else {
|
||||
@@ -149,4 +231,127 @@ mod tests {
|
||||
assert_eq!(buf.text(), "helloworld");
|
||||
assert_eq!(buf.cursor(), (0, 5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_forward() {
|
||||
let mut buf = EditorBuffer::new("hello");
|
||||
buf.set_cursor(0, 0);
|
||||
buf.delete_forward();
|
||||
assert_eq!(buf.text(), "ello");
|
||||
assert_eq!(buf.cursor(), (0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_forward_at_end_is_noop() {
|
||||
let mut buf = EditorBuffer::new("hi");
|
||||
buf.set_cursor(0, 2);
|
||||
buf.delete_forward();
|
||||
assert_eq!(buf.text(), "hi");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_forward_joins_lines() {
|
||||
let mut buf = EditorBuffer::new("hello\nworld");
|
||||
buf.set_cursor(0, 5);
|
||||
buf.delete_forward();
|
||||
assert_eq!(buf.text(), "helloworld");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_up() {
|
||||
let mut buf = EditorBuffer::new("abc\ndef\nghi");
|
||||
buf.set_cursor(2, 1);
|
||||
buf.move_up();
|
||||
assert_eq!(buf.cursor(), (1, 1));
|
||||
buf.move_up();
|
||||
assert_eq!(buf.cursor(), (0, 1));
|
||||
buf.move_up(); // at top, no-op
|
||||
assert_eq!(buf.cursor(), (0, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_down() {
|
||||
let mut buf = EditorBuffer::new("abc\ndef\nghi");
|
||||
buf.set_cursor(0, 1);
|
||||
buf.move_down();
|
||||
assert_eq!(buf.cursor(), (1, 1));
|
||||
buf.move_down();
|
||||
assert_eq!(buf.cursor(), (2, 1));
|
||||
buf.move_down(); // at bottom, no-op
|
||||
assert_eq!(buf.cursor(), (2, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_up_clamps_col_to_shorter_line() {
|
||||
let mut buf = EditorBuffer::new("long line\nhi");
|
||||
buf.set_cursor(0, 9);
|
||||
buf.move_down();
|
||||
assert_eq!(buf.cursor(), (1, 2)); // "hi" is only 2 chars
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_left_right() {
|
||||
let mut buf = EditorBuffer::new("abc");
|
||||
buf.set_cursor(0, 1);
|
||||
buf.move_right();
|
||||
assert_eq!(buf.cursor(), (0, 2));
|
||||
buf.move_left();
|
||||
assert_eq!(buf.cursor(), (0, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_left_wraps_to_previous_line() {
|
||||
let mut buf = EditorBuffer::new("abc\ndef");
|
||||
buf.set_cursor(1, 0);
|
||||
buf.move_left();
|
||||
assert_eq!(buf.cursor(), (0, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_right_wraps_to_next_line() {
|
||||
let mut buf = EditorBuffer::new("abc\ndef");
|
||||
buf.set_cursor(0, 3);
|
||||
buf.move_right();
|
||||
assert_eq!(buf.cursor(), (1, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_home_end() {
|
||||
let mut buf = EditorBuffer::new("hello world");
|
||||
buf.set_cursor(0, 5);
|
||||
buf.move_home();
|
||||
assert_eq!(buf.cursor(), (0, 0));
|
||||
buf.move_end();
|
||||
assert_eq!(buf.cursor(), (0, 11));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scroll_ensures_cursor_visible() {
|
||||
let mut buf = EditorBuffer::new("a\nb\nc\nd\ne\nf\ng\nh\ni\nj");
|
||||
buf.set_cursor(8, 0); // line 8
|
||||
buf.ensure_cursor_visible(5); // viewport shows 5 lines
|
||||
assert_eq!(buf.scroll_offset(), 4); // scroll so line 8 is visible
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scroll_by_positive() {
|
||||
let mut buf = EditorBuffer::new("a\nb\nc\nd\ne");
|
||||
buf.scroll_by(2);
|
||||
assert_eq!(buf.scroll_offset(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scroll_by_negative() {
|
||||
let mut buf = EditorBuffer::new("a\nb\nc\nd\ne");
|
||||
buf.scroll_by(3);
|
||||
buf.scroll_by(-1);
|
||||
assert_eq!(buf.scroll_offset(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scroll_by_clamps_to_zero() {
|
||||
let mut buf = EditorBuffer::new("a\nb\nc");
|
||||
buf.scroll_by(-10);
|
||||
assert_eq!(buf.scroll_offset(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
use iced::advanced::layout::{self, Layout};
|
||||
use iced::advanced::renderer;
|
||||
use iced::advanced::text;
|
||||
use iced::advanced::widget::{self, Widget};
|
||||
use iced::advanced::{Clipboard, Shell};
|
||||
use iced::event::Status;
|
||||
use iced::keyboard;
|
||||
use iced::mouse;
|
||||
use iced::{Color, Element, Event, Length, Rectangle, Size, Theme};
|
||||
use iced::{Color, Element, Event, Length, Pixels, Point, Rectangle, Size, Theme};
|
||||
|
||||
use crate::buffer::EditorBuffer;
|
||||
use crate::highlight::Highlighter;
|
||||
@@ -15,22 +17,37 @@ pub enum EditorMessage {
|
||||
ContentChanged(String),
|
||||
}
|
||||
|
||||
/// A syntax-highlighting code editor widget for Iced.
|
||||
///
|
||||
/// M0 proof of concept: renders highlighted text with line numbers.
|
||||
/// Full editing (cursor, input, selection) follows in M3.
|
||||
pub struct CodeEditor<'a> {
|
||||
buffer: &'a EditorBuffer,
|
||||
highlighter: &'a Highlighter,
|
||||
extension: &'a str,
|
||||
line_height: f32,
|
||||
char_width: f32,
|
||||
gutter_width: f32,
|
||||
/// Persistent widget state across frames.
|
||||
#[derive(Default)]
|
||||
struct EditorState {
|
||||
is_focused: bool,
|
||||
}
|
||||
|
||||
impl<'a> CodeEditor<'a> {
|
||||
const LINE_HEIGHT: f32 = 20.0;
|
||||
const CHAR_WIDTH: f32 = 8.4;
|
||||
const GUTTER_WIDTH: f32 = 50.0;
|
||||
const FONT_SIZE: f32 = 14.0;
|
||||
const BG_COLOR: Color = Color::from_rgb(0.18, 0.20, 0.25);
|
||||
const GUTTER_BG: Color = Color::from_rgb(0.15, 0.17, 0.21);
|
||||
const TEXT_COLOR: Color = Color::from_rgb(0.85, 0.85, 0.85);
|
||||
const GUTTER_TEXT: Color = Color::from_rgb(0.45, 0.48, 0.55);
|
||||
const CURSOR_COLOR: Color = Color::from_rgb(0.9, 0.9, 0.2);
|
||||
const ACTIVE_LINE_NUM: Color = Color::from_rgb(0.75, 0.78, 0.85);
|
||||
|
||||
/// A syntax-highlighting code editor widget for Iced.
|
||||
///
|
||||
/// M0 PoC: renders highlighted text with line numbers, handles keyboard
|
||||
/// input for basic editing, supports cursor movement and vertical scrolling.
|
||||
pub struct CodeEditor<'a, Message> {
|
||||
buffer: &'a mut EditorBuffer,
|
||||
highlighter: &'a Highlighter,
|
||||
extension: &'a str,
|
||||
on_change: Option<Box<dyn Fn(EditorMessage) -> Message + 'a>>,
|
||||
}
|
||||
|
||||
impl<'a, Message> CodeEditor<'a, Message> {
|
||||
pub fn new(
|
||||
buffer: &'a EditorBuffer,
|
||||
buffer: &'a mut EditorBuffer,
|
||||
highlighter: &'a Highlighter,
|
||||
extension: &'a str,
|
||||
) -> Self {
|
||||
@@ -38,17 +55,29 @@ impl<'a> CodeEditor<'a> {
|
||||
buffer,
|
||||
highlighter,
|
||||
extension,
|
||||
line_height: 20.0,
|
||||
char_width: 8.4,
|
||||
gutter_width: 50.0,
|
||||
on_change: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_change(mut self, f: impl Fn(EditorMessage) -> Message + 'a) -> Self {
|
||||
self.on_change = Some(Box::new(f));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Renderer> Widget<Message, Theme, Renderer> for CodeEditor<'a>
|
||||
impl<'a, Message, Renderer> Widget<Message, Theme, Renderer> for CodeEditor<'a, Message>
|
||||
where
|
||||
Renderer: renderer::Renderer,
|
||||
Renderer: renderer::Renderer + text::Renderer<Font = iced::Font>,
|
||||
Message: 'a,
|
||||
{
|
||||
fn tag(&self) -> widget::tree::Tag {
|
||||
widget::tree::Tag::of::<EditorState>()
|
||||
}
|
||||
|
||||
fn state(&self) -> widget::tree::State {
|
||||
widget::tree::State::new(EditorState::default())
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
Size::new(Length::Fill, Length::Fill)
|
||||
}
|
||||
@@ -65,7 +94,7 @@ where
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
_tree: &widget::Tree,
|
||||
tree: &widget::Tree,
|
||||
renderer: &mut Renderer,
|
||||
_theme: &Theme,
|
||||
_style: &renderer::Style,
|
||||
@@ -74,20 +103,21 @@ where
|
||||
_viewport: &Rectangle,
|
||||
) {
|
||||
let bounds = layout.bounds();
|
||||
let _state = tree.state.downcast_ref::<EditorState>();
|
||||
|
||||
// Draw background
|
||||
// Background
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds,
|
||||
border: iced::Border::default(),
|
||||
shadow: iced::Shadow::default(),
|
||||
},
|
||||
Color::from_rgb(0.18, 0.20, 0.25),
|
||||
BG_COLOR,
|
||||
);
|
||||
|
||||
// Draw gutter background
|
||||
// Gutter background
|
||||
let gutter_bounds = Rectangle {
|
||||
width: self.gutter_width,
|
||||
width: GUTTER_WIDTH,
|
||||
..bounds
|
||||
};
|
||||
renderer.fill_quad(
|
||||
@@ -96,35 +126,187 @@ where
|
||||
border: iced::Border::default(),
|
||||
shadow: iced::Shadow::default(),
|
||||
},
|
||||
Color::from_rgb(0.15, 0.17, 0.21),
|
||||
GUTTER_BG,
|
||||
);
|
||||
|
||||
// Note: Full text rendering with cosmic-text will be added when
|
||||
// we integrate cosmic-text's Buffer for font shaping and layout.
|
||||
// For M0 PoC, we verify the widget mounts and draws backgrounds.
|
||||
let (cursor_line, cursor_col) = self.buffer.cursor();
|
||||
let scroll = self.buffer.scroll_offset();
|
||||
let visible_lines = (bounds.height / LINE_HEIGHT) as usize + 1;
|
||||
|
||||
let font = iced::Font::MONOSPACE;
|
||||
|
||||
// Render visible lines
|
||||
for vis_idx in 0..visible_lines {
|
||||
let line_idx = scroll + vis_idx;
|
||||
if line_idx >= self.buffer.line_count() {
|
||||
break;
|
||||
}
|
||||
|
||||
let y = bounds.y + vis_idx as f32 * LINE_HEIGHT;
|
||||
if y + LINE_HEIGHT < bounds.y || y > bounds.y + bounds.height {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Line number
|
||||
let line_num = format!("{:>4}", line_idx + 1);
|
||||
let num_color = if line_idx == cursor_line {
|
||||
ACTIVE_LINE_NUM
|
||||
} else {
|
||||
GUTTER_TEXT
|
||||
};
|
||||
renderer.fill_text(
|
||||
text::Text {
|
||||
content: line_num,
|
||||
bounds: Size::new(GUTTER_WIDTH - 8.0, LINE_HEIGHT),
|
||||
size: Pixels(FONT_SIZE),
|
||||
line_height: iced::widget::text::LineHeight::Absolute(Pixels(LINE_HEIGHT)),
|
||||
font,
|
||||
horizontal_alignment: iced::alignment::Horizontal::Right,
|
||||
vertical_alignment: iced::alignment::Vertical::Top,
|
||||
shaping: iced::widget::text::Shaping::Basic,
|
||||
wrapping: iced::widget::text::Wrapping::None,
|
||||
},
|
||||
Point::new(bounds.x, y),
|
||||
num_color,
|
||||
bounds,
|
||||
);
|
||||
|
||||
// Line content
|
||||
if let Some(line) = self.buffer.line(line_idx) {
|
||||
let mut line_text: String = line.chars().collect();
|
||||
// Strip trailing newline for display
|
||||
if line_text.ends_with('\n') {
|
||||
line_text.pop();
|
||||
}
|
||||
|
||||
let text_x = bounds.x + GUTTER_WIDTH + 8.0;
|
||||
renderer.fill_text(
|
||||
text::Text {
|
||||
content: line_text,
|
||||
bounds: Size::new(bounds.width - GUTTER_WIDTH - 8.0, LINE_HEIGHT),
|
||||
size: Pixels(FONT_SIZE),
|
||||
line_height: iced::widget::text::LineHeight::Absolute(Pixels(LINE_HEIGHT)),
|
||||
font,
|
||||
horizontal_alignment: iced::alignment::Horizontal::Left,
|
||||
vertical_alignment: iced::alignment::Vertical::Top,
|
||||
shaping: iced::widget::text::Shaping::Advanced,
|
||||
wrapping: iced::widget::text::Wrapping::None,
|
||||
},
|
||||
Point::new(text_x, y),
|
||||
TEXT_COLOR,
|
||||
bounds,
|
||||
);
|
||||
|
||||
// Draw cursor on current line
|
||||
if line_idx == cursor_line {
|
||||
let cursor_x = text_x + cursor_col as f32 * CHAR_WIDTH;
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds: Rectangle {
|
||||
x: cursor_x,
|
||||
y,
|
||||
width: 2.0,
|
||||
height: LINE_HEIGHT,
|
||||
},
|
||||
border: iced::Border::default(),
|
||||
shadow: iced::Shadow::default(),
|
||||
},
|
||||
CURSOR_COLOR,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_event(
|
||||
&mut self,
|
||||
_state: &mut widget::Tree,
|
||||
_event: Event,
|
||||
_layout: Layout<'_>,
|
||||
_cursor: mouse::Cursor,
|
||||
tree: &mut widget::Tree,
|
||||
event: Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
_renderer: &Renderer,
|
||||
_clipboard: &mut dyn Clipboard,
|
||||
_shell: &mut Shell<'_, Message>,
|
||||
_viewport: &Rectangle,
|
||||
) -> Status {
|
||||
let state = tree.state.downcast_mut::<EditorState>();
|
||||
let bounds = layout.bounds();
|
||||
|
||||
match event {
|
||||
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
|
||||
if cursor.is_over(bounds) {
|
||||
state.is_focused = true;
|
||||
// Place cursor at click position
|
||||
if let Some(pos) = cursor.position_in(bounds) {
|
||||
let line = (pos.y / LINE_HEIGHT) as usize + self.buffer.scroll_offset();
|
||||
let col = ((pos.x - GUTTER_WIDTH - 8.0).max(0.0) / CHAR_WIDTH) as usize;
|
||||
self.buffer.set_cursor(line, col);
|
||||
}
|
||||
return Status::Captured;
|
||||
} else {
|
||||
state.is_focused = false;
|
||||
}
|
||||
}
|
||||
Event::Mouse(mouse::Event::WheelScrolled { delta }) if cursor.is_over(bounds) => {
|
||||
let lines = match delta {
|
||||
mouse::ScrollDelta::Lines { y, .. } => -(y * 3.0) as isize,
|
||||
mouse::ScrollDelta::Pixels { y, .. } => -(y / LINE_HEIGHT) as isize,
|
||||
};
|
||||
self.buffer.scroll_by(lines);
|
||||
return Status::Captured;
|
||||
}
|
||||
Event::Keyboard(keyboard::Event::KeyPressed { key, .. }) if state.is_focused => {
|
||||
match key {
|
||||
keyboard::Key::Named(keyboard::key::Named::ArrowUp) => {
|
||||
self.buffer.move_up();
|
||||
let vis = (bounds.height / LINE_HEIGHT) as usize;
|
||||
self.buffer.ensure_cursor_visible(vis);
|
||||
}
|
||||
keyboard::Key::Named(keyboard::key::Named::ArrowDown) => {
|
||||
self.buffer.move_down();
|
||||
let vis = (bounds.height / LINE_HEIGHT) as usize;
|
||||
self.buffer.ensure_cursor_visible(vis);
|
||||
}
|
||||
keyboard::Key::Named(keyboard::key::Named::ArrowLeft) => {
|
||||
self.buffer.move_left();
|
||||
}
|
||||
keyboard::Key::Named(keyboard::key::Named::ArrowRight) => {
|
||||
self.buffer.move_right();
|
||||
}
|
||||
keyboard::Key::Named(keyboard::key::Named::Home) => {
|
||||
self.buffer.move_home();
|
||||
}
|
||||
keyboard::Key::Named(keyboard::key::Named::End) => {
|
||||
self.buffer.move_end();
|
||||
}
|
||||
keyboard::Key::Named(keyboard::key::Named::Backspace) => {
|
||||
self.buffer.backspace();
|
||||
}
|
||||
keyboard::Key::Named(keyboard::key::Named::Delete) => {
|
||||
self.buffer.delete_forward();
|
||||
}
|
||||
keyboard::Key::Named(keyboard::key::Named::Enter) => {
|
||||
self.buffer.insert("\n");
|
||||
}
|
||||
keyboard::Key::Character(ref c) => {
|
||||
self.buffer.insert(c);
|
||||
}
|
||||
_ => return Status::Ignored,
|
||||
}
|
||||
return Status::Captured;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Status::Ignored
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Renderer> From<CodeEditor<'a>> for Element<'a, Message, Theme, Renderer>
|
||||
impl<'a, Message, Renderer> From<CodeEditor<'a, Message>> for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: renderer::Renderer + 'a,
|
||||
Renderer: renderer::Renderer + text::Renderer<Font = iced::Font> + 'a,
|
||||
Message: 'a,
|
||||
{
|
||||
fn from(editor: CodeEditor<'a>) -> Self {
|
||||
fn from(editor: CodeEditor<'a, Message>) -> Self {
|
||||
Self::new(editor)
|
||||
}
|
||||
}
|
||||
|
||||
214
crates/bds-editor/tests/editor_poc.rs
Normal file
214
crates/bds-editor/tests/editor_poc.rs
Normal file
@@ -0,0 +1,214 @@
|
||||
//! bds-editor PoC integration test.
|
||||
//!
|
||||
//! M0 validation: verifies that the editor components (buffer + highlighter)
|
||||
//! work together — highlighted markdown rendering, keyboard input simulation,
|
||||
//! and cursor movement. The Iced widget (CodeEditor) requires a renderer and
|
||||
//! cannot be tested without a windowing system; this test covers the
|
||||
//! non-GUI integration surface.
|
||||
|
||||
use bds_editor::{EditorBuffer, Highlighter};
|
||||
|
||||
// ── PoC: highlighted markdown rendering ──
|
||||
|
||||
#[test]
|
||||
fn highlight_markdown_document() {
|
||||
let md = "# Title\n\nA paragraph with **bold** text.\n\n- item one\n- item two\n";
|
||||
let hl = Highlighter::new();
|
||||
let syntax = hl.syntax_for_extension("md");
|
||||
let lines = hl.highlight_lines(md, syntax);
|
||||
|
||||
// 6 content lines in the markdown
|
||||
assert_eq!(lines.len(), 6);
|
||||
// Each line has at least one styled span
|
||||
for (i, line) in lines.iter().enumerate() {
|
||||
assert!(!line.is_empty(), "line {i} should have styled spans");
|
||||
}
|
||||
// The heading line should contain "# Title"
|
||||
let heading_text: String = lines[0].iter().map(|(_, t)| t.as_str()).collect();
|
||||
assert!(
|
||||
heading_text.contains("# Title"),
|
||||
"heading line should contain '# Title', got: {heading_text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlight_multiple_syntaxes() {
|
||||
let hl = Highlighter::new();
|
||||
|
||||
// Markdown
|
||||
let md_syntax = hl.syntax_for_extension("md");
|
||||
let md_lines = hl.highlight_lines("# Hello", md_syntax);
|
||||
assert_eq!(md_lines.len(), 1);
|
||||
|
||||
// YAML (used in frontmatter)
|
||||
let yaml_syntax = hl.syntax_for_extension("yaml");
|
||||
let yaml_lines = hl.highlight_lines("key: value", yaml_syntax);
|
||||
assert_eq!(yaml_lines.len(), 1);
|
||||
|
||||
// HTML (used in templates)
|
||||
let html_syntax = hl.syntax_for_extension("html");
|
||||
let html_lines = hl.highlight_lines("<div>hello</div>", html_syntax);
|
||||
assert_eq!(html_lines.len(), 1);
|
||||
}
|
||||
|
||||
// ── PoC: keyboard input simulation ──
|
||||
|
||||
#[test]
|
||||
fn type_text_into_buffer() {
|
||||
let mut buf = EditorBuffer::new("");
|
||||
// Simulate typing "Hello, world!"
|
||||
for c in "Hello, world!".chars() {
|
||||
buf.insert(&c.to_string());
|
||||
}
|
||||
assert_eq!(buf.text(), "Hello, world!");
|
||||
assert_eq!(buf.cursor(), (0, 13));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_multiline_text() {
|
||||
let mut buf = EditorBuffer::new("");
|
||||
buf.insert("line one");
|
||||
buf.insert("\n");
|
||||
buf.insert("line two");
|
||||
buf.insert("\n");
|
||||
buf.insert("line three");
|
||||
|
||||
assert_eq!(buf.line_count(), 3);
|
||||
assert_eq!(buf.cursor(), (2, 10));
|
||||
|
||||
let text = buf.text();
|
||||
assert!(text.contains("line one\n"));
|
||||
assert!(text.contains("line two\n"));
|
||||
assert!(text.contains("line three"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backspace_and_retype() {
|
||||
let mut buf = EditorBuffer::new("");
|
||||
buf.insert("Helo");
|
||||
// Fix typo: backspace removes 'o', then type correct chars
|
||||
buf.backspace(); // "Hel" cursor at 3
|
||||
buf.insert("lo"); // "Hello"
|
||||
assert_eq!(buf.text(), "Hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_forward_mid_line() {
|
||||
let mut buf = EditorBuffer::new("abcdef");
|
||||
buf.set_cursor(0, 3); // after 'c'
|
||||
buf.delete_forward(); // remove 'd'
|
||||
assert_eq!(buf.text(), "abcef");
|
||||
assert_eq!(buf.cursor(), (0, 3));
|
||||
}
|
||||
|
||||
// ── PoC: cursor movement ──
|
||||
|
||||
#[test]
|
||||
fn cursor_navigation_full_cycle() {
|
||||
let mut buf = EditorBuffer::new("first line\nsecond line\nthird line");
|
||||
|
||||
// Start at (0,0), move to end of first line
|
||||
buf.move_end();
|
||||
assert_eq!(buf.cursor(), (0, 10));
|
||||
|
||||
// Move down to second line
|
||||
buf.move_down();
|
||||
assert_eq!(buf.cursor(), (1, 10));
|
||||
|
||||
// Move home
|
||||
buf.move_home();
|
||||
assert_eq!(buf.cursor(), (1, 0));
|
||||
|
||||
// Move down to third line
|
||||
buf.move_down();
|
||||
assert_eq!(buf.cursor(), (2, 0));
|
||||
|
||||
// Move right 5 times
|
||||
for _ in 0..5 {
|
||||
buf.move_right();
|
||||
}
|
||||
assert_eq!(buf.cursor(), (2, 5));
|
||||
|
||||
// Move up twice to first line
|
||||
buf.move_up();
|
||||
buf.move_up();
|
||||
assert_eq!(buf.cursor(), (0, 5));
|
||||
|
||||
// Move left to beginning with wrap
|
||||
for _ in 0..6 {
|
||||
buf.move_left();
|
||||
}
|
||||
assert_eq!(buf.cursor(), (0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_wrap_across_lines() {
|
||||
let mut buf = EditorBuffer::new("abc\ndef");
|
||||
|
||||
// Move right past end of first line wraps to second
|
||||
buf.set_cursor(0, 3);
|
||||
buf.move_right();
|
||||
assert_eq!(buf.cursor(), (1, 0));
|
||||
|
||||
// Move left at start of second line wraps to first
|
||||
buf.move_left();
|
||||
assert_eq!(buf.cursor(), (0, 3));
|
||||
}
|
||||
|
||||
// ── PoC: scrolling ──
|
||||
|
||||
#[test]
|
||||
fn scroll_keeps_cursor_visible() {
|
||||
// 20 lines of content
|
||||
let text: String = (0..20).map(|i| format!("line {i}\n")).collect();
|
||||
let mut buf = EditorBuffer::new(&text);
|
||||
|
||||
// Simulate moving cursor to line 15
|
||||
for _ in 0..15 {
|
||||
buf.move_down();
|
||||
}
|
||||
assert_eq!(buf.cursor().0, 15);
|
||||
|
||||
// With a viewport of 10 lines, ensure scroll tracks
|
||||
buf.ensure_cursor_visible(10);
|
||||
let scroll = buf.scroll_offset();
|
||||
assert!(
|
||||
scroll <= 15 && 15 < scroll + 10,
|
||||
"cursor line 15 should be visible in viewport starting at {scroll}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scroll_by_manual() {
|
||||
let text: String = (0..50).map(|i| format!("line {i}\n")).collect();
|
||||
let mut buf = EditorBuffer::new(&text);
|
||||
|
||||
buf.scroll_by(10);
|
||||
assert_eq!(buf.scroll_offset(), 10);
|
||||
|
||||
buf.scroll_by(-3);
|
||||
assert_eq!(buf.scroll_offset(), 7);
|
||||
}
|
||||
|
||||
// ── PoC: edit + highlight round-trip ──
|
||||
|
||||
#[test]
|
||||
fn edit_then_rehighlight() {
|
||||
let mut buf = EditorBuffer::new("# Hello\n\nSome text.");
|
||||
let hl = Highlighter::new();
|
||||
let syntax = hl.syntax_for_extension("md");
|
||||
|
||||
// Initial highlight
|
||||
let lines1 = hl.highlight_lines(&buf.text(), syntax);
|
||||
assert_eq!(lines1.len(), 3);
|
||||
|
||||
// Edit: add a new line
|
||||
buf.set_cursor(2, 10);
|
||||
buf.insert("\n\n## Subheading");
|
||||
|
||||
// Re-highlight after edit
|
||||
let lines2 = hl.highlight_lines(&buf.text(), syntax);
|
||||
assert_eq!(lines2.len(), 5); // 3 original + blank + subheading
|
||||
let subheading_text: String = lines2[4].iter().map(|(_, t)| t.as_str()).collect();
|
||||
assert!(subheading_text.contains("## Subheading"));
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
mod app;
|
||||
mod platform;
|
||||
pub mod app;
|
||||
pub mod platform;
|
||||
|
||||
pub use app::BdsApp;
|
||||
|
||||
@@ -4,6 +4,10 @@ use muda::{Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu};
|
||||
use crate::app::Message;
|
||||
|
||||
/// Build the native menu bar with standard application menus.
|
||||
///
|
||||
/// On macOS, also calls `init_for_nsapp()` to register the menu with AppKit.
|
||||
/// This requires an active NSApplication, so it will silently fail in
|
||||
/// test contexts without one (muda returns an error that we discard).
|
||||
pub fn build_menu_bar() -> Menu {
|
||||
let menu = Menu::new();
|
||||
|
||||
|
||||
39
crates/bds-ui/tests/app_smoke.rs
Normal file
39
crates/bds-ui/tests/app_smoke.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
//! App launch smoke tests.
|
||||
//!
|
||||
//! M0 validation: verifies that the core UI types can be constructed
|
||||
//! and that the message routing works at the type level.
|
||||
//!
|
||||
//! NOTE: muda::Menu on macOS requires the actual main thread (not just
|
||||
//! single-threaded test mode). Menu construction and BdsApp::new() cannot
|
||||
//! be tested via `cargo test`. The full smoke test is launching the binary:
|
||||
//! cargo run -p bds-ui
|
||||
|
||||
use bds_ui::app::Message;
|
||||
|
||||
// ── Smoke: Message enum is well-formed ──
|
||||
|
||||
#[test]
|
||||
fn message_variants_constructable() {
|
||||
let _noop = Message::Noop;
|
||||
let _menu = Message::MenuEvent(muda::MenuId::new("test"));
|
||||
// Verify Debug trait works
|
||||
assert!(format!("{:?}", Message::Noop).contains("Noop"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_clone_works() {
|
||||
let msg = Message::MenuEvent(muda::MenuId::new("file-open"));
|
||||
let cloned = msg.clone();
|
||||
assert!(format!("{cloned:?}").contains("MenuEvent"));
|
||||
}
|
||||
|
||||
// ── Smoke: BdsApp type is accessible from integration tests ──
|
||||
|
||||
#[test]
|
||||
fn bds_app_type_is_public() {
|
||||
// This test verifies the public API surface exists.
|
||||
// BdsApp, Message, platform::menu are all reachable.
|
||||
fn _assert_types() {
|
||||
let _: fn() -> (bds_ui::BdsApp, iced::Task<Message>) = bds_ui::BdsApp::new;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user