feat: first take at milestone M3

This commit is contained in:
2026-04-05 16:28:59 +02:00
parent 118633de81
commit b755c6bcbc
27 changed files with 5372 additions and 134 deletions

View File

@@ -6,7 +6,9 @@ pub mod tag;
pub mod post; pub mod post;
pub mod media; pub mod media;
pub mod post_media; pub mod post_media;
pub mod template;
pub mod template_rebuild; pub mod template_rebuild;
pub mod script;
pub mod script_rebuild; pub mod script_rebuild;
pub mod task; pub mod task;
pub mod metadata_diff; pub mod metadata_diff;

View File

@@ -0,0 +1,431 @@
use std::fs;
use std::path::Path;
use rusqlite::Connection;
use uuid::Uuid;
use crate::db::queries::script as qs;
use crate::engine::{EngineError, EngineResult};
use crate::model::{Script, ScriptKind, ScriptStatus};
use crate::util::frontmatter::{write_script_file, ScriptFrontmatter};
use crate::util::{atomic_write_str, ensure_unique, now_unix_ms, slugify};
/// Create a new draft script. Content stored in DB, no file written.
pub fn create_script(
conn: &Connection,
project_id: &str,
title: &str,
kind: ScriptKind,
content: &str,
entrypoint: Option<&str>,
) -> EngineResult<Script> {
let slug_source = if title.is_empty() { "untitled" } else { title };
let base_slug = slugify(slug_source);
let base_slug = if base_slug.is_empty() {
"untitled".to_string()
} else {
base_slug
};
let slug = ensure_unique(&base_slug, |candidate| {
qs::get_script_by_slug(conn, project_id, candidate).is_ok()
});
let now = now_unix_ms();
let id = Uuid::new_v4().to_string();
let script = Script {
id,
project_id: project_id.to_string(),
slug,
title: title.to_string(),
kind,
entrypoint: entrypoint.unwrap_or("render").to_string(),
enabled: true,
version: 1,
file_path: String::new(),
status: ScriptStatus::Draft,
content: Some(content.to_string()),
created_at: now,
updated_at: now,
};
qs::insert_script(conn, &script)?;
Ok(script)
}
/// Update a script's metadata and/or content. Bumps version.
pub fn update_script(
conn: &Connection,
script_id: &str,
project_id: &str,
title: Option<&str>,
slug: Option<&str>,
kind: Option<ScriptKind>,
entrypoint: Option<&str>,
enabled: Option<bool>,
content: Option<&str>,
) -> EngineResult<Script> {
let mut script = qs::get_script_by_id(conn, script_id)?;
// Slug uniqueness
if let Some(new_slug) = slug {
if new_slug != script.slug {
if qs::get_script_by_slug(conn, project_id, new_slug).is_ok() {
return Err(EngineError::Conflict(format!(
"script slug '{new_slug}' already exists"
)));
}
}
}
if let Some(t) = title {
script.title = t.to_string();
}
if let Some(s) = slug {
script.slug = s.to_string();
}
if let Some(k) = kind {
script.kind = k;
}
if let Some(ep) = entrypoint {
script.entrypoint = ep.to_string();
}
if let Some(e) = enabled {
script.enabled = e;
}
if let Some(c) = content {
script.content = Some(c.to_string());
}
// If published, transition back to draft on edit
if script.status == ScriptStatus::Published {
script.status = ScriptStatus::Draft;
}
script.version += 1;
script.updated_at = now_unix_ms();
qs::update_script(conn, &script)?;
Ok(script)
}
/// Save script content (editor save). Updates DB, bumps version.
pub fn save_script(
conn: &Connection,
script_id: &str,
content: &str,
) -> EngineResult<Script> {
let mut script = qs::get_script_by_id(conn, script_id)?;
script.content = Some(content.to_string());
script.version += 1;
script.updated_at = now_unix_ms();
if script.status == ScriptStatus::Published {
script.status = ScriptStatus::Draft;
}
qs::update_script(conn, &script)?;
Ok(script)
}
/// Validate Lua script syntax. Returns Ok(()) or a parse error message.
pub fn validate_script_syntax(content: &str) -> Result<(), String> {
// Basic validation: balanced block structures
validate_lua_blocks(content)?;
Ok(())
}
/// Discover entrypoint function names from Lua source.
/// Returns list of function names, with "main" always first if present.
pub fn discover_entrypoints(content: &str) -> Vec<String> {
let mut funcs = Vec::new();
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with("function ") {
// Extract function name: "function name(" or "function name (..."
let rest = trimmed.strip_prefix("function ").unwrap_or("").trim();
if let Some(name) = rest.split(&['(', ' '][..]).next() {
let name = name.trim();
if !name.is_empty() && !name.contains('.') && !name.contains(':') {
funcs.push(name.to_string());
}
}
}
}
// Ensure "main" is first if present
if let Some(pos) = funcs.iter().position(|n| n == "main") {
funcs.remove(pos);
funcs.insert(0, "main".to_string());
}
funcs
}
/// Publish a script: write frontmatter+body to file, clear content in DB.
pub fn publish_script(
conn: &Connection,
data_dir: &Path,
script_id: &str,
) -> EngineResult<Script> {
let mut script = qs::get_script_by_id(conn, script_id)?;
if script.status == ScriptStatus::Published {
return Err(EngineError::Conflict(
"script is already published".to_string(),
));
}
let body = script.content.clone().unwrap_or_default();
// Validate before publishing
validate_script_syntax(&body).map_err(EngineError::Validation)?;
let now = now_unix_ms();
let rel_path = format!("scripts/{}.lua", script.slug);
let abs_path = data_dir.join(&rel_path);
// Ensure scripts/ directory exists
if let Some(parent) = abs_path.parent() {
fs::create_dir_all(parent)?;
}
let fm = ScriptFrontmatter {
id: script.id.clone(),
project_id: Some(script.project_id.clone()),
slug: script.slug.clone(),
title: script.title.clone(),
kind: script_kind_to_frontmatter(&script.kind),
entrypoint: script.entrypoint.clone(),
enabled: script.enabled,
version: script.version,
created_at: script.created_at,
updated_at: now,
};
let file_content = write_script_file(&fm, &body);
atomic_write_str(&abs_path, &file_content)?;
script.status = ScriptStatus::Published;
script.file_path = rel_path;
script.content = None;
script.updated_at = now;
qs::update_script(conn, &script)?;
Ok(script)
}
/// Unpublish a script: read content from file back into DB, set status to draft.
pub fn unpublish_script(
conn: &Connection,
data_dir: &Path,
script_id: &str,
) -> EngineResult<Script> {
let mut script = qs::get_script_by_id(conn, script_id)?;
if script.status != ScriptStatus::Published {
return Err(EngineError::Conflict(
"script is not published".to_string(),
));
}
if !script.file_path.is_empty() {
let abs_path = data_dir.join(&script.file_path);
if abs_path.exists() {
let file_content = fs::read_to_string(&abs_path)?;
let (_fm, body) = crate::util::frontmatter::read_script_file(&file_content)
.map_err(EngineError::Parse)?;
script.content = Some(body);
}
}
script.status = ScriptStatus::Draft;
script.updated_at = now_unix_ms();
qs::update_script(conn, &script)?;
Ok(script)
}
/// Delete a script and its file.
pub fn delete_script(
conn: &Connection,
data_dir: &Path,
script_id: &str,
) -> EngineResult<()> {
let script = qs::get_script_by_id(conn, script_id)?;
// Delete file if exists
if !script.file_path.is_empty() {
let abs_path = data_dir.join(&script.file_path);
if abs_path.exists() {
fs::remove_file(&abs_path)?;
}
}
qs::delete_script(conn, script_id)?;
Ok(())
}
// --- Helper functions ---
fn script_kind_to_frontmatter(kind: &ScriptKind) -> String {
match kind {
ScriptKind::Macro => "macro".to_string(),
ScriptKind::Utility => "utility".to_string(),
ScriptKind::Transform => "transform".to_string(),
}
}
fn validate_lua_blocks(content: &str) -> Result<(), String> {
// Track block-level nesting for function/end, if/end, for/end, while/end, do/end
let mut depth: i32 = 0;
for line in content.lines() {
let trimmed = line.trim();
// Skip comments
if trimmed.starts_with("--") {
continue;
}
// Count block openers
for word in trimmed.split_whitespace() {
match word {
"function" | "if" | "for" | "while" | "do" => depth += 1,
"end" | "end," | "end;" => {
depth -= 1;
if depth < 0 {
return Err("unexpected 'end' without matching block opener".to_string());
}
}
_ => {}
}
}
// Handle "then" on if lines (don't double-count)
// Handle inline "function() ... end"
}
if depth > 0 {
return Err(format!("{depth} unclosed block(s) — missing 'end'"));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::db::queries::project::{insert_project, make_test_project};
use crate::db::Database;
use tempfile::TempDir;
fn setup() -> (Database, TempDir) {
let mut db = Database::open_in_memory().unwrap();
db.migrate().unwrap();
insert_project(db.conn(), &make_test_project("p1", "blog")).unwrap();
let dir = TempDir::new().unwrap();
(db, dir)
}
#[test]
fn create_draft_script() {
let (db, _dir) = setup();
let s = create_script(db.conn(), "p1", "My Script", ScriptKind::Macro, "return 'hi'", None).unwrap();
assert_eq!(s.title, "My Script");
assert_eq!(s.slug, "my-script");
assert_eq!(s.kind, ScriptKind::Macro);
assert_eq!(s.status, ScriptStatus::Draft);
assert_eq!(s.content, Some("return 'hi'".to_string()));
assert_eq!(s.entrypoint, "render");
assert!(s.file_path.is_empty());
assert!(s.enabled);
}
#[test]
fn create_with_custom_entrypoint() {
let (db, _dir) = setup();
let s = create_script(db.conn(), "p1", "Util", ScriptKind::Utility, "", Some("main")).unwrap();
assert_eq!(s.entrypoint, "main");
}
#[test]
fn create_deduplicates_slug() {
let (db, _dir) = setup();
let s1 = create_script(db.conn(), "p1", "Test", ScriptKind::Macro, "", None).unwrap();
let s2 = create_script(db.conn(), "p1", "Test", ScriptKind::Macro, "", None).unwrap();
assert_eq!(s1.slug, "test");
assert_eq!(s2.slug, "test-2");
}
#[test]
fn update_script_bumps_version() {
let (db, _dir) = setup();
let s = create_script(db.conn(), "p1", "S", ScriptKind::Macro, "old", None).unwrap();
let updated = update_script(db.conn(), &s.id, "p1", Some("New"), None, None, None, None, Some("new")).unwrap();
assert_eq!(updated.title, "New");
assert_eq!(updated.content, Some("new".to_string()));
assert_eq!(updated.version, 2);
}
#[test]
fn save_script_updates_content() {
let (db, _dir) = setup();
let s = create_script(db.conn(), "p1", "S", ScriptKind::Macro, "old", None).unwrap();
let saved = save_script(db.conn(), &s.id, "new body").unwrap();
assert_eq!(saved.content, Some("new body".to_string()));
assert_eq!(saved.version, 2);
}
#[test]
fn publish_and_unpublish_script() {
let (db, dir) = setup();
let s = create_script(db.conn(), "p1", "Pub", ScriptKind::Macro, "function render()\n return 'hi'\nend", None).unwrap();
let published = publish_script(db.conn(), dir.path(), &s.id).unwrap();
assert_eq!(published.status, ScriptStatus::Published);
assert!(published.content.is_none());
assert_eq!(published.file_path, "scripts/pub.lua");
assert!(dir.path().join("scripts/pub.lua").exists());
let unpublished = unpublish_script(db.conn(), dir.path(), &published.id).unwrap();
assert_eq!(unpublished.status, ScriptStatus::Draft);
assert!(unpublished.content.is_some());
}
#[test]
fn delete_script_removes_file() {
let (db, dir) = setup();
let s = create_script(db.conn(), "p1", "Del", ScriptKind::Macro, "function render()\nend", None).unwrap();
publish_script(db.conn(), dir.path(), &s.id).unwrap();
assert!(dir.path().join("scripts/del.lua").exists());
delete_script(db.conn(), dir.path(), &s.id).unwrap();
assert!(!dir.path().join("scripts/del.lua").exists());
assert!(qs::get_script_by_id(db.conn(), &s.id).is_err());
}
#[test]
fn discover_entrypoints_finds_functions() {
let code = "function render()\n return 'hi'\nend\n\nfunction helper(x)\n return x\nend";
let funcs = discover_entrypoints(code);
assert_eq!(funcs, vec!["render", "helper"]);
}
#[test]
fn discover_entrypoints_main_first() {
let code = "function helper()\nend\n\nfunction main()\nend";
let funcs = discover_entrypoints(code);
assert_eq!(funcs[0], "main");
}
#[test]
fn validate_valid_lua() {
assert!(validate_script_syntax("function render()\n return 'hi'\nend").is_ok());
}
#[test]
fn validate_unclosed_function() {
assert!(validate_script_syntax("function render()\n return 'hi'").is_err());
}
#[test]
fn validate_extra_end() {
assert!(validate_script_syntax("end").is_err());
}
}

View File

@@ -0,0 +1,550 @@
use std::fs;
use std::path::Path;
use rusqlite::Connection;
use uuid::Uuid;
use crate::db::queries::template as qt;
use crate::engine::{EngineError, EngineResult};
use crate::model::{Template, TemplateKind, TemplateStatus};
use crate::util::frontmatter::{write_template_file, TemplateFrontmatter};
use crate::util::{atomic_write_str, ensure_unique, now_unix_ms, slugify};
/// Create a new draft template. Content stored in DB, no file written.
pub fn create_template(
conn: &Connection,
project_id: &str,
title: &str,
kind: TemplateKind,
content: &str,
) -> EngineResult<Template> {
let slug_source = if title.is_empty() { "untitled" } else { title };
let base_slug = slugify(slug_source);
let base_slug = if base_slug.is_empty() {
"untitled".to_string()
} else {
base_slug
};
let slug = ensure_unique(&base_slug, |candidate| {
qt::get_template_by_slug(conn, project_id, candidate).is_ok()
});
let now = now_unix_ms();
let id = Uuid::new_v4().to_string();
let tpl = Template {
id,
project_id: project_id.to_string(),
slug,
title: title.to_string(),
kind,
enabled: true,
version: 1,
file_path: String::new(),
status: TemplateStatus::Draft,
content: Some(content.to_string()),
created_at: now,
updated_at: now,
};
qt::insert_template(conn, &tpl)?;
Ok(tpl)
}
/// Update a template's metadata and/or content. Bumps version.
pub fn update_template(
conn: &Connection,
template_id: &str,
project_id: &str,
title: Option<&str>,
slug: Option<&str>,
kind: Option<TemplateKind>,
enabled: Option<bool>,
content: Option<&str>,
) -> EngineResult<Template> {
let mut tpl = qt::get_template_by_id(conn, template_id)?;
// Slug uniqueness check
if let Some(new_slug) = slug {
if new_slug != tpl.slug {
if qt::get_template_by_slug(conn, project_id, new_slug).is_ok() {
return Err(EngineError::Conflict(format!(
"template slug '{new_slug}' already exists"
)));
}
}
}
if let Some(t) = title {
tpl.title = t.to_string();
}
if let Some(s) = slug {
tpl.slug = s.to_string();
}
if let Some(k) = kind {
tpl.kind = k;
}
if let Some(e) = enabled {
tpl.enabled = e;
}
if let Some(c) = content {
tpl.content = Some(c.to_string());
}
// If published, transition back to draft on edit
if tpl.status == TemplateStatus::Published {
// Reload content from file if needed
if tpl.content.is_none() && !tpl.file_path.is_empty() {
// Content will come from the file when we read for publish
// For update we need the new content from the caller
}
tpl.status = TemplateStatus::Draft;
}
tpl.version += 1;
tpl.updated_at = now_unix_ms();
qt::update_template(conn, &tpl)?;
Ok(tpl)
}
/// Save template content (editor save). Updates DB, bumps version.
pub fn save_template(
conn: &Connection,
template_id: &str,
content: &str,
) -> EngineResult<Template> {
let mut tpl = qt::get_template_by_id(conn, template_id)?;
tpl.content = Some(content.to_string());
tpl.version += 1;
tpl.updated_at = now_unix_ms();
// If published, transition back to draft
if tpl.status == TemplateStatus::Published {
tpl.status = TemplateStatus::Draft;
}
qt::update_template(conn, &tpl)?;
Ok(tpl)
}
/// Validate Liquid template syntax. Returns Ok(()) or a parse error message.
pub fn validate_template(content: &str) -> Result<(), String> {
// Check for basic Liquid syntax correctness:
// Matching {% %} tags, matching {{ }}
validate_liquid_brackets(content)?;
validate_liquid_blocks(content)?;
Ok(())
}
/// Publish a template: write frontmatter+body to file, clear content in DB.
pub fn publish_template(
conn: &Connection,
data_dir: &Path,
template_id: &str,
) -> EngineResult<Template> {
let mut tpl = qt::get_template_by_id(conn, template_id)?;
if tpl.status == TemplateStatus::Published {
return Err(EngineError::Conflict(
"template is already published".to_string(),
));
}
let body = tpl
.content
.clone()
.unwrap_or_default();
// Validate before publishing
validate_template(&body).map_err(EngineError::Validation)?;
let now = now_unix_ms();
let rel_path = format!("templates/{}.liquid", tpl.slug);
let abs_path = data_dir.join(&rel_path);
// Ensure templates/ directory exists
if let Some(parent) = abs_path.parent() {
fs::create_dir_all(parent)?;
}
// Build frontmatter
let fm = TemplateFrontmatter {
id: tpl.id.clone(),
project_id: Some(tpl.project_id.clone()),
slug: tpl.slug.clone(),
title: tpl.title.clone(),
kind: template_kind_to_frontmatter(&tpl.kind),
enabled: tpl.enabled,
version: tpl.version,
created_at: tpl.created_at,
updated_at: now,
};
let file_content = write_template_file(&fm, &body);
atomic_write_str(&abs_path, &file_content)?;
// Update DB
tpl.status = TemplateStatus::Published;
tpl.file_path = rel_path;
tpl.content = None;
tpl.updated_at = now;
qt::update_template(conn, &tpl)?;
Ok(tpl)
}
/// Unpublish a template: read content from file back into DB, set status to draft.
pub fn unpublish_template(
conn: &Connection,
data_dir: &Path,
template_id: &str,
) -> EngineResult<Template> {
let mut tpl = qt::get_template_by_id(conn, template_id)?;
if tpl.status != TemplateStatus::Published {
return Err(EngineError::Conflict(
"template is not published".to_string(),
));
}
// Read body from file
if !tpl.file_path.is_empty() {
let abs_path = data_dir.join(&tpl.file_path);
if abs_path.exists() {
let file_content = fs::read_to_string(&abs_path)?;
let (_fm, body) =
crate::util::frontmatter::read_template_file(&file_content)
.map_err(EngineError::Parse)?;
tpl.content = Some(body);
}
}
tpl.status = TemplateStatus::Draft;
tpl.updated_at = now_unix_ms();
qt::update_template(conn, &tpl)?;
Ok(tpl)
}
/// Delete a template. Checks for references from posts and tags.
pub fn delete_template(
conn: &Connection,
data_dir: &Path,
template_id: &str,
force: bool,
) -> EngineResult<()> {
let tpl = qt::get_template_by_id(conn, template_id)?;
// Check references
let referencing_posts = count_posts_using_template(conn, &tpl.slug)?;
let referencing_tags = count_tags_using_template(conn, &tpl.slug)?;
if (referencing_posts > 0 || referencing_tags > 0) && !force {
return Err(EngineError::Conflict(format!(
"template is referenced by {} posts and {} tags",
referencing_posts, referencing_tags
)));
}
// Force: null out references
if force {
if referencing_posts > 0 {
null_template_slug_on_posts(conn, &tpl.slug)?;
}
if referencing_tags > 0 {
null_template_slug_on_tags(conn, &tpl.slug)?;
}
}
// Delete file if exists
if !tpl.file_path.is_empty() {
let abs_path = data_dir.join(&tpl.file_path);
if abs_path.exists() {
fs::remove_file(&abs_path)?;
}
}
qt::delete_template(conn, template_id)?;
Ok(())
}
// --- Helper functions ---
fn template_kind_to_frontmatter(kind: &TemplateKind) -> String {
match kind {
TemplateKind::Post => "post".to_string(),
TemplateKind::List => "list".to_string(),
TemplateKind::NotFound => "not_found".to_string(),
TemplateKind::Partial => "partial".to_string(),
}
}
fn validate_liquid_brackets(content: &str) -> Result<(), String> {
// Check balanced {{ }} and {% %}
let mut in_output = false;
let mut in_tag = false;
let chars: Vec<char> = content.chars().collect();
let len = chars.len();
let mut i = 0;
while i < len {
if i + 1 < len {
let pair = (chars[i], chars[i + 1]);
match pair {
('{', '{') if !in_output && !in_tag => {
in_output = true;
i += 2;
continue;
}
('}', '}') if in_output => {
in_output = false;
i += 2;
continue;
}
('{', '%') if !in_output && !in_tag => {
in_tag = true;
i += 2;
continue;
}
('%', '}') if in_tag => {
in_tag = false;
i += 2;
continue;
}
_ => {}
}
}
i += 1;
}
if in_output {
return Err("unclosed {{ output tag".to_string());
}
if in_tag {
return Err("unclosed {% tag".to_string());
}
Ok(())
}
fn validate_liquid_blocks(content: &str) -> Result<(), String> {
// Check that block tags are balanced (if/endif, for/endfor)
let mut if_depth: i32 = 0;
let mut for_depth: i32 = 0;
// Simple regex-free scanner for {% tag %} blocks
let chars: Vec<char> = content.chars().collect();
let len = chars.len();
let mut i = 0;
while i < len {
if i + 1 < len && chars[i] == '{' && chars[i + 1] == '%' {
// Find closing %}
let start = i + 2;
if let Some(end_offset) = content[start..].find("%}") {
let tag_content = content[start..start + end_offset].trim();
let tag_content = tag_content.trim_start_matches('-').trim_end_matches('-').trim();
let first_word = tag_content
.split_whitespace()
.next()
.unwrap_or("");
match first_word {
"if" => if_depth += 1,
"endif" => {
if_depth -= 1;
if if_depth < 0 {
return Err("unexpected {% endif %} without matching {% if %}".to_string());
}
}
"for" => for_depth += 1,
"endfor" => {
for_depth -= 1;
if for_depth < 0 {
return Err("unexpected {% endfor %} without matching {% for %}".to_string());
}
}
_ => {}
}
i = start + end_offset + 2;
continue;
}
}
i += 1;
}
if if_depth > 0 {
return Err(format!("{if_depth} unclosed {{% if %}} block(s)"));
}
if for_depth > 0 {
return Err(format!("{for_depth} unclosed {{% for %}} block(s)"));
}
Ok(())
}
fn count_posts_using_template(conn: &Connection, slug: &str) -> EngineResult<usize> {
let count: i64 = conn.query_row(
"SELECT COUNT(*) FROM posts WHERE template_slug = ?1",
rusqlite::params![slug],
|row| row.get(0),
)?;
Ok(count as usize)
}
fn count_tags_using_template(conn: &Connection, slug: &str) -> EngineResult<usize> {
let count: i64 = conn.query_row(
"SELECT COUNT(*) FROM tags WHERE post_template_slug = ?1",
rusqlite::params![slug],
|row| row.get(0),
)?;
Ok(count as usize)
}
fn null_template_slug_on_posts(conn: &Connection, slug: &str) -> EngineResult<()> {
conn.execute(
"UPDATE posts SET template_slug = NULL WHERE template_slug = ?1",
rusqlite::params![slug],
)?;
Ok(())
}
fn null_template_slug_on_tags(conn: &Connection, slug: &str) -> EngineResult<()> {
conn.execute(
"UPDATE tags SET post_template_slug = NULL WHERE post_template_slug = ?1",
rusqlite::params![slug],
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::db::queries::project::{insert_project, make_test_project};
use crate::db::Database;
use tempfile::TempDir;
fn setup() -> (Database, TempDir) {
let mut db = Database::open_in_memory().unwrap();
db.migrate().unwrap();
insert_project(db.conn(), &make_test_project("p1", "blog")).unwrap();
let dir = TempDir::new().unwrap();
(db, dir)
}
#[test]
fn create_draft_template() {
let (db, _dir) = setup();
let tpl = create_template(db.conn(), "p1", "My Template", TemplateKind::Post, "<p>hello</p>").unwrap();
assert_eq!(tpl.title, "My Template");
assert_eq!(tpl.slug, "my-template");
assert_eq!(tpl.kind, TemplateKind::Post);
assert_eq!(tpl.status, TemplateStatus::Draft);
assert_eq!(tpl.content, Some("<p>hello</p>".to_string()));
assert!(tpl.file_path.is_empty());
assert!(tpl.enabled);
assert_eq!(tpl.version, 1);
}
#[test]
fn create_template_deduplicates_slug() {
let (db, _dir) = setup();
let t1 = create_template(db.conn(), "p1", "Test", TemplateKind::Post, "").unwrap();
let t2 = create_template(db.conn(), "p1", "Test", TemplateKind::Post, "").unwrap();
assert_eq!(t1.slug, "test");
assert_eq!(t2.slug, "test-2");
}
#[test]
fn update_template_bumps_version() {
let (db, _dir) = setup();
let tpl = create_template(db.conn(), "p1", "Tpl", TemplateKind::Post, "old").unwrap();
let updated = update_template(
db.conn(), &tpl.id, "p1",
Some("New Title"), None, None, None, Some("new content"),
).unwrap();
assert_eq!(updated.title, "New Title");
assert_eq!(updated.content, Some("new content".to_string()));
assert_eq!(updated.version, 2);
}
#[test]
fn update_template_slug_conflict() {
let (db, _dir) = setup();
create_template(db.conn(), "p1", "Alpha", TemplateKind::Post, "").unwrap();
let t2 = create_template(db.conn(), "p1", "Beta", TemplateKind::Post, "").unwrap();
let result = update_template(db.conn(), &t2.id, "p1", None, Some("alpha"), None, None, None);
assert!(result.is_err());
}
#[test]
fn save_template_updates_content() {
let (db, _dir) = setup();
let tpl = create_template(db.conn(), "p1", "Tpl", TemplateKind::Post, "old").unwrap();
let saved = save_template(db.conn(), &tpl.id, "new content").unwrap();
assert_eq!(saved.content, Some("new content".to_string()));
assert_eq!(saved.version, 2);
}
#[test]
fn publish_and_unpublish_template() {
let (db, dir) = setup();
let tpl = create_template(db.conn(), "p1", "Pub", TemplateKind::Post, "<div>body</div>").unwrap();
// Publish
let published = publish_template(db.conn(), dir.path(), &tpl.id).unwrap();
assert_eq!(published.status, TemplateStatus::Published);
assert!(published.content.is_none());
assert_eq!(published.file_path, "templates/pub.liquid");
assert!(dir.path().join("templates/pub.liquid").exists());
// Unpublish
let unpublished = unpublish_template(db.conn(), dir.path(), &published.id).unwrap();
assert_eq!(unpublished.status, TemplateStatus::Draft);
assert_eq!(unpublished.content, Some("<div>body</div>".to_string()));
}
#[test]
fn publish_requires_draft() {
let (db, dir) = setup();
let tpl = create_template(db.conn(), "p1", "Tpl", TemplateKind::Post, "body").unwrap();
publish_template(db.conn(), dir.path(), &tpl.id).unwrap();
let result = publish_template(db.conn(), dir.path(), &tpl.id);
assert!(result.is_err());
}
#[test]
fn delete_template_removes_file() {
let (db, dir) = setup();
let tpl = create_template(db.conn(), "p1", "Del", TemplateKind::Post, "body").unwrap();
publish_template(db.conn(), dir.path(), &tpl.id).unwrap();
assert!(dir.path().join("templates/del.liquid").exists());
delete_template(db.conn(), dir.path(), &tpl.id, false).unwrap();
assert!(!dir.path().join("templates/del.liquid").exists());
assert!(qt::get_template_by_id(db.conn(), &tpl.id).is_err());
}
#[test]
fn validate_valid_liquid() {
assert!(validate_template("<div>{{ title }}</div>").is_ok());
assert!(validate_template("{% if x %}<p>y</p>{% endif %}").is_ok());
assert!(validate_template("{% for p in posts %}{{ p.title }}{% endfor %}").is_ok());
}
#[test]
fn validate_unclosed_output() {
assert!(validate_template("<div>{{ title </div>").is_err());
}
#[test]
fn validate_unclosed_if() {
assert!(validate_template("{% if x %}<p>y</p>").is_err());
}
#[test]
fn validate_unmatched_endif() {
assert!(validate_template("<p>y</p>{% endif %}").is_err());
}
#[test]
fn validate_unclosed_for() {
assert!(validate_template("{% for p in posts %}{{ p.title }}").is_err());
}
}

View File

@@ -1,12 +1,44 @@
use ropey::Rope; use ropey::Rope;
/// Rope-based text buffer with edit operations and cursor management. use crate::history::{EditAction, UndoHistory};
/// Selection anchor and head (cursor). Both are (line, col) positions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Selection {
pub anchor_line: usize,
pub anchor_col: usize,
pub head_line: usize,
pub head_col: usize,
}
impl Selection {
/// Returns (start, end) as (line, col) pairs in document order.
pub fn ordered(&self) -> ((usize, usize), (usize, usize)) {
let a = (self.anchor_line, self.anchor_col);
let h = (self.head_line, self.head_col);
if a <= h { (a, h) } else { (h, a) }
}
pub fn is_empty(&self) -> bool {
self.anchor_line == self.head_line && self.anchor_col == self.head_col
}
}
/// Rope-based text buffer with edit operations, cursor, selection, and undo/redo.
pub struct EditorBuffer { pub struct EditorBuffer {
rope: Rope, rope: Rope,
cursor_line: usize, cursor_line: usize,
cursor_col: usize, cursor_col: usize,
/// Vertical scroll offset in lines. /// Vertical scroll offset in lines.
scroll_offset: usize, scroll_offset: usize,
/// Selection state (None = no selection).
selection: Option<Selection>,
/// Undo/redo history.
history: UndoHistory,
/// Whether the buffer has been modified since last save/checkpoint.
dirty: bool,
/// Soft wrap enabled.
soft_wrap: bool,
} }
impl EditorBuffer { impl EditorBuffer {
@@ -16,6 +48,10 @@ impl EditorBuffer {
cursor_line: 0, cursor_line: 0,
cursor_col: 0, cursor_col: 0,
scroll_offset: 0, scroll_offset: 0,
selection: None,
history: UndoHistory::new(),
dirty: false,
soft_wrap: false,
} }
} }
@@ -47,16 +83,108 @@ impl EditorBuffer {
self.scroll_offset self.scroll_offset
} }
pub fn selection(&self) -> Option<&Selection> {
self.selection.as_ref()
}
pub fn is_dirty(&self) -> bool {
self.dirty
}
pub fn set_dirty(&mut self, dirty: bool) {
self.dirty = dirty;
}
pub fn soft_wrap(&self) -> bool {
self.soft_wrap
}
pub fn set_soft_wrap(&mut self, wrap: bool) {
self.soft_wrap = wrap;
}
pub fn set_cursor(&mut self, line: usize, col: usize) { pub fn set_cursor(&mut self, line: usize, col: usize) {
self.cursor_line = line.min(self.line_count().saturating_sub(1)); self.cursor_line = line.min(self.line_count().saturating_sub(1));
let line_len = self.current_line_len(); let line_len = self.current_line_len();
self.cursor_col = col.min(line_len); self.cursor_col = col.min(line_len);
} }
/// Insert text at the current cursor position. /// Clear the current selection.
pub fn clear_selection(&mut self) {
self.selection = None;
}
/// Start or extend a selection from the current cursor to the new cursor position.
fn extend_selection(&mut self, new_line: usize, new_col: usize) {
let sel = self.selection.get_or_insert(Selection {
anchor_line: self.cursor_line,
anchor_col: self.cursor_col,
head_line: self.cursor_line,
head_col: self.cursor_col,
});
sel.head_line = new_line;
sel.head_col = new_col;
}
/// Set selection explicitly (for double-click word select, etc).
pub fn set_selection(&mut self, anchor_line: usize, anchor_col: usize, head_line: usize, head_col: usize) {
self.selection = Some(Selection {
anchor_line,
anchor_col,
head_line,
head_col,
});
}
/// Get the selected text, or empty string if no selection.
pub fn selected_text(&self) -> String {
match &self.selection {
None => String::new(),
Some(sel) if sel.is_empty() => String::new(),
Some(sel) => {
let (start, end) = sel.ordered();
let start_idx = self.pos_to_char_idx(start.0, start.1);
let end_idx = self.pos_to_char_idx(end.0, end.1);
self.rope.slice(start_idx..end_idx).to_string()
}
}
}
/// Delete the selected text and place cursor at start of selection.
/// Returns the deleted text.
pub fn delete_selection(&mut self) -> String {
let sel = match self.selection.take() {
Some(s) if !s.is_empty() => s,
_ => return String::new(),
};
let (start, end) = sel.ordered();
let start_idx = self.pos_to_char_idx(start.0, start.1);
let end_idx = self.pos_to_char_idx(end.0, end.1);
let deleted: String = self.rope.slice(start_idx..end_idx).to_string();
self.history.push(EditAction::Delete {
pos: start_idx,
text: deleted.clone(),
});
self.rope.remove(start_idx..end_idx);
self.cursor_line = start.0;
self.cursor_col = start.1;
self.dirty = true;
deleted
}
/// Insert text at the current cursor position. Deletes selection first if any.
pub fn insert(&mut self, text: &str) { pub fn insert(&mut self, text: &str) {
if self.selection.is_some() && self.selection.as_ref().map_or(false, |s| !s.is_empty()) {
self.delete_selection();
}
let char_idx = self.cursor_char_idx(); let char_idx = self.cursor_char_idx();
self.rope.insert(char_idx, text); self.rope.insert(char_idx, text);
self.history.push(EditAction::Insert {
pos: char_idx,
text: text.to_string(),
});
for c in text.chars() { for c in text.chars() {
if c == '\n' { if c == '\n' {
self.cursor_line += 1; self.cursor_line += 1;
@@ -65,85 +193,298 @@ impl EditorBuffer {
self.cursor_col += 1; self.cursor_col += 1;
} }
} }
self.dirty = true;
} }
/// Delete one character before the cursor (backspace). /// Delete one character before the cursor (backspace).
pub fn backspace(&mut self) { pub fn backspace(&mut self) {
if self.selection.as_ref().map_or(false, |s| !s.is_empty()) {
self.delete_selection();
return;
}
if self.cursor_col > 0 { if self.cursor_col > 0 {
let char_idx = self.cursor_char_idx(); let char_idx = self.cursor_char_idx();
let deleted: String = self.rope.slice(char_idx - 1..char_idx).to_string();
self.history.push(EditAction::Delete {
pos: char_idx - 1,
text: deleted,
});
self.rope.remove(char_idx - 1..char_idx); self.rope.remove(char_idx - 1..char_idx);
self.cursor_col -= 1; self.cursor_col -= 1;
self.dirty = true;
} else if self.cursor_line > 0 { } else if self.cursor_line > 0 {
let prev_line_len = self let prev_line_len = self.line_len(self.cursor_line - 1);
.rope
.line(self.cursor_line - 1)
.len_chars()
.saturating_sub(1);
let char_idx = self.cursor_char_idx(); let char_idx = self.cursor_char_idx();
let deleted: String = self.rope.slice(char_idx - 1..char_idx).to_string();
self.history.push(EditAction::Delete {
pos: char_idx - 1,
text: deleted,
});
self.rope.remove(char_idx - 1..char_idx); self.rope.remove(char_idx - 1..char_idx);
self.cursor_line -= 1; self.cursor_line -= 1;
self.cursor_col = prev_line_len; self.cursor_col = prev_line_len;
self.dirty = true;
} }
} }
/// Delete one character after the cursor (delete key). /// Delete one character after the cursor (delete key).
pub fn delete_forward(&mut self) { pub fn delete_forward(&mut self) {
if self.selection.as_ref().map_or(false, |s| !s.is_empty()) {
self.delete_selection();
return;
}
let char_idx = self.cursor_char_idx(); let char_idx = self.cursor_char_idx();
if char_idx < self.rope.len_chars() { if char_idx < self.rope.len_chars() {
let deleted: String = self.rope.slice(char_idx..char_idx + 1).to_string();
self.history.push(EditAction::Delete {
pos: char_idx,
text: deleted,
});
self.rope.remove(char_idx..char_idx + 1); self.rope.remove(char_idx..char_idx + 1);
self.dirty = true;
} }
} }
/// Move cursor up one line. // ── Cursor movement ──────────────────────────────────────
pub fn move_up(&mut self) { pub fn move_up(&mut self) {
if self.cursor_line > 0 { self.clear_selection();
self.cursor_line -= 1; self.move_up_inner();
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) { pub fn move_down(&mut self) {
if self.cursor_line + 1 < self.line_count() { self.clear_selection();
self.cursor_line += 1; self.move_down_inner();
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) { pub fn move_left(&mut self) {
if self.cursor_col > 0 { self.clear_selection();
self.cursor_col -= 1; self.move_left_inner();
} 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) { pub fn move_right(&mut self) {
let line_len = self.current_line_len(); self.clear_selection();
if self.cursor_col < line_len { self.move_right_inner();
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) { pub fn move_home(&mut self) {
self.clear_selection();
self.cursor_col = 0; self.cursor_col = 0;
} }
/// Move cursor to end of line.
pub fn move_end(&mut self) { pub fn move_end(&mut self) {
self.clear_selection();
self.cursor_col = self.current_line_len(); self.cursor_col = self.current_line_len();
} }
/// Scroll so the cursor is visible within the given viewport height (in lines). /// Move cursor to start of previous word.
pub fn move_word_left(&mut self) {
self.clear_selection();
self.move_word_left_inner();
}
/// Move cursor to end of next word.
pub fn move_word_right(&mut self) {
self.clear_selection();
self.move_word_right_inner();
}
/// Move cursor up by a page (viewport height).
pub fn move_page_up(&mut self, page_lines: usize) {
self.clear_selection();
let target = self.cursor_line.saturating_sub(page_lines);
self.cursor_line = target;
let line_len = self.current_line_len();
self.cursor_col = self.cursor_col.min(line_len);
}
/// Move cursor down by a page (viewport height).
pub fn move_page_down(&mut self, page_lines: usize) {
self.clear_selection();
let max_line = self.line_count().saturating_sub(1);
let target = (self.cursor_line + page_lines).min(max_line);
self.cursor_line = target;
let line_len = self.current_line_len();
self.cursor_col = self.cursor_col.min(line_len);
}
// ── Selection movement ───────────────────────────────────
pub fn select_up(&mut self) {
let (new_line, new_col) = self.calc_up();
self.extend_selection(new_line, new_col);
self.cursor_line = new_line;
self.cursor_col = new_col;
}
pub fn select_down(&mut self) {
let (new_line, new_col) = self.calc_down();
self.extend_selection(new_line, new_col);
self.cursor_line = new_line;
self.cursor_col = new_col;
}
pub fn select_left(&mut self) {
let (new_line, new_col) = self.calc_left();
self.extend_selection(new_line, new_col);
self.cursor_line = new_line;
self.cursor_col = new_col;
}
pub fn select_right(&mut self) {
let (new_line, new_col) = self.calc_right();
self.extend_selection(new_line, new_col);
self.cursor_line = new_line;
self.cursor_col = new_col;
}
pub fn select_home(&mut self) {
self.extend_selection(self.cursor_line, 0);
self.cursor_col = 0;
}
pub fn select_end(&mut self) {
let end = self.current_line_len();
self.extend_selection(self.cursor_line, end);
self.cursor_col = end;
}
pub fn select_word_left(&mut self) {
let (new_line, new_col) = self.calc_word_left();
self.extend_selection(new_line, new_col);
self.cursor_line = new_line;
self.cursor_col = new_col;
}
pub fn select_word_right(&mut self) {
let (new_line, new_col) = self.calc_word_right();
self.extend_selection(new_line, new_col);
self.cursor_line = new_line;
self.cursor_col = new_col;
}
pub fn select_page_up(&mut self, page_lines: usize) {
let target = self.cursor_line.saturating_sub(page_lines);
let col = self.cursor_col.min(self.line_len(target));
self.extend_selection(target, col);
self.cursor_line = target;
self.cursor_col = col;
}
pub fn select_page_down(&mut self, page_lines: usize) {
let max_line = self.line_count().saturating_sub(1);
let target = (self.cursor_line + page_lines).min(max_line);
let col = self.cursor_col.min(self.line_len(target));
self.extend_selection(target, col);
self.cursor_line = target;
self.cursor_col = col;
}
/// Select all text.
pub fn select_all(&mut self) {
let last_line = self.line_count().saturating_sub(1);
let last_col = self.line_len(last_line);
self.selection = Some(Selection {
anchor_line: 0,
anchor_col: 0,
head_line: last_line,
head_col: last_col,
});
self.cursor_line = last_line;
self.cursor_col = last_col;
}
/// Select the word at the given position (double-click).
pub fn select_word_at(&mut self, line: usize, col: usize) {
self.set_cursor(line, col);
let line_text = match self.line(self.cursor_line) {
Some(l) => {
let s: String = l.chars().collect();
s.trim_end_matches('\n').to_string()
}
None => return,
};
if line_text.is_empty() {
return;
}
let col = self.cursor_col.min(line_text.len());
let chars: Vec<char> = line_text.chars().collect();
// Find word boundaries
let mut start = col;
while start > 0 && is_word_char(chars[start - 1]) {
start -= 1;
}
let mut end = col;
while end < chars.len() && is_word_char(chars[end]) {
end += 1;
}
if start == end && col < chars.len() {
// Click on non-word char: select just that character
end = col + 1;
start = col;
}
self.set_selection(self.cursor_line, start, self.cursor_line, end);
self.cursor_col = end;
}
// ── Undo/Redo ────────────────────────────────────────────
pub fn undo(&mut self) {
if let Some(action) = self.history.undo() {
match action {
EditAction::Insert { pos, text } => {
let end = pos + text.chars().count();
self.rope.remove(pos..end);
let (line, col) = self.char_idx_to_pos(pos);
self.cursor_line = line;
self.cursor_col = col;
}
EditAction::Delete { pos, text } => {
self.rope.insert(pos, &text);
let end_pos = pos + text.chars().count();
let (line, col) = self.char_idx_to_pos(end_pos);
self.cursor_line = line;
self.cursor_col = col;
}
}
self.clear_selection();
self.dirty = true;
}
}
pub fn redo(&mut self) {
if let Some(action) = self.history.redo() {
match action {
EditAction::Insert { pos, text } => {
self.rope.insert(pos, &text);
let end_pos = pos + text.chars().count();
let (line, col) = self.char_idx_to_pos(end_pos);
self.cursor_line = line;
self.cursor_col = col;
}
EditAction::Delete { pos, text } => {
let end = pos + text.chars().count();
self.rope.remove(pos..end);
let (line, col) = self.char_idx_to_pos(pos);
self.cursor_line = line;
self.cursor_col = col;
}
}
self.clear_selection();
self.dirty = true;
}
}
/// Mark an undo group boundary (e.g. after each keystroke pause).
pub fn mark_undo_group(&mut self) {
self.history.mark_group();
}
// ── Scrolling ────────────────────────────────────────────
pub fn ensure_cursor_visible(&mut self, visible_lines: usize) { pub fn ensure_cursor_visible(&mut self, visible_lines: usize) {
if visible_lines == 0 { if visible_lines == 0 {
return; return;
@@ -155,7 +496,6 @@ impl EditorBuffer {
} }
} }
/// Scroll by a delta (positive = down, negative = up).
pub fn scroll_by(&mut self, delta: isize) { pub fn scroll_by(&mut self, delta: isize) {
let max_scroll = self.line_count().saturating_sub(1); let max_scroll = self.line_count().saturating_sub(1);
if delta < 0 { if delta < 0 {
@@ -165,16 +505,39 @@ impl EditorBuffer {
} }
} }
// ── Internal helpers ─────────────────────────────────────
fn cursor_char_idx(&self) -> usize { fn cursor_char_idx(&self) -> usize {
let line_start = self.rope.line_to_char(self.cursor_line); self.pos_to_char_idx(self.cursor_line, self.cursor_col)
line_start + self.cursor_col }
fn pos_to_char_idx(&self, line: usize, col: usize) -> usize {
if line >= self.rope.len_lines() {
self.rope.len_chars()
} else {
let line_start = self.rope.line_to_char(line);
let line_len = self.line_len(line);
line_start + col.min(line_len)
}
}
fn char_idx_to_pos(&self, idx: usize) -> (usize, usize) {
let idx = idx.min(self.rope.len_chars());
let line = self.rope.char_to_line(idx);
let line_start = self.rope.line_to_char(line);
let col = idx - line_start;
(line, col)
} }
fn current_line_len(&self) -> usize { fn current_line_len(&self) -> usize {
if self.cursor_line < self.rope.len_lines() { self.line_len(self.cursor_line)
let line = self.rope.line(self.cursor_line); }
let len = line.len_chars();
if len > 0 && line.char(len - 1) == '\n' { fn line_len(&self, line: usize) -> usize {
if line < self.rope.len_lines() {
let l = self.rope.line(line);
let len = l.len_chars();
if len > 0 && l.char(len - 1) == '\n' {
len - 1 len - 1
} else { } else {
len len
@@ -183,6 +546,146 @@ impl EditorBuffer {
0 0
} }
} }
// ── Movement calculation helpers (no selection changes) ──
fn move_up_inner(&mut self) {
let (line, col) = self.calc_up();
self.cursor_line = line;
self.cursor_col = col;
}
fn move_down_inner(&mut self) {
let (line, col) = self.calc_down();
self.cursor_line = line;
self.cursor_col = col;
}
fn move_left_inner(&mut self) {
let (line, col) = self.calc_left();
self.cursor_line = line;
self.cursor_col = col;
}
fn move_right_inner(&mut self) {
let (line, col) = self.calc_right();
self.cursor_line = line;
self.cursor_col = col;
}
fn move_word_left_inner(&mut self) {
let (line, col) = self.calc_word_left();
self.cursor_line = line;
self.cursor_col = col;
}
fn move_word_right_inner(&mut self) {
let (line, col) = self.calc_word_right();
self.cursor_line = line;
self.cursor_col = col;
}
fn calc_up(&self) -> (usize, usize) {
if self.cursor_line > 0 {
let new_line = self.cursor_line - 1;
let new_col = self.cursor_col.min(self.line_len(new_line));
(new_line, new_col)
} else {
(self.cursor_line, self.cursor_col)
}
}
fn calc_down(&self) -> (usize, usize) {
if self.cursor_line + 1 < self.line_count() {
let new_line = self.cursor_line + 1;
let new_col = self.cursor_col.min(self.line_len(new_line));
(new_line, new_col)
} else {
(self.cursor_line, self.cursor_col)
}
}
fn calc_left(&self) -> (usize, usize) {
if self.cursor_col > 0 {
(self.cursor_line, self.cursor_col - 1)
} else if self.cursor_line > 0 {
let new_line = self.cursor_line - 1;
(new_line, self.line_len(new_line))
} else {
(0, 0)
}
}
fn calc_right(&self) -> (usize, usize) {
let line_len = self.current_line_len();
if self.cursor_col < line_len {
(self.cursor_line, self.cursor_col + 1)
} else if self.cursor_line + 1 < self.line_count() {
(self.cursor_line + 1, 0)
} else {
(self.cursor_line, self.cursor_col)
}
}
fn calc_word_left(&self) -> (usize, usize) {
if self.cursor_col == 0 && self.cursor_line == 0 {
return (0, 0);
}
if self.cursor_col == 0 {
let new_line = self.cursor_line - 1;
return (new_line, self.line_len(new_line));
}
let line_text = match self.line(self.cursor_line) {
Some(l) => {
let s: String = l.chars().collect();
s.trim_end_matches('\n').to_string()
}
None => return (self.cursor_line, 0),
};
let chars: Vec<char> = line_text.chars().collect();
let mut col = self.cursor_col.min(chars.len());
// Skip spaces
while col > 0 && !is_word_char(chars[col - 1]) {
col -= 1;
}
// Skip word chars
while col > 0 && is_word_char(chars[col - 1]) {
col -= 1;
}
(self.cursor_line, col)
}
fn calc_word_right(&self) -> (usize, usize) {
let line_len = self.current_line_len();
if self.cursor_col >= line_len {
if self.cursor_line + 1 < self.line_count() {
return (self.cursor_line + 1, 0);
}
return (self.cursor_line, self.cursor_col);
}
let line_text = match self.line(self.cursor_line) {
Some(l) => {
let s: String = l.chars().collect();
s.trim_end_matches('\n').to_string()
}
None => return (self.cursor_line, self.cursor_col),
};
let chars: Vec<char> = line_text.chars().collect();
let mut col = self.cursor_col;
// Skip word chars
while col < chars.len() && is_word_char(chars[col]) {
col += 1;
}
// Skip spaces
while col < chars.len() && !is_word_char(chars[col]) {
col += 1;
}
(self.cursor_line, col)
}
}
fn is_word_char(c: char) -> bool {
c.is_alphanumeric() || c == '_'
} }
#[cfg(test)] #[cfg(test)]
@@ -265,7 +768,7 @@ mod tests {
assert_eq!(buf.cursor(), (1, 1)); assert_eq!(buf.cursor(), (1, 1));
buf.move_up(); buf.move_up();
assert_eq!(buf.cursor(), (0, 1)); assert_eq!(buf.cursor(), (0, 1));
buf.move_up(); // at top, no-op buf.move_up();
assert_eq!(buf.cursor(), (0, 1)); assert_eq!(buf.cursor(), (0, 1));
} }
@@ -277,7 +780,7 @@ mod tests {
assert_eq!(buf.cursor(), (1, 1)); assert_eq!(buf.cursor(), (1, 1));
buf.move_down(); buf.move_down();
assert_eq!(buf.cursor(), (2, 1)); assert_eq!(buf.cursor(), (2, 1));
buf.move_down(); // at bottom, no-op buf.move_down();
assert_eq!(buf.cursor(), (2, 1)); assert_eq!(buf.cursor(), (2, 1));
} }
@@ -286,7 +789,7 @@ mod tests {
let mut buf = EditorBuffer::new("long line\nhi"); let mut buf = EditorBuffer::new("long line\nhi");
buf.set_cursor(0, 9); buf.set_cursor(0, 9);
buf.move_down(); buf.move_down();
assert_eq!(buf.cursor(), (1, 2)); // "hi" is only 2 chars assert_eq!(buf.cursor(), (1, 2));
} }
#[test] #[test]
@@ -325,12 +828,127 @@ mod tests {
assert_eq!(buf.cursor(), (0, 11)); assert_eq!(buf.cursor(), (0, 11));
} }
#[test]
fn word_movement() {
let mut buf = EditorBuffer::new("hello world test");
buf.set_cursor(0, 0);
buf.move_word_right();
assert_eq!(buf.cursor(), (0, 6)); // after "hello "
buf.move_word_right();
assert_eq!(buf.cursor(), (0, 13)); // after "world "
buf.move_word_left();
assert_eq!(buf.cursor(), (0, 6)); // back to "world"
buf.move_word_left();
assert_eq!(buf.cursor(), (0, 0)); // back to start
}
#[test]
fn page_movement() {
let mut buf = EditorBuffer::new("a\nb\nc\nd\ne\nf\ng\nh\ni\nj");
buf.set_cursor(0, 0);
buf.move_page_down(5);
assert_eq!(buf.cursor(), (5, 0));
buf.move_page_up(3);
assert_eq!(buf.cursor(), (2, 0));
}
#[test]
fn selection_shift_right() {
let mut buf = EditorBuffer::new("hello");
buf.set_cursor(0, 0);
buf.select_right();
buf.select_right();
buf.select_right();
assert_eq!(buf.selected_text(), "hel");
}
#[test]
fn selection_delete() {
let mut buf = EditorBuffer::new("hello world");
buf.set_cursor(0, 0);
buf.select_right();
buf.select_right();
buf.select_right();
buf.select_right();
buf.select_right();
let deleted = buf.delete_selection();
assert_eq!(deleted, "hello");
assert_eq!(buf.text(), " world");
}
#[test]
fn select_word_at() {
let mut buf = EditorBuffer::new("hello world");
buf.select_word_at(0, 3); // inside "hello"
assert_eq!(buf.selected_text(), "hello");
}
#[test]
fn select_all() {
let mut buf = EditorBuffer::new("hello\nworld");
buf.select_all();
assert_eq!(buf.selected_text(), "hello\nworld");
}
#[test]
fn undo_insert() {
let mut buf = EditorBuffer::new("hello");
buf.set_cursor(0, 5);
buf.insert(" world");
assert_eq!(buf.text(), "hello world");
buf.undo();
assert_eq!(buf.text(), "hello");
}
#[test]
fn redo_insert() {
let mut buf = EditorBuffer::new("hello");
buf.set_cursor(0, 5);
buf.insert(" world");
buf.undo();
buf.redo();
assert_eq!(buf.text(), "hello world");
}
#[test]
fn undo_backspace() {
let mut buf = EditorBuffer::new("hello");
buf.set_cursor(0, 5);
buf.backspace();
assert_eq!(buf.text(), "hell");
buf.undo();
assert_eq!(buf.text(), "hello");
}
#[test]
fn insert_replaces_selection() {
let mut buf = EditorBuffer::new("hello world");
buf.set_cursor(0, 0);
buf.select_right();
buf.select_right();
buf.select_right();
buf.select_right();
buf.select_right();
buf.insert("hi");
assert_eq!(buf.text(), "hi world");
}
#[test]
fn dirty_tracking() {
let mut buf = EditorBuffer::new("hello");
assert!(!buf.is_dirty());
buf.insert("x");
assert!(buf.is_dirty());
buf.set_dirty(false);
assert!(!buf.is_dirty());
}
#[test] #[test]
fn scroll_ensures_cursor_visible() { fn scroll_ensures_cursor_visible() {
let mut buf = EditorBuffer::new("a\nb\nc\nd\ne\nf\ng\nh\ni\nj"); let mut buf = EditorBuffer::new("a\nb\nc\nd\ne\nf\ng\nh\ni\nj");
buf.set_cursor(8, 0); // line 8 buf.set_cursor(8, 0);
buf.ensure_cursor_visible(5); // viewport shows 5 lines buf.ensure_cursor_visible(5);
assert_eq!(buf.scroll_offset(), 4); // scroll so line 8 is visible assert_eq!(buf.scroll_offset(), 4);
} }
#[test] #[test]

View File

@@ -1,11 +1,15 @@
use std::collections::HashMap;
use syntect::highlighting::{Style, ThemeSet}; use syntect::highlighting::{Style, ThemeSet};
use syntect::parsing::{SyntaxReference, SyntaxSet}; use syntect::parsing::{SyntaxReference, SyntaxSet};
/// Syntax highlighter using syntect. /// Syntax highlighter using syntect with line-level caching.
pub struct Highlighter { pub struct Highlighter {
syntax_set: SyntaxSet, syntax_set: SyntaxSet,
theme_set: ThemeSet, theme_set: ThemeSet,
theme_name: String, theme_name: String,
/// Extension aliases (e.g. "liquid" → "html")
extension_aliases: HashMap<String, String>,
} }
/// A line of highlighted text: spans of (style, text). /// A line of highlighted text: spans of (style, text).
@@ -13,17 +17,29 @@ pub type HighlightedLine = Vec<(Style, String)>;
impl Highlighter { impl Highlighter {
pub fn new() -> Self { pub fn new() -> Self {
let mut extension_aliases = HashMap::new();
// Liquid templates use HTML syntax highlighting
extension_aliases.insert("liquid".into(), "html".into());
extension_aliases.insert("njk".into(), "html".into());
Self { Self {
syntax_set: SyntaxSet::load_defaults_newlines(), syntax_set: SyntaxSet::load_defaults_newlines(),
theme_set: ThemeSet::load_defaults(), theme_set: ThemeSet::load_defaults(),
theme_name: "base16-ocean.dark".to_string(), theme_name: "base16-ocean.dark".to_string(),
extension_aliases,
} }
} }
/// Find the syntax definition for a file extension. /// Find the syntax definition for a file extension.
/// Resolves aliases (e.g. liquid → html) before lookup.
pub fn syntax_for_extension(&self, ext: &str) -> &SyntaxReference { pub fn syntax_for_extension(&self, ext: &str) -> &SyntaxReference {
let resolved = self
.extension_aliases
.get(ext)
.map(|s| s.as_str())
.unwrap_or(ext);
self.syntax_set self.syntax_set
.find_syntax_by_extension(ext) .find_syntax_by_extension(resolved)
.unwrap_or_else(|| self.syntax_set.find_syntax_plain_text()) .unwrap_or_else(|| self.syntax_set.find_syntax_plain_text())
} }
@@ -49,6 +65,43 @@ impl Highlighter {
result result
} }
/// Highlight only a visible range of lines (start..start+count) for a given text.
/// Re-parses from the beginning to maintain correct parse state, but only
/// collects highlight output for the visible window.
pub fn highlight_visible_range(
&self,
text: &str,
syntax: &SyntaxReference,
start: usize,
count: usize,
) -> Vec<HighlightedLine> {
use syntect::easy::HighlightLines;
let theme = &self.theme_set.themes[&self.theme_name];
let mut h = HighlightLines::new(syntax, theme);
let mut result = Vec::new();
let end = start + count;
for (idx, line) in text.lines().enumerate() {
let line_with_newline = format!("{line}\n");
let ranges = h
.highlight_line(&line_with_newline, &self.syntax_set)
.unwrap_or_default();
if idx >= start && idx < end {
let styled: HighlightedLine = ranges
.into_iter()
.map(|(style, text)| (style, text.to_string()))
.collect();
result.push(styled);
}
if idx >= end {
break;
}
}
result
}
} }
impl Default for Highlighter { impl Default for Highlighter {
@@ -78,4 +131,42 @@ mod tests {
let lines = h.highlight_lines("hello", syntax); let lines = h.highlight_lines("hello", syntax);
assert_eq!(lines.len(), 1); assert_eq!(lines.len(), 1);
} }
#[test]
fn liquid_uses_html_syntax() {
let h = Highlighter::new();
let liquid_syntax = h.syntax_for_extension("liquid");
let html_syntax = h.syntax_for_extension("html");
assert_eq!(liquid_syntax.name, html_syntax.name);
}
#[test]
fn json_syntax_available() {
let h = Highlighter::new();
let syntax = h.syntax_for_extension("json");
assert_ne!(syntax.name, "Plain Text");
}
#[test]
fn yaml_syntax_available() {
let h = Highlighter::new();
let syntax = h.syntax_for_extension("yaml");
assert_ne!(syntax.name, "Plain Text");
}
#[test]
fn lua_syntax_available() {
let h = Highlighter::new();
let syntax = h.syntax_for_extension("lua");
assert_ne!(syntax.name, "Plain Text");
}
#[test]
fn highlight_visible_range_returns_subset() {
let h = Highlighter::new();
let syntax = h.syntax_for_extension("md");
let text = "# Line 1\nLine 2\nLine 3\nLine 4\nLine 5";
let visible = h.highlight_visible_range(text, syntax, 1, 2);
assert_eq!(visible.len(), 2);
}
} }

View File

@@ -0,0 +1,115 @@
/// A single edit action that can be undone/redone.
#[derive(Debug, Clone)]
pub enum EditAction {
Insert { pos: usize, text: String },
Delete { pos: usize, text: String },
}
/// Undo/redo history with edit grouping support.
pub struct UndoHistory {
undo_stack: Vec<EditAction>,
redo_stack: Vec<EditAction>,
/// Group boundary marker: index in undo_stack where last group ended.
last_group_boundary: usize,
}
impl UndoHistory {
pub fn new() -> Self {
Self {
undo_stack: Vec::new(),
redo_stack: Vec::new(),
last_group_boundary: 0,
}
}
/// Push an edit action onto the undo stack. Clears redo stack.
pub fn push(&mut self, action: EditAction) {
self.undo_stack.push(action);
self.redo_stack.clear();
}
/// Mark a group boundary (e.g. after a pause in typing).
pub fn mark_group(&mut self) {
self.last_group_boundary = self.undo_stack.len();
}
/// Pop a single undo action.
pub fn undo(&mut self) -> Option<EditAction> {
let action = self.undo_stack.pop()?;
self.redo_stack.push(action.clone());
if self.last_group_boundary > self.undo_stack.len() {
self.last_group_boundary = self.undo_stack.len();
}
Some(action)
}
/// Pop a single redo action.
pub fn redo(&mut self) -> Option<EditAction> {
let action = self.redo_stack.pop()?;
self.undo_stack.push(action.clone());
Some(action)
}
pub fn can_undo(&self) -> bool {
!self.undo_stack.is_empty()
}
pub fn can_redo(&self) -> bool {
!self.redo_stack.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn push_and_undo() {
let mut h = UndoHistory::new();
h.push(EditAction::Insert {
pos: 0,
text: "hello".into(),
});
assert!(h.can_undo());
let action = h.undo().unwrap();
match action {
EditAction::Insert { pos, text } => {
assert_eq!(pos, 0);
assert_eq!(text, "hello");
}
_ => panic!("Expected Insert"),
}
assert!(!h.can_undo());
}
#[test]
fn undo_redo_cycle() {
let mut h = UndoHistory::new();
h.push(EditAction::Insert {
pos: 0,
text: "a".into(),
});
h.undo();
assert!(h.can_redo());
let action = h.redo().unwrap();
match action {
EditAction::Insert { text, .. } => assert_eq!(text, "a"),
_ => panic!("Expected Insert"),
}
}
#[test]
fn new_push_clears_redo() {
let mut h = UndoHistory::new();
h.push(EditAction::Insert {
pos: 0,
text: "a".into(),
});
h.undo();
h.push(EditAction::Insert {
pos: 0,
text: "b".into(),
});
assert!(!h.can_redo());
}
}

View File

@@ -1,7 +1,8 @@
mod buffer; mod buffer;
mod highlight; mod highlight;
pub mod history;
mod widget; mod widget;
pub use buffer::EditorBuffer; pub use buffer::{EditorBuffer, Selection};
pub use highlight::Highlighter; pub use highlight::Highlighter;
pub use widget::{CodeEditor, mono_metrics}; pub use widget::{CodeEditor, EditorMessage, mono_metrics};

View File

@@ -18,12 +18,19 @@ use crate::highlight::Highlighter;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum EditorMessage { pub enum EditorMessage {
ContentChanged(String), ContentChanged(String),
SaveRequested,
} }
/// Persistent widget state across frames. /// Persistent widget state across frames.
#[derive(Default)] #[derive(Default)]
struct EditorState { struct EditorState {
is_focused: bool, is_focused: bool,
/// Track drag state for click-and-drag selection
is_dragging: bool,
/// Last click time for double-click detection (ms)
last_click_time: Option<std::time::Instant>,
last_click_line: usize,
last_click_col: usize,
} }
/// Font metrics measured via cosmic-text, cached globally. /// Font metrics measured via cosmic-text, cached globally.
@@ -60,7 +67,10 @@ pub fn mono_metrics() -> &'static MonoMetrics {
break; break;
} }
MonoMetrics { char_width, line_height } MonoMetrics {
char_width,
line_height,
}
}) })
} }
@@ -72,11 +82,19 @@ 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 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 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); const ACTIVE_LINE_NUM: Color = Color::from_rgb(0.75, 0.78, 0.85);
const SELECTION_BG: Color = Color::from_rgba(0.26, 0.54, 0.79, 0.40);
/// Convert syntect RGBA color to Iced Color.
fn syntect_to_iced(c: syntect::highlighting::Color) -> Color {
Color::from_rgba(
c.r as f32 / 255.0,
c.g as f32 / 255.0,
c.b as f32 / 255.0,
c.a as f32 / 255.0,
)
}
/// A syntax-highlighting code editor widget for Iced. /// 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> { pub struct CodeEditor<'a, Message> {
buffer: &'a mut EditorBuffer, buffer: &'a mut EditorBuffer,
highlighter: &'a Highlighter, highlighter: &'a Highlighter,
@@ -142,7 +160,7 @@ where
_viewport: &Rectangle, _viewport: &Rectangle,
) { ) {
let bounds = layout.bounds(); let bounds = layout.bounds();
let _state = tree.state.downcast_ref::<EditorState>(); let state = tree.state.downcast_ref::<EditorState>();
// Background // Background
renderer.fill_quad( renderer.fill_quad(
@@ -172,6 +190,12 @@ where
let (cursor_line, cursor_col) = self.buffer.cursor(); let (cursor_line, cursor_col) = self.buffer.cursor();
let scroll = self.buffer.scroll_offset(); let scroll = self.buffer.scroll_offset();
let visible_lines = (bounds.height / metrics.line_height) as usize + 1; let visible_lines = (bounds.height / metrics.line_height) as usize + 1;
let selection = self.buffer.selection();
// Pre-compute highlighted lines for visible range
let syntax = self.highlighter.syntax_for_extension(self.extension);
let full_text = self.buffer.text();
let highlighted = self.highlighter.highlight_lines(&full_text, syntax);
let font = iced::Font::MONOSPACE; let font = iced::Font::MONOSPACE;
@@ -187,6 +211,54 @@ where
continue; continue;
} }
let text_x = bounds.x + GUTTER_WIDTH + 8.0;
// Draw selection highlight for this line
if let Some(sel) = selection {
if !sel.is_empty() {
let (start, end) = sel.ordered();
let line_len = self
.buffer
.line(line_idx)
.map(|l| {
let len = l.len_chars();
if len > 0 && l.char(len - 1) == '\n' {
len - 1
} else {
len
}
})
.unwrap_or(0);
if line_idx >= start.0 && line_idx <= end.0 {
let sel_start_col = if line_idx == start.0 { start.1 } else { 0 };
let sel_end_col = if line_idx == end.0 {
end.1
} else {
line_len + 1
};
let sel_x = text_x + sel_start_col as f32 * metrics.char_width;
let sel_w =
(sel_end_col - sel_start_col) as f32 * metrics.char_width;
if sel_w > 0.0 {
renderer.fill_quad(
renderer::Quad {
bounds: Rectangle {
x: sel_x,
y,
width: sel_w,
height: metrics.line_height,
},
border: iced::Border::default(),
shadow: iced::Shadow::default(),
},
SELECTION_BG,
);
}
}
}
}
// Line number // Line number
let line_num = format!("{:>4}", line_idx + 1); let line_num = format!("{:>4}", line_idx + 1);
let num_color = if line_idx == cursor_line { let num_color = if line_idx == cursor_line {
@@ -199,7 +271,9 @@ where
content: line_num, content: line_num,
bounds: Size::new(GUTTER_WIDTH - 8.0, metrics.line_height), bounds: Size::new(GUTTER_WIDTH - 8.0, metrics.line_height),
size: Pixels(FONT_SIZE), size: Pixels(FONT_SIZE),
line_height: iced::widget::text::LineHeight::Absolute(Pixels(metrics.line_height)), line_height: iced::widget::text::LineHeight::Absolute(Pixels(
metrics.line_height,
)),
font, font,
horizontal_alignment: iced::alignment::Horizontal::Right, horizontal_alignment: iced::alignment::Horizontal::Right,
vertical_alignment: iced::alignment::Vertical::Top, vertical_alignment: iced::alignment::Vertical::Top,
@@ -211,21 +285,57 @@ where
bounds, bounds,
); );
// Line content // Line content with syntax highlighting
if let Some(line) = self.buffer.line(line_idx) { if line_idx < highlighted.len() {
let spans = &highlighted[line_idx];
let mut x_off = text_x;
for (style, span_text) in spans {
let mut display_text = span_text.clone();
if display_text.ends_with('\n') {
display_text.pop();
}
if display_text.is_empty() {
continue;
}
let color = syntect_to_iced(style.foreground);
let span_width = display_text.len() as f32 * metrics.char_width;
renderer.fill_text(
text::Text {
content: display_text,
bounds: Size::new(span_width + metrics.char_width, metrics.line_height),
size: Pixels(FONT_SIZE),
line_height: iced::widget::text::LineHeight::Absolute(Pixels(
metrics.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(x_off, y),
color,
bounds,
);
x_off += span_width;
}
} else if let Some(line) = self.buffer.line(line_idx) {
// Fallback: plain text rendering
let mut line_text: String = line.chars().collect(); let mut line_text: String = line.chars().collect();
// Strip trailing newline for display
if line_text.ends_with('\n') { if line_text.ends_with('\n') {
line_text.pop(); line_text.pop();
} }
let text_x = bounds.x + GUTTER_WIDTH + 8.0;
renderer.fill_text( renderer.fill_text(
text::Text { text::Text {
content: line_text, content: line_text,
bounds: Size::new(bounds.width - GUTTER_WIDTH - 8.0, metrics.line_height), bounds: Size::new(
bounds.width - GUTTER_WIDTH - 8.0,
metrics.line_height,
),
size: Pixels(FONT_SIZE), size: Pixels(FONT_SIZE),
line_height: iced::widget::text::LineHeight::Absolute(Pixels(metrics.line_height)), line_height: iced::widget::text::LineHeight::Absolute(Pixels(
metrics.line_height,
)),
font, font,
horizontal_alignment: iced::alignment::Horizontal::Left, horizontal_alignment: iced::alignment::Horizontal::Left,
vertical_alignment: iced::alignment::Vertical::Top, vertical_alignment: iced::alignment::Vertical::Top,
@@ -236,24 +346,24 @@ where
TEXT_COLOR, TEXT_COLOR,
bounds, bounds,
); );
}
// Draw cursor on current line // Draw cursor on current line
if line_idx == cursor_line { if line_idx == cursor_line && state.is_focused {
let cursor_x = text_x + cursor_col as f32 * metrics.char_width; let cursor_x = text_x + cursor_col as f32 * metrics.char_width;
renderer.fill_quad( renderer.fill_quad(
renderer::Quad { renderer::Quad {
bounds: Rectangle { bounds: Rectangle {
x: cursor_x, x: cursor_x,
y, y,
width: 2.0, width: 2.0,
height: metrics.line_height, height: metrics.line_height,
},
border: iced::Border::default(),
shadow: iced::Shadow::default(),
}, },
CURSOR_COLOR, border: iced::Border::default(),
); shadow: iced::Shadow::default(),
} },
CURSOR_COLOR,
);
} }
} }
} }
@@ -265,8 +375,8 @@ where
layout: Layout<'_>, layout: Layout<'_>,
cursor: mouse::Cursor, cursor: mouse::Cursor,
_renderer: &Renderer, _renderer: &Renderer,
_clipboard: &mut dyn Clipboard, clipboard: &mut dyn Clipboard,
_shell: &mut Shell<'_, Message>, shell: &mut Shell<'_, Message>,
_viewport: &Rectangle, _viewport: &Rectangle,
) -> Status { ) -> Status {
let state = tree.state.downcast_mut::<EditorState>(); let state = tree.state.downcast_mut::<EditorState>();
@@ -277,60 +387,250 @@ where
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => { Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
if cursor.is_over(bounds) { if cursor.is_over(bounds) {
state.is_focused = true; state.is_focused = true;
// Place cursor at click position state.is_dragging = true;
if let Some(pos) = cursor.position_in(bounds) { if let Some(pos) = cursor.position_in(bounds) {
let line = (pos.y / metrics.line_height) as usize + self.buffer.scroll_offset(); let line = (pos.y / metrics.line_height) as usize
let col = ((pos.x - GUTTER_WIDTH - 8.0).max(0.0) / metrics.char_width) as usize; + self.buffer.scroll_offset();
self.buffer.set_cursor(line, col); let col = ((pos.x - GUTTER_WIDTH - 8.0).max(0.0) / metrics.char_width)
as usize;
// Double-click detection
let now = std::time::Instant::now();
let is_double_click = state
.last_click_time
.map(|t| now.duration_since(t).as_millis() < 400)
.unwrap_or(false)
&& state.last_click_line == line
&& (state.last_click_col as isize - col as isize).unsigned_abs() < 3;
if is_double_click {
self.buffer.select_word_at(line, col);
state.last_click_time = None; // reset
} else {
self.buffer.clear_selection();
self.buffer.set_cursor(line, col);
state.last_click_time = Some(now);
state.last_click_line = line;
state.last_click_col = col;
}
} }
return Status::Captured; return Status::Captured;
} else { } else {
state.is_focused = false; state.is_focused = false;
} }
} }
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
state.is_dragging = false;
}
Event::Mouse(mouse::Event::CursorMoved { .. }) => {
if state.is_dragging && state.is_focused {
if let Some(pos) = cursor.position_in(bounds) {
let line = (pos.y / metrics.line_height) as usize
+ self.buffer.scroll_offset();
let col = ((pos.x - GUTTER_WIDTH - 8.0).max(0.0) / metrics.char_width)
as usize;
// Extend selection by simulating shift+movement
let clamped_line = line.min(self.buffer.line_count().saturating_sub(1));
let clamped_col = if clamped_line < self.buffer.line_count() {
col.min(
self.buffer
.line(clamped_line)
.map(|l| {
let len = l.len_chars();
if len > 0 && l.char(len - 1) == '\n' {
len - 1
} else {
len
}
})
.unwrap_or(0),
)
} else {
0
};
self.buffer
.set_selection(
self.buffer
.selection()
.map(|s| s.anchor_line)
.unwrap_or(self.buffer.cursor().0),
self.buffer
.selection()
.map(|s| s.anchor_col)
.unwrap_or(self.buffer.cursor().1),
clamped_line,
clamped_col,
);
self.buffer.set_cursor(clamped_line, clamped_col);
}
return Status::Captured;
}
}
Event::Mouse(mouse::Event::WheelScrolled { delta }) if cursor.is_over(bounds) => { Event::Mouse(mouse::Event::WheelScrolled { delta }) if cursor.is_over(bounds) => {
let lines = match delta { let lines = match delta {
mouse::ScrollDelta::Lines { y, .. } => -(y * 3.0) as isize, mouse::ScrollDelta::Lines { y, .. } => -(y * 3.0) as isize,
mouse::ScrollDelta::Pixels { y, .. } => -(y / metrics.line_height) as isize, mouse::ScrollDelta::Pixels { y, .. } => {
-(y / metrics.line_height) as isize
}
}; };
self.buffer.scroll_by(lines); self.buffer.scroll_by(lines);
return Status::Captured; return Status::Captured;
} }
Event::Keyboard(keyboard::Event::KeyPressed { key, .. }) if state.is_focused => { Event::Keyboard(keyboard::Event::KeyPressed {
key, modifiers, ..
}) if state.is_focused => {
let vis = (bounds.height / metrics.line_height) as usize;
let is_cmd = modifiers.command();
let is_shift = modifiers.shift();
let is_alt = modifiers.alt();
match key { match key {
// Cmd+Z = undo, Cmd+Shift+Z = redo
keyboard::Key::Character(ref c) if is_cmd && c.as_str() == "z" => {
if is_shift {
self.buffer.redo();
} else {
self.buffer.undo();
}
self.emit_change(shell);
}
// Cmd+Y = redo (Windows convention)
keyboard::Key::Character(ref c) if is_cmd && c.as_str() == "y" => {
self.buffer.redo();
self.emit_change(shell);
}
// Cmd+A = select all
keyboard::Key::Character(ref c) if is_cmd && c.as_str() == "a" => {
self.buffer.select_all();
}
// Cmd+C = copy
keyboard::Key::Character(ref c) if is_cmd && c.as_str() == "c" => {
let text = self.buffer.selected_text();
if !text.is_empty() {
clipboard.write(iced::advanced::clipboard::Kind::Standard, text);
}
}
// Cmd+X = cut
keyboard::Key::Character(ref c) if is_cmd && c.as_str() == "x" => {
let text = self.buffer.selected_text();
if !text.is_empty() {
clipboard.write(iced::advanced::clipboard::Kind::Standard, text);
self.buffer.delete_selection();
self.emit_change(shell);
}
}
// Cmd+V = paste
keyboard::Key::Character(ref c) if is_cmd && c.as_str() == "v" => {
if let Some(text) =
clipboard.read(iced::advanced::clipboard::Kind::Standard)
{
self.buffer.insert(&text);
self.emit_change(shell);
}
}
// Cmd+S = save
keyboard::Key::Character(ref c) if is_cmd && c.as_str() == "s" => {
if let Some(ref on_change) = self.on_change {
shell.publish((on_change)(EditorMessage::SaveRequested));
}
}
// Arrow keys with modifiers
keyboard::Key::Named(keyboard::key::Named::ArrowUp) => { keyboard::Key::Named(keyboard::key::Named::ArrowUp) => {
self.buffer.move_up(); if is_shift {
let vis = (bounds.height / metrics.line_height) as usize; self.buffer.select_up();
} else {
self.buffer.move_up();
}
self.buffer.ensure_cursor_visible(vis); self.buffer.ensure_cursor_visible(vis);
} }
keyboard::Key::Named(keyboard::key::Named::ArrowDown) => { keyboard::Key::Named(keyboard::key::Named::ArrowDown) => {
self.buffer.move_down(); if is_shift {
let vis = (bounds.height / metrics.line_height) as usize; self.buffer.select_down();
} else {
self.buffer.move_down();
}
self.buffer.ensure_cursor_visible(vis); self.buffer.ensure_cursor_visible(vis);
} }
keyboard::Key::Named(keyboard::key::Named::ArrowLeft) => { keyboard::Key::Named(keyboard::key::Named::ArrowLeft) => {
self.buffer.move_left(); if is_shift && is_alt {
self.buffer.select_word_left();
} else if is_shift {
self.buffer.select_left();
} else if is_alt {
self.buffer.move_word_left();
} else {
self.buffer.move_left();
}
self.buffer.ensure_cursor_visible(vis);
} }
keyboard::Key::Named(keyboard::key::Named::ArrowRight) => { keyboard::Key::Named(keyboard::key::Named::ArrowRight) => {
self.buffer.move_right(); if is_shift && is_alt {
self.buffer.select_word_right();
} else if is_shift {
self.buffer.select_right();
} else if is_alt {
self.buffer.move_word_right();
} else {
self.buffer.move_right();
}
self.buffer.ensure_cursor_visible(vis);
} }
keyboard::Key::Named(keyboard::key::Named::Home) => { keyboard::Key::Named(keyboard::key::Named::Home) => {
self.buffer.move_home(); if is_shift {
self.buffer.select_home();
} else {
self.buffer.move_home();
}
} }
keyboard::Key::Named(keyboard::key::Named::End) => { keyboard::Key::Named(keyboard::key::Named::End) => {
self.buffer.move_end(); if is_shift {
self.buffer.select_end();
} else {
self.buffer.move_end();
}
}
keyboard::Key::Named(keyboard::key::Named::PageUp) => {
if is_shift {
self.buffer.select_page_up(vis);
} else {
self.buffer.move_page_up(vis);
}
self.buffer.ensure_cursor_visible(vis);
}
keyboard::Key::Named(keyboard::key::Named::PageDown) => {
if is_shift {
self.buffer.select_page_down(vis);
} else {
self.buffer.move_page_down(vis);
}
self.buffer.ensure_cursor_visible(vis);
} }
keyboard::Key::Named(keyboard::key::Named::Backspace) => { keyboard::Key::Named(keyboard::key::Named::Backspace) => {
self.buffer.backspace(); if is_alt {
// Option+Backspace = delete word left
self.buffer.select_word_left();
self.buffer.delete_selection();
} else {
self.buffer.backspace();
}
self.emit_change(shell);
} }
keyboard::Key::Named(keyboard::key::Named::Delete) => { keyboard::Key::Named(keyboard::key::Named::Delete) => {
self.buffer.delete_forward(); self.buffer.delete_forward();
self.emit_change(shell);
} }
keyboard::Key::Named(keyboard::key::Named::Enter) => { keyboard::Key::Named(keyboard::key::Named::Enter) => {
self.buffer.insert("\n"); self.buffer.insert("\n");
self.emit_change(shell);
} }
keyboard::Key::Character(ref c) => { keyboard::Key::Named(keyboard::key::Named::Tab) => {
self.buffer.insert(" ");
self.emit_change(shell);
}
keyboard::Key::Character(ref c) if !is_cmd => {
self.buffer.insert(c); self.buffer.insert(c);
self.emit_change(shell);
} }
_ => return Status::Ignored, _ => return Status::Ignored,
} }
@@ -342,6 +642,15 @@ where
} }
} }
impl<'a, Message> CodeEditor<'a, Message> {
fn emit_change(&self, shell: &mut Shell<'_, Message>) {
if let Some(ref on_change) = self.on_change {
let text = self.buffer.text();
shell.publish((on_change)(EditorMessage::ContentChanged(text)));
}
}
}
impl<'a, Message, Renderer> From<CodeEditor<'a, Message>> for Element<'a, Message, Theme, Renderer> impl<'a, Message, Renderer> From<CodeEditor<'a, Message>> for Element<'a, Message, Theme, Renderer>
where where
Renderer: renderer::Renderer + text::Renderer<Font = iced::Font> + 'a, Renderer: renderer::Renderer + text::Renderer<Font = iced::Font> + 'a,

View File

@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
@@ -19,7 +20,17 @@ use crate::state::sidebar_filter::{
}; };
use crate::state::tabs::{self, Tab, TabType}; use crate::state::tabs::{self, Tab, TabType};
use crate::state::toast::{Toast, ToastLevel}; use crate::state::toast::{Toast, ToastLevel};
use crate::views::{modal, workspace}; use crate::views::{
modal, workspace,
post_editor::{PostEditorState, PostEditorMsg},
media_editor::{MediaEditorState, MediaEditorMsg},
template_editor::{TemplateEditorState, TemplateEditorMsg},
script_editor::{ScriptEditorState, ScriptEditorMsg},
tags_view::{self, TagsViewState, TagsMsg},
settings_view::{SettingsViewState, SettingsMsg},
dashboard::DashboardState,
translation_editor::{TranslationEditorState, TranslationEditorMsg},
};
// ─────────────────────────────────────────────────────────── // ───────────────────────────────────────────────────────────
// Message // Message
@@ -112,6 +123,21 @@ pub enum Message {
RunMetadataDiff, RunMetadataDiff,
EngineTaskDone { task_id: TaskId, label: String, result: Result<String, String> }, EngineTaskDone { task_id: TaskId, label: String, result: Result<String, String> },
// Editor views
PostEditor(PostEditorMsg),
MediaEditor(MediaEditorMsg),
TemplateEditor(TemplateEditorMsg),
ScriptEditor(ScriptEditorMsg),
Tags(TagsMsg),
Settings(SettingsMsg),
TranslationEditor(TranslationEditorMsg),
// Editor data loading
PostLoaded(Result<Post, String>),
MediaLoaded(Result<Media, String>),
TemplateLoaded(Result<Template, String>),
ScriptLoaded(Result<Script, String>),
Noop, Noop,
InitMenuBar, InitMenuBar,
} }
@@ -185,6 +211,16 @@ pub struct BdsApp {
// Modal // Modal
active_modal: Option<modal::ModalState>, active_modal: Option<modal::ModalState>,
// Editor states (keyed by entity id)
post_editors: HashMap<String, PostEditorState>,
media_editors: HashMap<String, MediaEditorState>,
template_editors: HashMap<String, TemplateEditorState>,
script_editors: HashMap<String, ScriptEditorState>,
translation_editors: HashMap<String, TranslationEditorState>,
tags_view_state: Option<TagsViewState>,
settings_state: Option<SettingsViewState>,
dashboard_state: Option<DashboardState>,
} }
// ─────────────────────────────────────────────────────────── // ───────────────────────────────────────────────────────────
@@ -299,6 +335,14 @@ impl BdsApp {
theme_badge: String::from("pico"), theme_badge: String::from("pico"),
toasts: Vec::new(), toasts: Vec::new(),
active_modal: None, active_modal: None,
post_editors: HashMap::new(),
media_editors: HashMap::new(),
template_editors: HashMap::new(),
script_editors: HashMap::new(),
translation_editors: HashMap::new(),
tags_view_state: None,
settings_state: None,
dashboard_state: None,
}, },
init_task, init_task,
) )
@@ -362,6 +406,8 @@ impl BdsApp {
let idx = tabs::open_tab(&mut self.tabs, tab); let idx = tabs::open_tab(&mut self.tabs, tab);
if let Some(t) = self.tabs.get(idx) { if let Some(t) = self.tabs.get(idx) {
self.active_tab = Some(t.id.clone()); self.active_tab = Some(t.id.clone());
let tab_clone = t.clone();
self.load_editor_for_tab(&tab_clone);
} }
self.enforce_panel_tab_fallback(); self.enforce_panel_tab_fallback();
self.sync_menu_state(); self.sync_menu_state();
@@ -868,6 +914,216 @@ impl BdsApp {
} }
} }
// ── Editor view messages ──
Message::PostEditor(msg) => {
if let Some(tab_id) = self.active_tab.clone() {
if let Some(state) = self.post_editors.get_mut(&tab_id) {
match msg {
PostEditorMsg::TitleChanged(s) => { state.title = s; state.is_dirty = true; }
PostEditorMsg::SlugChanged(s) => { state.slug = s; state.is_dirty = true; }
PostEditorMsg::ExcerptChanged(s) => { state.excerpt = s; state.is_dirty = true; }
PostEditorMsg::ContentChanged(s) => { state.content = s; state.is_dirty = true; }
PostEditorMsg::AuthorChanged(s) => { state.author = s; state.is_dirty = true; }
PostEditorMsg::TemplateSlugChanged(s) => { state.template_slug = s; state.is_dirty = true; }
PostEditorMsg::ToggleDoNotTranslate(b) => { state.do_not_translate = b; state.is_dirty = true; }
PostEditorMsg::Save => {
return self.save_post_editor(&tab_id);
}
PostEditorMsg::Publish => {
return self.publish_post_editor(&tab_id);
}
PostEditorMsg::Delete => {
let name = state.title.clone();
return Task::done(Message::ShowModal(modal::ModalState::ConfirmDelete {
entity_name: name,
references: Vec::new(),
on_confirm: modal::ConfirmAction::DeletePost(tab_id),
}));
}
}
// Mark tab dirty
if let Some(tab) = self.tabs.iter_mut().find(|t| t.id == *state.post_id.as_str()) {
tab.is_dirty = state.is_dirty;
}
}
}
Task::none()
}
Message::MediaEditor(msg) => {
if let Some(tab_id) = self.active_tab.clone() {
if let Some(state) = self.media_editors.get_mut(&tab_id) {
match msg {
MediaEditorMsg::TitleChanged(s) => { state.title = s; state.is_dirty = true; }
MediaEditorMsg::AltChanged(s) => { state.alt = s; state.is_dirty = true; }
MediaEditorMsg::CaptionChanged(s) => { state.caption = s; state.is_dirty = true; }
MediaEditorMsg::AuthorChanged(s) => { state.author = s; state.is_dirty = true; }
MediaEditorMsg::Save => {
return self.save_media_editor(&tab_id);
}
MediaEditorMsg::Delete => {
let name = state.title.clone();
return Task::done(Message::ShowModal(modal::ModalState::ConfirmDelete {
entity_name: name,
references: Vec::new(),
on_confirm: modal::ConfirmAction::DeleteMedia(tab_id),
}));
}
}
if let Some(tab) = self.tabs.iter_mut().find(|t| t.id == *state.media_id.as_str()) {
tab.is_dirty = state.is_dirty;
}
}
}
Task::none()
}
Message::TemplateEditor(msg) => {
if let Some(tab_id) = self.active_tab.clone() {
if let Some(state) = self.template_editors.get_mut(&tab_id) {
match msg {
TemplateEditorMsg::TitleChanged(s) => { state.title = s; state.is_dirty = true; }
TemplateEditorMsg::SlugChanged(s) => { state.slug = s; state.is_dirty = true; }
TemplateEditorMsg::KindChanged(k) => { state.kind = k.0; state.is_dirty = true; }
TemplateEditorMsg::EnabledChanged(b) => { state.enabled = b; state.is_dirty = true; }
TemplateEditorMsg::ContentChanged(s) => { state.content = s; state.is_dirty = true; }
TemplateEditorMsg::Save => {
return self.save_template_editor(&tab_id);
}
TemplateEditorMsg::Validate => {
if let Some(st) = self.template_editors.get_mut(&tab_id) {
match engine::template::validate_template(&st.content) {
Ok(()) => { st.validation_error = None; }
Err(e) => { st.validation_error = Some(e); }
}
}
}
TemplateEditorMsg::Delete => {
let name = state.title.clone();
return Task::done(Message::ShowModal(modal::ModalState::ConfirmDelete {
entity_name: name,
references: Vec::new(),
on_confirm: modal::ConfirmAction::DeleteTemplate(tab_id),
}));
}
}
if let Some(st) = self.template_editors.get(&tab_id) {
if let Some(tab) = self.tabs.iter_mut().find(|t| t.id == tab_id) {
tab.is_dirty = st.is_dirty;
}
}
}
}
Task::none()
}
Message::ScriptEditor(msg) => {
if let Some(tab_id) = self.active_tab.clone() {
if let Some(state) = self.script_editors.get_mut(&tab_id) {
match msg {
ScriptEditorMsg::TitleChanged(s) => { state.title = s; state.is_dirty = true; }
ScriptEditorMsg::SlugChanged(s) => { state.slug = s; state.is_dirty = true; }
ScriptEditorMsg::KindChanged(k) => { state.kind = k.0; state.is_dirty = true; }
ScriptEditorMsg::EntrypointChanged(s) => { state.entrypoint = s; state.is_dirty = true; }
ScriptEditorMsg::EnabledChanged(b) => { state.enabled = b; state.is_dirty = true; }
ScriptEditorMsg::ContentChanged(s) => {
state.discovered_entrypoints = engine::script::discover_entrypoints(&s);
state.content = s;
state.is_dirty = true;
}
ScriptEditorMsg::Save => {
return self.save_script_editor(&tab_id);
}
ScriptEditorMsg::CheckSyntax => {
if let Some(st) = self.script_editors.get_mut(&tab_id) {
match engine::script::validate_script_syntax(&st.content) {
Ok(()) => { st.validation_error = None; }
Err(e) => { st.validation_error = Some(e); }
}
}
}
ScriptEditorMsg::Run => {
self.notify(ToastLevel::Info, &t(self.ui_locale, "editor.scriptRunNotYet"));
}
ScriptEditorMsg::Delete => {
let name = state.title.clone();
return Task::done(Message::ShowModal(modal::ModalState::ConfirmDelete {
entity_name: name,
references: Vec::new(),
on_confirm: modal::ConfirmAction::DeleteScript(tab_id),
}));
}
}
if let Some(st) = self.script_editors.get(&tab_id) {
if let Some(tab) = self.tabs.iter_mut().find(|t| t.id == tab_id) {
tab.is_dirty = st.is_dirty;
}
}
}
}
Task::none()
}
Message::Tags(msg) => {
self.handle_tags_msg(msg)
}
Message::Settings(msg) => {
self.handle_settings_msg(msg)
}
Message::TranslationEditor(msg) => {
if let Some(tab_id) = self.active_tab.clone() {
if let Some(state) = self.translation_editors.get_mut(&tab_id) {
match msg {
TranslationEditorMsg::TitleChanged(s) => { state.title = s; state.is_dirty = true; }
TranslationEditorMsg::ExcerptChanged(s) => { state.excerpt = s; state.is_dirty = true; }
TranslationEditorMsg::ContentChanged(s) => { state.content = s; state.is_dirty = true; }
TranslationEditorMsg::Save | TranslationEditorMsg::Publish | TranslationEditorMsg::Delete => {
// Translation save/publish/delete will be wired to engine in future
}
}
}
}
Task::none()
}
// ── Editor data loading ──
Message::PostLoaded(result) => {
match result {
Ok(post) => {
let state = PostEditorState::from_post(&post);
self.post_editors.insert(post.id.clone(), state);
}
Err(e) => self.notify(ToastLevel::Error, &e),
}
Task::none()
}
Message::MediaLoaded(result) => {
match result {
Ok(media) => {
let state = MediaEditorState::from_media(&media);
self.media_editors.insert(media.id.clone(), state);
}
Err(e) => self.notify(ToastLevel::Error, &e),
}
Task::none()
}
Message::TemplateLoaded(result) => {
match result {
Ok(template) => {
let state = TemplateEditorState::from_template(&template);
self.template_editors.insert(template.id.clone(), state);
}
Err(e) => self.notify(ToastLevel::Error, &e),
}
Task::none()
}
Message::ScriptLoaded(result) => {
match result {
Ok(script) => {
let state = ScriptEditorState::from_script(&script);
self.script_editors.insert(script.id.clone(), state);
}
Err(e) => self.notify(ToastLevel::Error, &e),
}
Task::none()
}
Message::Noop => Task::none(), Message::Noop => Task::none(),
Message::InitMenuBar => { Message::InitMenuBar => {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
@@ -913,6 +1169,13 @@ impl BdsApp {
&self.toasts, &self.toasts,
self.active_modal.as_ref(), self.active_modal.as_ref(),
self.data_dir.as_deref(), self.data_dir.as_deref(),
&self.post_editors,
&self.media_editors,
&self.template_editors,
&self.script_editors,
self.tags_view_state.as_ref(),
self.settings_state.as_ref(),
self.dashboard_state.as_ref(),
) )
} }
@@ -1381,4 +1644,390 @@ impl BdsApp {
self.menu_registry.set_enabled(MenuAction::ValidateSite, has_project); self.menu_registry.set_enabled(MenuAction::ValidateSite, has_project);
self.menu_registry.set_enabled(MenuAction::UploadSite, has_project && !self.offline_mode); self.menu_registry.set_enabled(MenuAction::UploadSite, has_project && !self.offline_mode);
} }
// ── Editor save/publish helpers ──
fn save_post_editor(&mut self, post_id: &str) -> Task<Message> {
let Some(state) = self.post_editors.get(post_id) else { return Task::none() };
let Some(ref db) = self.db else { return Task::none() };
let Some(ref data_dir) = self.data_dir else { return Task::none() };
let excerpt_val = if state.excerpt.is_empty() { None } else { Some(state.excerpt.as_str()) };
let author_val = if state.author.is_empty() { None } else { Some(state.author.as_str()) };
let tmpl_val = if state.template_slug.is_empty() { None } else { Some(state.template_slug.as_str()) };
match engine::post::update_post(
db.conn(),
data_dir,
&state.post_id,
Some(&state.title),
Some(&state.slug),
Some(excerpt_val),
Some(&state.content),
None, // tags
None, // categories
Some(author_val),
None, // language
Some(tmpl_val),
Some(state.do_not_translate),
) {
Ok(post) => {
let s = self.post_editors.get_mut(post_id).unwrap();
s.is_dirty = false;
s.updated_at = post.updated_at;
if let Some(tab) = self.tabs.iter_mut().find(|t| t.id == post.id) {
tab.is_dirty = false;
if !post.title.is_empty() {
tab.title = post.title.clone();
}
}
self.notify(ToastLevel::Success, &t(self.ui_locale, "editor.saved"));
}
Err(e) => {
self.notify(ToastLevel::Error, &format!("Save failed: {e}"));
}
}
Task::none()
}
fn publish_post_editor(&mut self, post_id: &str) -> Task<Message> {
let Some(ref db) = self.db else { return Task::none() };
let Some(ref data_dir) = self.data_dir else { return Task::none() };
match engine::post::publish_post(db.conn(), data_dir, post_id) {
Ok(post) => {
if let Some(s) = self.post_editors.get_mut(post_id) {
s.status = post.status.clone();
s.is_dirty = false;
}
self.notify(ToastLevel::Success, &t(self.ui_locale, "editor.published"));
}
Err(e) => {
self.notify(ToastLevel::Error, &format!("Publish failed: {e}"));
}
}
Task::none()
}
fn save_media_editor(&mut self, media_id: &str) -> Task<Message> {
let Some(state) = self.media_editors.get(media_id) else { return Task::none() };
let Some(ref db) = self.db else { return Task::none() };
// Build a Media struct from editor state for the update call
let media = bds_core::model::Media {
id: state.media_id.clone(),
project_id: self.active_project.as_ref().map(|p| p.id.clone()).unwrap_or_default(),
filename: state.filename.clone(),
original_name: state.original_name.clone(),
mime_type: state.mime_type.clone(),
size: state.size,
width: state.width,
height: state.height,
title: Some(state.title.clone()),
alt: Some(state.alt.clone()),
caption: Some(state.caption.clone()),
author: Some(state.author.clone()),
language: if state.language.is_empty() { None } else { Some(state.language.clone()) },
file_path: state.file_path.clone(),
sidecar_path: String::new(),
checksum: None,
tags: state.tags.clone(),
created_at: state.created_at,
updated_at: state.updated_at,
};
match bds_core::db::queries::media::update_media(db.conn(), &media) {
Ok(()) => {
let s = self.media_editors.get_mut(media_id).unwrap();
s.is_dirty = false;
if let Some(tab) = self.tabs.iter_mut().find(|t| t.id == media.id) {
tab.is_dirty = false;
}
self.notify(ToastLevel::Success, &t(self.ui_locale, "editor.saved"));
}
Err(e) => {
self.notify(ToastLevel::Error, &format!("Save failed: {e}"));
}
}
Task::none()
}
fn save_template_editor(&mut self, template_id: &str) -> Task<Message> {
let Some(state) = self.template_editors.get(template_id) else { return Task::none() };
let Some(ref db) = self.db else { return Task::none() };
let Some(ref project) = self.active_project else { return Task::none() };
match engine::template::update_template(
db.conn(),
&state.template_id,
&project.id,
Some(&state.title),
Some(&state.slug),
Some(state.kind.clone()),
Some(state.enabled),
Some(&state.content),
) {
Ok(tmpl) => {
let s = self.template_editors.get_mut(template_id).unwrap();
s.is_dirty = false;
s.updated_at = tmpl.updated_at;
if let Some(tab) = self.tabs.iter_mut().find(|t| t.id == tmpl.id) {
tab.is_dirty = false;
tab.title = tmpl.title.clone();
}
self.notify(ToastLevel::Success, &t(self.ui_locale, "editor.saved"));
}
Err(e) => {
self.notify(ToastLevel::Error, &format!("Save failed: {e}"));
}
}
Task::none()
}
fn save_script_editor(&mut self, script_id: &str) -> Task<Message> {
let Some(state) = self.script_editors.get(script_id) else { return Task::none() };
let Some(ref db) = self.db else { return Task::none() };
let Some(ref project) = self.active_project else { return Task::none() };
match engine::script::update_script(
db.conn(),
&state.script_id,
&project.id,
Some(&state.title),
Some(&state.slug),
Some(state.kind.clone()),
Some(&state.entrypoint),
Some(state.enabled),
Some(&state.content),
) {
Ok(script) => {
let s = self.script_editors.get_mut(script_id).unwrap();
s.is_dirty = false;
s.updated_at = script.updated_at;
if let Some(tab) = self.tabs.iter_mut().find(|t| t.id == script.id) {
tab.is_dirty = false;
tab.title = script.title.clone();
}
self.notify(ToastLevel::Success, &t(self.ui_locale, "editor.saved"));
}
Err(e) => {
self.notify(ToastLevel::Error, &format!("Save failed: {e}"));
}
}
Task::none()
}
fn handle_tags_msg(&mut self, msg: TagsMsg) -> Task<Message> {
// Ensure tags view state exists
if self.tags_view_state.is_none() {
let tags = if let (Some(db), Some(project)) = (&self.db, &self.active_project) {
bds_core::db::queries::tag::list_tags_by_project(db.conn(), &project.id)
.unwrap_or_default()
} else {
Vec::new()
};
self.tags_view_state = Some(TagsViewState::new(tags));
}
let state = self.tags_view_state.as_mut().unwrap();
match msg {
TagsMsg::SetSection(s) => { state.section = s; }
TagsMsg::SearchChanged(q) => { state.search_query = q; }
TagsMsg::SelectTag(id) => {
if let Some(tag) = state.tags.iter().find(|t| t.id == id) {
state.editing_tag = Some(tags_view::EditingTag {
id: tag.id.clone(),
name: tag.name.clone(),
color: tag.color.clone().unwrap_or_default(),
template_slug: tag.post_template_slug.clone().unwrap_or_default(),
});
}
}
TagsMsg::CreateTag(_name) => {
// Tag creation will dispatch to engine
}
TagsMsg::EditTagName(s) => { if let Some(ref mut e) = state.editing_tag { e.name = s; } }
TagsMsg::EditTagColor(s) => { if let Some(ref mut e) = state.editing_tag { e.color = s; } }
TagsMsg::EditTagTemplate(s) => { if let Some(ref mut e) = state.editing_tag { e.template_slug = s; } }
TagsMsg::SaveTag => { /* will wire to engine */ }
TagsMsg::DeleteTag(id) => {
let name = state.tags.iter().find(|t| t.id == id).map(|t| t.name.clone()).unwrap_or_default();
return Task::done(Message::ShowModal(modal::ModalState::ConfirmDelete {
entity_name: name,
references: Vec::new(),
on_confirm: modal::ConfirmAction::DeletePost(id), // TODO: add DeleteTag variant
}));
}
TagsMsg::SetMergeSource(s) => { state.merge_source = Some(s); }
TagsMsg::SetMergeTarget(s) => { state.merge_target = Some(s); }
TagsMsg::MergeTags => {
if let (Some(source), Some(target)) = (&state.merge_source, &state.merge_target) {
return Task::done(Message::ShowModal(modal::ModalState::Confirm {
title: t(self.ui_locale, "tags.mergeTags"),
message: t(self.ui_locale, "tags.mergeConfirm"),
on_confirm: modal::ConfirmAction::MergeTags {
source: source.clone(),
target: target.clone(),
},
}));
}
}
}
Task::none()
}
fn handle_settings_msg(&mut self, msg: SettingsMsg) -> Task<Message> {
// Ensure settings state exists
if self.settings_state.is_none() {
let mut state = SettingsViewState::default();
if let Some(ref project) = self.active_project {
state.project_name = project.name.clone();
state.project_description = project.description.clone().unwrap_or_default();
state.data_path = project.data_path.clone().unwrap_or_default();
}
if let Some(ref data_dir) = self.data_dir {
if let Ok(meta) = engine::meta::read_project_json(data_dir) {
state.public_url = meta.public_url.unwrap_or_default();
state.default_author = meta.default_author.unwrap_or_default();
state.max_posts_per_page = meta.max_posts_per_page.to_string();
}
if let Ok(pub_prefs) = engine::meta::read_publishing_json(data_dir) {
state.ssh_host = pub_prefs.ssh_host.unwrap_or_default();
state.ssh_username = pub_prefs.ssh_user.unwrap_or_default();
state.ssh_remote_path = pub_prefs.ssh_remote_path.unwrap_or_default();
state.ssh_mode = format!("{:?}", pub_prefs.ssh_mode).to_lowercase();
}
}
state.offline_mode = self.offline_mode;
self.settings_state = Some(state);
}
let state = self.settings_state.as_mut().unwrap();
match msg {
SettingsMsg::SearchChanged(q) => { state.search_query = q; }
SettingsMsg::ToggleSection(section) => {
if let Some(pos) = state.collapsed.iter().position(|s| *s == section) {
state.collapsed.remove(pos);
} else {
state.collapsed.push(section);
}
}
SettingsMsg::ProjectNameChanged(s) => { state.project_name = s; }
SettingsMsg::ProjectDescriptionChanged(s) => { state.project_description = s; }
SettingsMsg::DataPathChanged(s) => { state.data_path = s; }
SettingsMsg::BrowseDataPath => {
return crate::platform::dialog::pick_folder(t(self.ui_locale, "dialog.selectFolder"));
}
SettingsMsg::ResetDataPath => {
if let Some(ref project) = self.active_project {
state.data_path = project.data_path.clone().unwrap_or_default();
}
}
SettingsMsg::PublicUrlChanged(s) => { state.public_url = s; }
SettingsMsg::DefaultAuthorChanged(s) => { state.default_author = s; }
SettingsMsg::MaxPostsPerPageChanged(s) => { state.max_posts_per_page = s; }
SettingsMsg::SaveProject => { /* Project save will be wired to engine */ }
SettingsMsg::DefaultModeChanged(s) => { state.default_mode = s; }
SettingsMsg::DiffViewStyleChanged(s) => { state.diff_view_style = s; }
SettingsMsg::WrapLongLinesChanged(b) => { state.wrap_long_lines = b; }
SettingsMsg::HideUnchangedRegionsChanged(b) => { state.hide_unchanged_regions = b; }
SettingsMsg::SaveEditor => { /* Editor prefs save will be wired */ }
SettingsMsg::SshModeChanged(s) => { state.ssh_mode = s; }
SettingsMsg::SshHostChanged(s) => { state.ssh_host = s; }
SettingsMsg::SshUsernameChanged(s) => { state.ssh_username = s; }
SettingsMsg::SshRemotePathChanged(s) => { state.ssh_remote_path = s; }
SettingsMsg::SavePublishing => { /* Publishing save will be wired */ }
SettingsMsg::ClearPublishing => {
state.ssh_host.clear();
state.ssh_username.clear();
state.ssh_remote_path.clear();
}
SettingsMsg::OfflineModeChanged(b) => {
state.offline_mode = b;
return Task::done(Message::SetOfflineMode(b));
}
SettingsMsg::SystemPromptChanged(s) => { state.system_prompt = s; }
SettingsMsg::SaveSystemPrompt => { /* System prompt save will be wired */ }
SettingsMsg::ResetSystemPrompt => { state.system_prompt.clear(); }
SettingsMsg::RebuildPosts => { return Task::done(Message::RebuildDatabase); }
SettingsMsg::RebuildMedia => { return Task::done(Message::RebuildDatabase); }
SettingsMsg::RebuildScripts => { return Task::done(Message::RebuildDatabase); }
SettingsMsg::RebuildTemplates => { return Task::done(Message::RebuildDatabase); }
SettingsMsg::RebuildLinks => { return Task::done(Message::ReindexText); }
SettingsMsg::RegenerateThumbnails => {
self.notify(ToastLevel::Info, &t(self.ui_locale, "settings.regeneratingThumbnails"));
}
SettingsMsg::OpenDataFolder => {
if let Some(ref dir) = self.data_dir {
let _ = open::that(dir);
}
}
}
Task::none()
}
/// Load editor state when a tab is opened for an entity.
fn load_editor_for_tab(&mut self, tab: &Tab) {
let Some(ref db) = self.db else { return };
match tab.tab_type {
TabType::Post => {
if !self.post_editors.contains_key(&tab.id) {
match bds_core::db::queries::post::get_post_by_id(db.conn(), &tab.id) {
Ok(post) => {
self.post_editors.insert(post.id.clone(), PostEditorState::from_post(&post));
}
Err(e) => {
self.notify(ToastLevel::Error, &format!("Failed to load post: {e}"));
}
}
}
}
TabType::Media => {
if !self.media_editors.contains_key(&tab.id) {
match bds_core::db::queries::media::get_media_by_id(db.conn(), &tab.id) {
Ok(media) => {
self.media_editors.insert(media.id.clone(), MediaEditorState::from_media(&media));
}
Err(e) => {
self.notify(ToastLevel::Error, &format!("Failed to load media: {e}"));
}
}
}
}
TabType::Templates => {
if !self.template_editors.contains_key(&tab.id) {
match bds_core::db::queries::template::get_template_by_id(db.conn(), &tab.id) {
Ok(template) => {
self.template_editors.insert(template.id.clone(), TemplateEditorState::from_template(&template));
}
Err(e) => {
self.notify(ToastLevel::Error, &format!("Failed to load template: {e}"));
}
}
}
}
TabType::Scripts => {
if !self.script_editors.contains_key(&tab.id) {
match bds_core::db::queries::script::get_script_by_id(db.conn(), &tab.id) {
Ok(script) => {
self.script_editors.insert(script.id.clone(), ScriptEditorState::from_script(&script));
}
Err(e) => {
self.notify(ToastLevel::Error, &format!("Failed to load script: {e}"));
}
}
}
}
TabType::Tags => {
if self.tags_view_state.is_none() {
let tags = bds_core::db::queries::tag::list_tags_by_project(
db.conn(),
self.active_project.as_ref().map(|p| p.id.as_str()).unwrap_or(""),
).unwrap_or_default();
self.tags_view_state = Some(TagsViewState::new(tags));
}
}
TabType::Settings => {
// Settings state will be initialized lazily
}
_ => {}
}
}
} }

View File

@@ -0,0 +1,166 @@
use iced::widget::{button, checkbox, column, container, pick_list, row, text, text_input, Space};
use iced::{Alignment, Background, Color, Element, Length, Theme};
/// Standard form field label color.
const LABEL_COLOR: Color = Color::from_rgb(0.65, 0.68, 0.75);
const _FIELD_BG: Color = Color::from_rgb(0.15, 0.16, 0.20);
const SECTION_COLOR: Color = Color::from_rgb(0.50, 0.52, 0.58);
const DANGER_BG: Color = Color::from_rgb(0.60, 0.15, 0.15);
const DANGER_HOVER: Color = Color::from_rgb(0.70, 0.20, 0.20);
const PRIMARY_BG: Color = Color::from_rgb(0.20, 0.40, 0.70);
const PRIMARY_HOVER: Color = Color::from_rgb(0.25, 0.48, 0.80);
/// A labeled text input field.
pub fn labeled_input<'a, Message: Clone + 'a>(
label: &str,
placeholder: &str,
value: &str,
on_change: impl Fn(String) -> Message + 'a,
) -> Element<'a, Message> {
column![
text(label.to_string()).size(12).color(LABEL_COLOR),
text_input(placeholder, value).on_input(on_change).size(14),
]
.spacing(4)
.into()
}
/// A labeled select/dropdown field.
pub fn labeled_select<'a, T, Message>(
label: &str,
options: &[T],
selected: Option<&T>,
on_select: impl Fn(T) -> Message + 'a,
) -> Element<'a, Message>
where
T: ToString + PartialEq + Clone + 'a,
Message: Clone + 'a,
{
let list: Vec<T> = options.to_vec();
column![
text(label.to_string()).size(12).color(LABEL_COLOR),
pick_list(list, selected.cloned(), on_select),
]
.spacing(4)
.into()
}
/// A labeled checkbox.
pub fn labeled_checkbox<'a, Message: Clone + 'a>(
label: &str,
is_checked: bool,
on_toggle: impl Fn(bool) -> Message + 'a,
) -> Element<'a, Message> {
checkbox(label, is_checked)
.on_toggle(on_toggle)
.size(16)
.text_size(14)
.into()
}
/// A section header with optional separator line.
pub fn section_header<'a, Message: 'a>(label: &str) -> Element<'a, Message> {
column![
text(label.to_string())
.size(11)
.color(SECTION_COLOR),
container(Space::new(0, 0))
.width(Length::Fill)
.height(Length::Fixed(1.0))
.style(|_: &Theme| container::Style {
background: Some(Background::Color(Color::from_rgb(0.25, 0.25, 0.30))),
..container::Style::default()
}),
]
.spacing(4)
.into()
}
/// Primary action button style.
pub fn primary_button(theme: &Theme, status: button::Status) -> button::Style {
let _ = theme;
match status {
button::Status::Hovered => button::Style {
background: Some(Background::Color(PRIMARY_HOVER)),
text_color: Color::WHITE,
border: iced::Border {
radius: 4.0.into(),
..iced::Border::default()
},
..button::Style::default()
},
_ => button::Style {
background: Some(Background::Color(PRIMARY_BG)),
text_color: Color::WHITE,
border: iced::Border {
radius: 4.0.into(),
..iced::Border::default()
},
..button::Style::default()
},
}
}
/// Danger action button style (delete, destructive).
pub fn danger_button(theme: &Theme, status: button::Status) -> button::Style {
let _ = theme;
match status {
button::Status::Hovered => button::Style {
background: Some(Background::Color(DANGER_HOVER)),
text_color: Color::WHITE,
border: iced::Border {
radius: 4.0.into(),
..iced::Border::default()
},
..button::Style::default()
},
_ => button::Style {
background: Some(Background::Color(DANGER_BG)),
text_color: Color::WHITE,
border: iced::Border {
radius: 4.0.into(),
..iced::Border::default()
},
..button::Style::default()
},
}
}
/// Toolbar-style row with right-aligned actions.
pub fn toolbar<'a, Message: 'a>(
left: Vec<Element<'a, Message>>,
right: Vec<Element<'a, Message>>,
) -> Element<'a, Message> {
let left_row = iced::widget::Row::with_children(left)
.spacing(8)
.align_y(Alignment::Center);
let right_row = iced::widget::Row::with_children(right)
.spacing(8)
.align_y(Alignment::Center);
row![left_row, Space::with_width(Length::Fill), right_row]
.padding(8)
.align_y(Alignment::Center)
.width(Length::Fill)
.into()
}
/// Date display (read-only, locale-formatted).
pub fn date_label<'a, Message: 'a>(label: &str, timestamp_ms: i64) -> Element<'a, Message> {
let date_str = format_timestamp(timestamp_ms);
row![
text(label.to_string()).size(12).color(LABEL_COLOR),
text(date_str).size(12).color(Color::from_rgb(0.55, 0.58, 0.65)),
]
.spacing(8)
.into()
}
/// Format a Unix timestamp (ms) to a readable date string.
fn format_timestamp(ms: i64) -> String {
let secs = ms / 1000;
let (y, m, d) = bds_core::util::timestamp::year_month_day_from_unix_ms(ms);
let h = ((secs % 86400) / 3600) as u32;
let min = ((secs % 3600) / 60) as u32;
format!("{y}-{m:02}-{d:02} {h:02}:{min:02}")
}

View File

@@ -0,0 +1 @@
pub mod inputs;

View File

@@ -1,4 +1,5 @@
pub mod app; pub mod app;
pub mod components;
pub mod i18n; pub mod i18n;
pub mod platform; pub mod platform;
pub mod state; pub mod state;

View File

@@ -0,0 +1,104 @@
use iced::widget::{column, container, row, text, Space};
use iced::{Alignment, Background, Color, Element, Length, Theme};
use bds_core::i18n::UiLocale;
use crate::app::Message;
use crate::components::inputs;
use crate::i18n::t;
/// Dashboard overview state.
#[derive(Debug, Clone)]
pub struct DashboardState {
pub post_count: usize,
pub media_count: usize,
pub template_count: usize,
pub script_count: usize,
pub draft_count: usize,
pub published_count: usize,
pub project_name: String,
}
impl DashboardState {
pub fn new(project_name: String) -> Self {
Self {
post_count: 0,
media_count: 0,
template_count: 0,
script_count: 0,
draft_count: 0,
published_count: 0,
project_name,
}
}
}
/// Render the dashboard overview.
pub fn view<'a>(
state: &'a DashboardState,
locale: UiLocale,
) -> Element<'a, Message> {
let header = text(t(locale, "dashboard.overview"))
.size(20)
.color(Color::WHITE);
let project_label = text(state.project_name.clone())
.size(14)
.color(Color::from_rgb(0.6, 0.6, 0.7));
let counts_row = row![
stat_card(&t(locale, "dashboard.posts"), state.post_count),
stat_card(&t(locale, "dashboard.media"), state.media_count),
stat_card(&t(locale, "dashboard.templates"), state.template_count),
stat_card(&t(locale, "dashboard.scripts"), state.script_count),
]
.spacing(16);
let status_row = row![
stat_card(&t(locale, "dashboard.drafts"), state.draft_count),
stat_card(&t(locale, "dashboard.published"), state.published_count),
]
.spacing(16);
container(
column![
header,
project_label,
Space::with_height(16),
inputs::section_header(&t(locale, "dashboard.entityCounts")),
counts_row,
Space::with_height(12),
inputs::section_header(&t(locale, "dashboard.statusCounts")),
status_row,
]
.spacing(8)
.padding(24)
.width(Length::Fill),
)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
fn stat_card<'a>(label: &str, count: usize) -> Element<'a, Message> {
let card_bg = Color::from_rgb(0.15, 0.16, 0.20);
container(
column![
text(count.to_string()).size(28).color(Color::WHITE),
text(label.to_string()).size(12).color(Color::from_rgb(0.55, 0.58, 0.65)),
]
.spacing(4)
.align_x(Alignment::Center),
)
.padding(16)
.width(Length::FillPortion(1))
.style(move |_: &Theme| container::Style {
background: Some(Background::Color(card_bg)),
border: iced::Border {
radius: 8.0.into(),
..iced::Border::default()
},
..container::Style::default()
})
.into()
}

View File

@@ -0,0 +1,208 @@
use std::path::Path;
use iced::widget::{button, column, container, image, row, scrollable, text, Space};
use iced::{Color, Element, Length};
use bds_core::i18n::UiLocale;
use bds_core::model::Media;
use crate::app::Message;
use crate::components::inputs;
use crate::i18n::t;
/// State for an open media editor.
#[derive(Debug, Clone)]
pub struct MediaEditorState {
pub media_id: String,
pub filename: String,
pub original_name: String,
pub mime_type: String,
pub size: i64,
pub width: Option<i32>,
pub height: Option<i32>,
pub title: String,
pub alt: String,
pub caption: String,
pub author: String,
pub language: String,
pub file_path: String,
pub tags: Vec<String>,
pub created_at: i64,
pub updated_at: i64,
pub is_dirty: bool,
}
impl MediaEditorState {
pub fn from_media(media: &Media) -> Self {
Self {
media_id: media.id.clone(),
filename: media.filename.clone(),
original_name: media.original_name.clone(),
mime_type: media.mime_type.clone(),
size: media.size,
width: media.width,
height: media.height,
title: media.title.clone().unwrap_or_default(),
alt: media.alt.clone().unwrap_or_default(),
caption: media.caption.clone().unwrap_or_default(),
author: media.author.clone().unwrap_or_default(),
language: media.language.clone().unwrap_or_default(),
file_path: media.file_path.clone(),
tags: media.tags.clone(),
created_at: media.created_at,
updated_at: media.updated_at,
is_dirty: false,
}
}
}
/// Media editor messages.
#[derive(Debug, Clone)]
pub enum MediaEditorMsg {
TitleChanged(String),
AltChanged(String),
CaptionChanged(String),
AuthorChanged(String),
Save,
Delete,
}
/// Render the media editor view.
pub fn view<'a>(
state: &'a MediaEditorState,
locale: UiLocale,
data_dir: Option<&Path>,
) -> Element<'a, Message> {
let header = inputs::toolbar(
vec![
text(state.original_name.clone()).size(18).into(),
],
vec![
button(text(t(locale, "common.save")).size(13))
.on_press(Message::MediaEditor(MediaEditorMsg::Save))
.style(inputs::primary_button)
.padding([6, 16])
.into(),
button(text(t(locale, "modal.confirmDelete.delete")).size(13))
.on_press(Message::MediaEditor(MediaEditorMsg::Delete))
.style(inputs::danger_button)
.padding([6, 16])
.into(),
],
);
// Preview section
let preview: Element<'a, Message> = if state.mime_type.starts_with("image/") {
if let Some(dir) = data_dir {
let img_path = dir.join(&state.file_path);
if img_path.exists() {
container(
image(img_path.to_string_lossy().to_string())
.width(Length::Fill)
.height(Length::Fixed(300.0)),
)
.width(Length::Fill)
.into()
} else {
no_preview()
}
} else {
no_preview()
}
} else {
no_preview()
};
// File info
let dimensions = match (state.width, state.height) {
(Some(w), Some(h)) => format!("{w} × {h}"),
_ => String::new(),
};
let size_str = format_file_size(state.size);
let info = row![
text(format!("{}{}{}", state.mime_type, size_str, dimensions))
.size(12)
.color(Color::from_rgb(0.55, 0.58, 0.65)),
]
.padding(8);
// Metadata fields
let title_input = inputs::labeled_input(
&t(locale, "editor.title"),
&t(locale, "editor.titlePlaceholder"),
&state.title,
|s| Message::MediaEditor(MediaEditorMsg::TitleChanged(s)),
);
let alt_input = inputs::labeled_input(
&t(locale, "editor.alt"),
&t(locale, "editor.altPlaceholder"),
&state.alt,
|s| Message::MediaEditor(MediaEditorMsg::AltChanged(s)),
);
let meta_row1 = row![title_input, alt_input].spacing(16).width(Length::Fill);
let caption_input = inputs::labeled_input(
&t(locale, "editor.caption"),
"",
&state.caption,
|s| Message::MediaEditor(MediaEditorMsg::CaptionChanged(s)),
);
let author_input = inputs::labeled_input(
&t(locale, "editor.author"),
"",
&state.author,
|s| Message::MediaEditor(MediaEditorMsg::AuthorChanged(s)),
);
let meta_row2 = row![caption_input, author_input].spacing(16).width(Length::Fill);
// Footer
let footer = row![
inputs::date_label(&t(locale, "editor.createdAt"), state.created_at),
Space::with_width(Length::Fixed(24.0)),
inputs::date_label(&t(locale, "editor.updatedAt"), state.updated_at),
]
.padding(8);
let body = scrollable(
column![
header,
preview,
info,
inputs::section_header(&t(locale, "editor.metadata")),
meta_row1,
meta_row2,
footer,
]
.spacing(12)
.padding(16)
.width(Length::Fill)
);
container(body)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
fn no_preview<'a>() -> Element<'a, Message> {
container(
text("No preview available")
.size(14)
.color(Color::from_rgb(0.5, 0.5, 0.5)),
)
.width(Length::Fill)
.height(Length::Fixed(200.0))
.center_x(Length::Fill)
.center_y(Length::Fixed(200.0))
.into()
}
fn format_file_size(bytes: i64) -> String {
if bytes < 1024 {
format!("{bytes} B")
} else if bytes < 1024 * 1024 {
format!("{:.1} KB", bytes as f64 / 1024.0)
} else {
format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
}
}

View File

@@ -8,3 +8,11 @@ pub mod project_selector;
pub mod toast; pub mod toast;
pub mod welcome; pub mod welcome;
pub mod modal; pub mod modal;
pub mod post_editor;
pub mod media_editor;
pub mod template_editor;
pub mod script_editor;
pub mod tags_view;
pub mod settings_view;
pub mod dashboard;
pub mod translation_editor;

View File

@@ -0,0 +1,199 @@
use iced::widget::{button, column, container, row, scrollable, text, text_input, Space};
use iced::{Color, Element, Length, Theme};
use bds_core::i18n::UiLocale;
use bds_core::model::{Post, PostStatus};
use crate::app::Message;
use crate::components::inputs;
use crate::i18n::t;
/// State for an open post editor.
#[derive(Debug, Clone)]
pub struct PostEditorState {
pub post_id: String,
pub title: String,
pub slug: String,
pub excerpt: String,
pub content: String,
pub tags: Vec<String>,
pub categories: Vec<String>,
pub author: String,
pub language: String,
pub template_slug: String,
pub do_not_translate: bool,
pub status: PostStatus,
pub created_at: i64,
pub updated_at: i64,
pub is_dirty: bool,
}
impl PostEditorState {
pub fn from_post(post: &Post) -> Self {
Self {
post_id: post.id.clone(),
title: post.title.clone(),
slug: post.slug.clone(),
excerpt: post.excerpt.clone().unwrap_or_default(),
content: post.content.clone().unwrap_or_default(),
tags: post.tags.clone(),
categories: post.categories.clone(),
author: post.author.clone().unwrap_or_default(),
language: post.language.clone().unwrap_or_default(),
template_slug: post.template_slug.clone().unwrap_or_default(),
do_not_translate: post.do_not_translate,
status: post.status.clone(),
created_at: post.created_at,
updated_at: post.updated_at,
is_dirty: false,
}
}
}
/// Post editor messages.
#[derive(Debug, Clone)]
pub enum PostEditorMsg {
TitleChanged(String),
SlugChanged(String),
ExcerptChanged(String),
ContentChanged(String),
AuthorChanged(String),
TemplateSlugChanged(String),
ToggleDoNotTranslate(bool),
Save,
Publish,
Delete,
}
/// Render the post editor view.
pub fn view<'a>(
state: &'a PostEditorState,
locale: UiLocale,
) -> Element<'a, Message> {
let header = inputs::toolbar(
vec![
text(state.title.clone()).size(18).into(),
status_badge(&state.status),
],
vec![
button(text(t(locale, "common.save")).size(13))
.on_press(Message::PostEditor(PostEditorMsg::Save))
.style(inputs::primary_button)
.padding([6, 16])
.into(),
button(text(t(locale, "editor.publish")).size(13))
.on_press(Message::PostEditor(PostEditorMsg::Publish))
.style(inputs::primary_button)
.padding([6, 16])
.into(),
button(text(t(locale, "modal.confirmDelete.delete")).size(13))
.on_press(Message::PostEditor(PostEditorMsg::Delete))
.style(inputs::danger_button)
.padding([6, 16])
.into(),
],
);
// Metadata section
let title_input = inputs::labeled_input(
&t(locale, "editor.title"),
&t(locale, "editor.titlePlaceholder"),
&state.title,
|s| Message::PostEditor(PostEditorMsg::TitleChanged(s)),
);
let slug_input = inputs::labeled_input(
&t(locale, "editor.slug"),
&t(locale, "editor.slugPlaceholder"),
&state.slug,
|s| Message::PostEditor(PostEditorMsg::SlugChanged(s)),
);
let meta_row1 = row![title_input, slug_input].spacing(16).width(Length::Fill);
let author_input = inputs::labeled_input(
&t(locale, "editor.author"),
"",
&state.author,
|s| Message::PostEditor(PostEditorMsg::AuthorChanged(s)),
);
let template_input = inputs::labeled_input(
&t(locale, "editor.templateSlug"),
"",
&state.template_slug,
|s| Message::PostEditor(PostEditorMsg::TemplateSlugChanged(s)),
);
let dnt = inputs::labeled_checkbox(
&t(locale, "editor.doNotTranslate"),
state.do_not_translate,
|b| Message::PostEditor(PostEditorMsg::ToggleDoNotTranslate(b)),
);
let meta_row2 = row![author_input, template_input, dnt].spacing(16).width(Length::Fill);
// Excerpt
let excerpt_input = inputs::labeled_input(
&t(locale, "editor.excerpt"),
&t(locale, "editor.excerptPlaceholder"),
&state.excerpt,
|s| Message::PostEditor(PostEditorMsg::ExcerptChanged(s)),
);
// Content (text area placeholder — full editor will use CodeEditor widget)
let content_section: Element<'a, Message> = column![
inputs::section_header(&t(locale, "editor.content")),
container(
text_input(&t(locale, "editor.contentPlaceholder"), &state.content)
.on_input(|s| Message::PostEditor(PostEditorMsg::ContentChanged(s)))
.size(14)
)
.width(Length::Fill)
.height(Length::Fixed(300.0)),
]
.spacing(8)
.width(Length::Fill)
.into();
// Footer
let footer = row![
inputs::date_label(&t(locale, "editor.createdAt"), state.created_at),
Space::with_width(Length::Fixed(24.0)),
inputs::date_label(&t(locale, "editor.updatedAt"), state.updated_at),
]
.padding(8);
let body = scrollable(
column![
header,
meta_row1,
meta_row2,
excerpt_input,
content_section,
footer,
]
.spacing(12)
.padding(16)
.width(Length::Fill)
);
container(body)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
fn status_badge<'a>(status: &PostStatus) -> Element<'a, Message> {
let (label, color) = match status {
PostStatus::Draft => ("Draft", Color::from_rgb(0.8, 0.7, 0.2)),
PostStatus::Published => ("Published", Color::from_rgb(0.2, 0.7, 0.3)),
PostStatus::Archived => ("Archived", Color::from_rgb(0.5, 0.5, 0.5)),
};
container(text(label).size(11).color(color))
.padding([2, 8])
.style(move |_: &Theme| container::Style {
border: iced::Border {
radius: 4.0.into(),
width: 1.0,
color,
},
..container::Style::default()
})
.into()
}

View File

@@ -0,0 +1,232 @@
use iced::widget::{button, column, container, row, scrollable, text, text_input, Space};
use iced::{Color, Element, Length, Theme};
use bds_core::i18n::UiLocale;
use bds_core::model::{Script, ScriptKind, ScriptStatus};
use crate::app::Message;
use crate::components::inputs;
use crate::i18n::t;
/// State for an open script editor.
#[derive(Debug, Clone)]
pub struct ScriptEditorState {
pub script_id: String,
pub title: String,
pub slug: String,
pub kind: ScriptKind,
pub entrypoint: String,
pub enabled: bool,
pub content: String,
pub status: ScriptStatus,
pub version: i32,
pub created_at: i64,
pub updated_at: i64,
pub discovered_entrypoints: Vec<String>,
pub validation_error: Option<String>,
pub is_dirty: bool,
}
impl ScriptEditorState {
pub fn from_script(script: &Script) -> Self {
let content = script.content.clone().unwrap_or_default();
let discovered = bds_core::engine::script::discover_entrypoints(&content);
Self {
script_id: script.id.clone(),
title: script.title.clone(),
slug: script.slug.clone(),
kind: script.kind.clone(),
entrypoint: script.entrypoint.clone(),
enabled: script.enabled,
content,
status: script.status.clone(),
version: script.version,
created_at: script.created_at,
updated_at: script.updated_at,
discovered_entrypoints: discovered,
validation_error: None,
is_dirty: false,
}
}
}
/// Script kind display helper.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScriptKindOption(pub ScriptKind);
impl std::fmt::Display for ScriptKindOption {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0 {
ScriptKind::Macro => write!(f, "Macro"),
ScriptKind::Utility => write!(f, "Utility"),
ScriptKind::Transform => write!(f, "Transform"),
}
}
}
/// Script editor messages.
#[derive(Debug, Clone)]
pub enum ScriptEditorMsg {
TitleChanged(String),
SlugChanged(String),
KindChanged(ScriptKindOption),
EntrypointChanged(String),
EnabledChanged(bool),
ContentChanged(String),
Save,
CheckSyntax,
Run,
Delete,
}
/// Render the script editor view.
pub fn view<'a>(
state: &'a ScriptEditorState,
locale: UiLocale,
) -> Element<'a, Message> {
let header = inputs::toolbar(
vec![
text(state.title.clone()).size(18).into(),
status_badge(&state.status),
],
vec![
button(text(t(locale, "common.save")).size(13))
.on_press(Message::ScriptEditor(ScriptEditorMsg::Save))
.style(inputs::primary_button)
.padding([6, 16])
.into(),
button(text(t(locale, "editor.run")).size(13))
.on_press(Message::ScriptEditor(ScriptEditorMsg::Run))
.padding([6, 16])
.into(),
button(text(t(locale, "editor.checkSyntax")).size(13))
.on_press(Message::ScriptEditor(ScriptEditorMsg::CheckSyntax))
.padding([6, 16])
.into(),
button(text(t(locale, "modal.confirmDelete.delete")).size(13))
.on_press(Message::ScriptEditor(ScriptEditorMsg::Delete))
.style(inputs::danger_button)
.padding([6, 16])
.into(),
],
);
// Metadata row 1: title, slug
let title_input = inputs::labeled_input(
&t(locale, "editor.title"),
&t(locale, "editor.titlePlaceholder"),
&state.title,
|s| Message::ScriptEditor(ScriptEditorMsg::TitleChanged(s)),
);
let slug_input = inputs::labeled_input(
&t(locale, "editor.slug"),
&t(locale, "editor.slugPlaceholder"),
&state.slug,
|s| Message::ScriptEditor(ScriptEditorMsg::SlugChanged(s)),
);
let meta_row1 = row![title_input, slug_input].spacing(16).width(Length::Fill);
// Metadata row 2: kind, entrypoint, enabled
let kind_options = vec![
ScriptKindOption(ScriptKind::Macro),
ScriptKindOption(ScriptKind::Utility),
ScriptKindOption(ScriptKind::Transform),
];
let selected_kind = Some(ScriptKindOption(state.kind.clone()));
let kind_select = inputs::labeled_select(
&t(locale, "editor.kind"),
&kind_options,
selected_kind.as_ref(),
|k| Message::ScriptEditor(ScriptEditorMsg::KindChanged(k)),
);
// Entrypoint: show discovered functions as a select or text input
let entrypoint_input = inputs::labeled_input(
&t(locale, "editor.entrypoint"),
"render",
&state.entrypoint,
|s| Message::ScriptEditor(ScriptEditorMsg::EntrypointChanged(s)),
);
let enabled_check = inputs::labeled_checkbox(
&t(locale, "editor.enabled"),
state.enabled,
|b| Message::ScriptEditor(ScriptEditorMsg::EnabledChanged(b)),
);
let meta_row2 = row![kind_select, entrypoint_input, enabled_check]
.spacing(16)
.width(Length::Fill);
// Content editor (placeholder — will use CodeEditor with Lua syntax)
let content_section: Element<'a, Message> = column![
inputs::section_header(&t(locale, "editor.content")),
container(
text_input("", &state.content)
.on_input(|s| Message::ScriptEditor(ScriptEditorMsg::ContentChanged(s)))
.size(14)
)
.width(Length::Fill)
.height(Length::Fixed(300.0)),
]
.spacing(8)
.width(Length::Fill)
.into();
// Validation error
let validation: Element<'a, Message> = if let Some(ref err) = state.validation_error {
container(
text(err.clone())
.size(12)
.color(Color::from_rgb(0.9, 0.3, 0.3)),
)
.padding(8)
.into()
} else {
Space::new(0, 0).into()
};
// Footer
let footer = row![
inputs::date_label(&t(locale, "editor.createdAt"), state.created_at),
Space::with_width(Length::Fixed(24.0)),
inputs::date_label(&t(locale, "editor.updatedAt"), state.updated_at),
]
.padding(8);
let body = scrollable(
column![
header,
meta_row1,
meta_row2,
content_section,
validation,
footer,
]
.spacing(12)
.padding(16)
.width(Length::Fill)
);
container(body)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
fn status_badge<'a>(status: &ScriptStatus) -> Element<'a, Message> {
let (label, color) = match status {
ScriptStatus::Draft => ("Draft", Color::from_rgb(0.8, 0.7, 0.2)),
ScriptStatus::Published => ("Published", Color::from_rgb(0.2, 0.7, 0.3)),
};
container(text(label).size(11).color(color))
.padding([2, 8])
.style(move |_: &Theme| container::Style {
border: iced::Border {
radius: 4.0.into(),
width: 1.0,
color,
},
..container::Style::default()
})
.into()
}

View File

@@ -0,0 +1,431 @@
use iced::widget::{button, column, container, row, scrollable, text, text_input};
use iced::{Alignment, Color, Element, Length, Theme};
use bds_core::i18n::UiLocale;
use crate::app::Message;
use crate::components::inputs;
use crate::i18n::t;
/// Collapsible section identifiers per editor_settings.allium.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SettingsSection {
Project,
Editor,
Content,
AI,
Technology,
Publishing,
Data,
MCP,
}
impl SettingsSection {
pub fn all() -> &'static [SettingsSection] {
&[
Self::Project,
Self::Editor,
Self::Content,
Self::AI,
Self::Technology,
Self::Publishing,
Self::Data,
Self::MCP,
]
}
pub fn i18n_key(&self) -> &'static str {
match self {
Self::Project => "settings.nav.project",
Self::Editor => "settings.nav.editor",
Self::Content => "settings.nav.content",
Self::AI => "settings.nav.ai",
Self::Technology => "settings.nav.technology",
Self::Publishing => "settings.nav.publishing",
Self::Data => "settings.nav.data",
Self::MCP => "settings.nav.mcp",
}
}
}
/// State for the settings view.
#[derive(Debug, Clone)]
pub struct SettingsViewState {
pub search_query: String,
pub collapsed: Vec<SettingsSection>,
// Project
pub project_name: String,
pub project_description: String,
pub data_path: String,
pub public_url: String,
pub default_author: String,
pub max_posts_per_page: String,
// Editor
pub default_mode: String,
pub diff_view_style: String,
pub wrap_long_lines: bool,
pub hide_unchanged_regions: bool,
// Publishing
pub ssh_mode: String,
pub ssh_host: String,
pub ssh_username: String,
pub ssh_remote_path: String,
// AI
pub offline_mode: bool,
pub system_prompt: String,
}
impl Default for SettingsViewState {
fn default() -> Self {
Self {
search_query: String::new(),
collapsed: Vec::new(),
project_name: String::new(),
project_description: String::new(),
data_path: String::new(),
public_url: String::new(),
default_author: String::new(),
max_posts_per_page: "50".to_string(),
default_mode: "markdown".to_string(),
diff_view_style: "inline".to_string(),
wrap_long_lines: true,
hide_unchanged_regions: false,
ssh_mode: "rsync".to_string(),
ssh_host: String::new(),
ssh_username: String::new(),
ssh_remote_path: String::new(),
offline_mode: false,
system_prompt: String::new(),
}
}
}
/// Settings view messages.
#[derive(Debug, Clone)]
pub enum SettingsMsg {
SearchChanged(String),
ToggleSection(SettingsSection),
// Project
ProjectNameChanged(String),
ProjectDescriptionChanged(String),
DataPathChanged(String),
BrowseDataPath,
ResetDataPath,
PublicUrlChanged(String),
DefaultAuthorChanged(String),
MaxPostsPerPageChanged(String),
SaveProject,
// Editor
DefaultModeChanged(String),
DiffViewStyleChanged(String),
WrapLongLinesChanged(bool),
HideUnchangedRegionsChanged(bool),
SaveEditor,
// Publishing
SshModeChanged(String),
SshHostChanged(String),
SshUsernameChanged(String),
SshRemotePathChanged(String),
SavePublishing,
ClearPublishing,
// AI
OfflineModeChanged(bool),
SystemPromptChanged(String),
SaveSystemPrompt,
ResetSystemPrompt,
// Data maintenance
RebuildPosts,
RebuildMedia,
RebuildScripts,
RebuildTemplates,
RebuildLinks,
RegenerateThumbnails,
OpenDataFolder,
}
/// Render the settings view.
pub fn view<'a>(
state: &'a SettingsViewState,
locale: UiLocale,
) -> Element<'a, Message> {
let search = text_input(&t(locale, "sidebar.filter.search"), &state.search_query)
.on_input(|s| Message::Settings(SettingsMsg::SearchChanged(s)))
.size(14);
let query_lower = state.search_query.to_lowercase();
let mut sections = column![].spacing(12).width(Length::Fill);
for section in SettingsSection::all() {
let label = t(locale, section.i18n_key());
if !query_lower.is_empty() && !label.to_lowercase().contains(&query_lower) {
continue;
}
let collapsed = state.collapsed.contains(section);
let section_el = render_section(state, section, &label, collapsed, locale);
sections = sections.push(section_el);
}
let body = scrollable(
column![search, sections]
.spacing(16)
.padding(16)
.width(Length::Fill),
)
.width(Length::Fill)
.height(Length::Fill);
container(body)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
fn render_section<'a>(
state: &'a SettingsViewState,
section: &SettingsSection,
label: &str,
collapsed: bool,
locale: UiLocale,
) -> Element<'a, Message> {
let toggle_char = if collapsed { "\u{25B6}" } else { "\u{25BC}" };
let header = button(
row![
text(toggle_char).size(12),
text(label.to_string()).size(14).color(Color::WHITE),
]
.spacing(8)
.align_y(Alignment::Center),
)
.on_press(Message::Settings(SettingsMsg::ToggleSection(section.clone())))
.padding([6, 8])
.width(Length::Fill)
.style(|_: &Theme, _| button::Style::default());
if collapsed {
return column![header].into();
}
let content: Element<'a, Message> = match section {
SettingsSection::Project => section_project(state, locale),
SettingsSection::Editor => section_editor(state, locale),
SettingsSection::Content => section_content(locale),
SettingsSection::AI => section_ai(state, locale),
SettingsSection::Technology => section_technology(locale),
SettingsSection::Publishing => section_publishing(state, locale),
SettingsSection::Data => section_data(locale),
SettingsSection::MCP => section_mcp(locale),
};
column![header, content]
.spacing(4)
.into()
}
fn section_project<'a>(state: &'a SettingsViewState, locale: UiLocale) -> Element<'a, Message> {
let name = inputs::labeled_input(
&t(locale, "settings.projectName"),
"",
&state.project_name,
|s| Message::Settings(SettingsMsg::ProjectNameChanged(s)),
);
let desc = inputs::labeled_input(
&t(locale, "settings.projectDescription"),
"",
&state.project_description,
|s| Message::Settings(SettingsMsg::ProjectDescriptionChanged(s)),
);
let data_path = row![
inputs::labeled_input(
&t(locale, "settings.dataPath"),
"",
&state.data_path,
|s| Message::Settings(SettingsMsg::DataPathChanged(s)),
),
button(text(t(locale, "settings.browse")).size(12))
.on_press(Message::Settings(SettingsMsg::BrowseDataPath))
.padding([6, 12]),
button(text(t(locale, "settings.reset")).size(12))
.on_press(Message::Settings(SettingsMsg::ResetDataPath))
.padding([6, 12]),
]
.spacing(8)
.align_y(Alignment::End);
let url = inputs::labeled_input(
&t(locale, "settings.publicUrl"),
"https://",
&state.public_url,
|s| Message::Settings(SettingsMsg::PublicUrlChanged(s)),
);
let author = inputs::labeled_input(
&t(locale, "settings.defaultAuthor"),
"",
&state.default_author,
|s| Message::Settings(SettingsMsg::DefaultAuthorChanged(s)),
);
let max_posts = inputs::labeled_input(
&t(locale, "settings.maxPostsPerPage"),
"50",
&state.max_posts_per_page,
|s| Message::Settings(SettingsMsg::MaxPostsPerPageChanged(s)),
);
let save = button(text(t(locale, "common.save")).size(13))
.on_press(Message::Settings(SettingsMsg::SaveProject))
.style(inputs::primary_button)
.padding([6, 16]);
column![name, desc, data_path, url, author, max_posts, save]
.spacing(8)
.padding([0, 16])
.into()
}
fn section_editor<'a>(state: &'a SettingsViewState, locale: UiLocale) -> Element<'a, Message> {
let wrap = inputs::labeled_checkbox(
&t(locale, "settings.wrapLongLines"),
state.wrap_long_lines,
|b| Message::Settings(SettingsMsg::WrapLongLinesChanged(b)),
);
let hide = inputs::labeled_checkbox(
&t(locale, "settings.hideUnchangedRegions"),
state.hide_unchanged_regions,
|b| Message::Settings(SettingsMsg::HideUnchangedRegionsChanged(b)),
);
let save = button(text(t(locale, "common.save")).size(13))
.on_press(Message::Settings(SettingsMsg::SaveEditor))
.style(inputs::primary_button)
.padding([6, 16]);
column![wrap, hide, save]
.spacing(8)
.padding([0, 16])
.into()
}
fn section_content<'a>(locale: UiLocale) -> Element<'a, Message> {
// Categories table placeholder — full implementation in future iteration
text(t(locale, "settings.contentPlaceholder"))
.size(13)
.color(Color::from_rgb(0.5, 0.5, 0.5))
.into()
}
fn section_ai<'a>(state: &'a SettingsViewState, locale: UiLocale) -> Element<'a, Message> {
let offline = inputs::labeled_checkbox(
&t(locale, "settings.offlineMode"),
state.offline_mode,
|b| Message::Settings(SettingsMsg::OfflineModeChanged(b)),
);
let prompt = inputs::labeled_input(
&t(locale, "settings.systemPrompt"),
"",
&state.system_prompt,
|s| Message::Settings(SettingsMsg::SystemPromptChanged(s)),
);
let btns = row![
button(text(t(locale, "common.save")).size(13))
.on_press(Message::Settings(SettingsMsg::SaveSystemPrompt))
.style(inputs::primary_button)
.padding([6, 16]),
button(text(t(locale, "settings.resetToDefault")).size(13))
.on_press(Message::Settings(SettingsMsg::ResetSystemPrompt))
.padding([6, 16]),
]
.spacing(8);
column![offline, prompt, btns]
.spacing(8)
.padding([0, 16])
.into()
}
fn section_technology<'a>(locale: UiLocale) -> Element<'a, Message> {
text(t(locale, "settings.technologyPlaceholder"))
.size(13)
.color(Color::from_rgb(0.5, 0.5, 0.5))
.into()
}
fn section_publishing<'a>(state: &'a SettingsViewState, locale: UiLocale) -> Element<'a, Message> {
let host = inputs::labeled_input(
&t(locale, "settings.sshHost"),
"",
&state.ssh_host,
|s| Message::Settings(SettingsMsg::SshHostChanged(s)),
);
let user = inputs::labeled_input(
&t(locale, "settings.sshUsername"),
"",
&state.ssh_username,
|s| Message::Settings(SettingsMsg::SshUsernameChanged(s)),
);
let path = inputs::labeled_input(
&t(locale, "settings.sshRemotePath"),
"",
&state.ssh_remote_path,
|s| Message::Settings(SettingsMsg::SshRemotePathChanged(s)),
);
let btns = row![
button(text(t(locale, "common.save")).size(13))
.on_press(Message::Settings(SettingsMsg::SavePublishing))
.style(inputs::primary_button)
.padding([6, 16]),
button(text(t(locale, "settings.clear")).size(13))
.on_press(Message::Settings(SettingsMsg::ClearPublishing))
.style(inputs::danger_button)
.padding([6, 16]),
]
.spacing(8);
column![host, user, path, btns]
.spacing(8)
.padding([0, 16])
.into()
}
fn section_data<'a>(locale: UiLocale) -> Element<'a, Message> {
let rebuild_btns = column![
button(text(t(locale, "settings.rebuildPosts")).size(13))
.on_press(Message::Settings(SettingsMsg::RebuildPosts))
.padding([6, 16])
.width(Length::Fill),
button(text(t(locale, "settings.rebuildMedia")).size(13))
.on_press(Message::Settings(SettingsMsg::RebuildMedia))
.padding([6, 16])
.width(Length::Fill),
button(text(t(locale, "settings.rebuildScripts")).size(13))
.on_press(Message::Settings(SettingsMsg::RebuildScripts))
.padding([6, 16])
.width(Length::Fill),
button(text(t(locale, "settings.rebuildTemplates")).size(13))
.on_press(Message::Settings(SettingsMsg::RebuildTemplates))
.padding([6, 16])
.width(Length::Fill),
button(text(t(locale, "settings.rebuildLinks")).size(13))
.on_press(Message::Settings(SettingsMsg::RebuildLinks))
.padding([6, 16])
.width(Length::Fill),
button(text(t(locale, "settings.regenerateThumbnails")).size(13))
.on_press(Message::Settings(SettingsMsg::RegenerateThumbnails))
.padding([6, 16])
.width(Length::Fill),
]
.spacing(4);
let open = button(text(t(locale, "settings.openDataFolder")).size(13))
.on_press(Message::Settings(SettingsMsg::OpenDataFolder))
.padding([6, 16]);
column![rebuild_btns, open]
.spacing(12)
.padding([0, 16])
.into()
}
fn section_mcp<'a>(locale: UiLocale) -> Element<'a, Message> {
// MCP status and agent toggles — placeholder for M3
text(t(locale, "settings.mcpPlaceholder"))
.size(13)
.color(Color::from_rgb(0.5, 0.5, 0.5))
.into()
}

View File

@@ -0,0 +1,309 @@
use iced::widget::{button, column, container, row, scrollable, text, text_input, Space};
use iced::{Alignment, Background, Color, Element, Length, Theme};
use bds_core::i18n::UiLocale;
use bds_core::model::Tag;
use crate::app::Message;
use crate::components::inputs;
use crate::i18n::t;
const DEFAULT_TAG_COLOR: &str = "#6495ed";
/// Active view within the Tags tab.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TagsSection {
Cloud,
Manage,
Merge,
}
/// State for the tags view.
#[derive(Debug, Clone)]
pub struct TagsViewState {
pub section: TagsSection,
pub tags: Vec<Tag>,
pub search_query: String,
/// For "Manage": the currently editing tag
pub editing_tag: Option<EditingTag>,
/// For "Merge": source and target tag selection
pub merge_source: Option<String>,
pub merge_target: Option<String>,
}
#[derive(Debug, Clone)]
pub struct EditingTag {
pub id: String,
pub name: String,
pub color: String,
pub template_slug: String,
}
impl TagsViewState {
pub fn new(tags: Vec<Tag>) -> Self {
Self {
section: TagsSection::Cloud,
tags,
search_query: String::new(),
editing_tag: None,
merge_source: None,
merge_target: None,
}
}
}
/// Tags view messages.
#[derive(Debug, Clone)]
pub enum TagsMsg {
SetSection(TagsSection),
SearchChanged(String),
SelectTag(String),
CreateTag(String),
EditTagName(String),
EditTagColor(String),
EditTagTemplate(String),
SaveTag,
DeleteTag(String),
SetMergeSource(String),
SetMergeTarget(String),
MergeTags,
}
/// Render the tags management view.
pub fn view<'a>(
state: &'a TagsViewState,
locale: UiLocale,
) -> Element<'a, Message> {
// Section navigation tabs
let section_nav = row![
section_tab(&t(locale, "tags.nav.cloud"), state.section == TagsSection::Cloud, TagsSection::Cloud),
section_tab(&t(locale, "tags.nav.manage"), state.section == TagsSection::Manage, TagsSection::Manage),
section_tab(&t(locale, "tags.nav.merge"), state.section == TagsSection::Merge, TagsSection::Merge),
]
.spacing(4)
.padding(8);
let content: Element<'a, Message> = match state.section {
TagsSection::Cloud => view_cloud(state, locale),
TagsSection::Manage => view_manage(state, locale),
TagsSection::Merge => view_merge(state, locale),
};
column![section_nav, content]
.width(Length::Fill)
.height(Length::Fill)
.into()
}
fn section_tab<'a>(label: &str, active: bool, section: TagsSection) -> Element<'a, Message> {
let color = if active {
Color::WHITE
} else {
Color::from_rgb(0.55, 0.58, 0.65)
};
button(text(label.to_string()).size(13).color(color))
.on_press(Message::Tags(TagsMsg::SetSection(section)))
.padding([6, 12])
.style(move |_theme: &Theme, _status| {
if active {
button::Style {
background: Some(Background::Color(Color::from_rgb(0.25, 0.27, 0.33))),
border: iced::Border {
radius: 4.0.into(),
..iced::Border::default()
},
..button::Style::default()
}
} else {
button::Style::default()
}
})
.into()
}
fn view_cloud<'a>(state: &'a TagsViewState, locale: UiLocale) -> Element<'a, Message> {
if state.tags.is_empty() {
return container(
text(t(locale, "tags.noTags")).size(14).color(Color::from_rgb(0.5, 0.5, 0.5)),
)
.width(Length::Fill)
.height(Length::Fill)
.center_x(Length::Fill)
.center_y(Length::Fill)
.into();
}
let chips: Vec<Element<'a, Message>> = state
.tags
.iter()
.map(|tag| {
let color = parse_tag_color(tag.color.as_deref().unwrap_or(DEFAULT_TAG_COLOR));
button(text(&tag.name).size(13).color(Color::WHITE))
.on_press(Message::Tags(TagsMsg::SelectTag(tag.id.clone())))
.padding([4, 10])
.style(move |_: &Theme, _| button::Style {
background: Some(Background::Color(color)),
border: iced::Border {
radius: 12.0.into(),
..iced::Border::default()
},
text_color: Color::WHITE,
..button::Style::default()
})
.into()
})
.collect();
let cloud = iced::widget::Column::with_children(chips).spacing(6);
scrollable(
container(cloud)
.width(Length::Fill)
.padding(16),
)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
fn view_manage<'a>(state: &'a TagsViewState, locale: UiLocale) -> Element<'a, Message> {
let search = text_input(&t(locale, "sidebar.filter.search"), &state.search_query)
.on_input(|s| Message::Tags(TagsMsg::SearchChanged(s)))
.size(14);
let filtered: Vec<&Tag> = state
.tags
.iter()
.filter(|t| {
state.search_query.is_empty()
|| t.name.to_lowercase().contains(&state.search_query.to_lowercase())
})
.collect();
let rows: Vec<Element<'a, Message>> = filtered
.iter()
.map(|tag| {
let color = parse_tag_color(tag.color.as_deref().unwrap_or(DEFAULT_TAG_COLOR));
row![
container(Space::new(12, 12))
.style(move |_: &Theme| container::Style {
background: Some(Background::Color(color)),
border: iced::Border {
radius: 6.0.into(),
..iced::Border::default()
},
..container::Style::default()
}),
text(&tag.name).size(14),
Space::with_width(Length::Fill),
button(text(t(locale, "modal.confirmDelete.delete")).size(12))
.on_press(Message::Tags(TagsMsg::DeleteTag(tag.id.clone())))
.style(inputs::danger_button)
.padding([3, 8])
]
.spacing(8)
.align_y(Alignment::Center)
.padding(4)
.into()
})
.collect();
let tag_list = iced::widget::Column::with_children(rows).spacing(2);
// Edit panel for selected tag
let edit_panel: Element<'a, Message> = if let Some(ref editing) = state.editing_tag {
column![
inputs::section_header(&t(locale, "tags.editTag")),
inputs::labeled_input(
&t(locale, "tags.name"),
"",
&editing.name,
|s| Message::Tags(TagsMsg::EditTagName(s)),
),
inputs::labeled_input(
&t(locale, "tags.color"),
"#3498db",
&editing.color,
|s| Message::Tags(TagsMsg::EditTagColor(s)),
),
inputs::labeled_input(
&t(locale, "tags.postTemplate"),
"",
&editing.template_slug,
|s| Message::Tags(TagsMsg::EditTagTemplate(s)),
),
button(text(t(locale, "common.save")).size(13))
.on_press(Message::Tags(TagsMsg::SaveTag))
.style(inputs::primary_button)
.padding([6, 16]),
]
.spacing(8)
.padding(12)
.into()
} else {
Space::new(0, 0).into()
};
scrollable(
column![
search,
tag_list,
edit_panel,
]
.spacing(12)
.padding(16)
.width(Length::Fill)
)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
fn view_merge<'a>(state: &'a TagsViewState, locale: UiLocale) -> Element<'a, Message> {
let source_input = inputs::labeled_input(
&t(locale, "tags.mergeSource"),
&t(locale, "tags.selectTag"),
state.merge_source.as_deref().unwrap_or(""),
|s| Message::Tags(TagsMsg::SetMergeSource(s)),
);
let target_input = inputs::labeled_input(
&t(locale, "tags.mergeTarget"),
&t(locale, "tags.selectTag"),
state.merge_target.as_deref().unwrap_or(""),
|s| Message::Tags(TagsMsg::SetMergeTarget(s)),
);
let can_merge = state.merge_source.is_some() && state.merge_target.is_some();
let merge_btn = if can_merge {
button(text(t(locale, "tags.merge")).size(13))
.on_press(Message::Tags(TagsMsg::MergeTags))
.style(inputs::primary_button)
.padding([6, 16])
} else {
button(text(t(locale, "tags.merge")).size(13))
.padding([6, 16])
};
column![
source_input,
target_input,
merge_btn,
]
.spacing(12)
.padding(16)
.width(Length::Fill)
.into()
}
fn parse_tag_color(hex: &str) -> Color {
let hex = hex.trim_start_matches('#');
if hex.len() == 6 {
let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(100);
let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(100);
let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(100);
Color::from_rgb(r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0)
} else {
Color::from_rgb(0.4, 0.5, 0.7)
}
}

View File

@@ -0,0 +1,211 @@
use iced::widget::{button, column, container, row, scrollable, text, text_input, Space};
use iced::{Color, Element, Length, Theme};
use bds_core::i18n::UiLocale;
use bds_core::model::{Template, TemplateKind, TemplateStatus};
use crate::app::Message;
use crate::components::inputs;
use crate::i18n::t;
/// State for an open template editor.
#[derive(Debug, Clone)]
pub struct TemplateEditorState {
pub template_id: String,
pub title: String,
pub slug: String,
pub kind: TemplateKind,
pub enabled: bool,
pub content: String,
pub status: TemplateStatus,
pub version: i32,
pub created_at: i64,
pub updated_at: i64,
pub validation_error: Option<String>,
pub is_dirty: bool,
}
impl TemplateEditorState {
pub fn from_template(tpl: &Template) -> Self {
Self {
template_id: tpl.id.clone(),
title: tpl.title.clone(),
slug: tpl.slug.clone(),
kind: tpl.kind.clone(),
enabled: tpl.enabled,
content: tpl.content.clone().unwrap_or_default(),
status: tpl.status.clone(),
version: tpl.version,
created_at: tpl.created_at,
updated_at: tpl.updated_at,
validation_error: None,
is_dirty: false,
}
}
}
/// Template kind display helper.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateKindOption(pub TemplateKind);
impl std::fmt::Display for TemplateKindOption {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0 {
TemplateKind::Post => write!(f, "Post"),
TemplateKind::List => write!(f, "List"),
TemplateKind::NotFound => write!(f, "Not Found"),
TemplateKind::Partial => write!(f, "Partial"),
}
}
}
/// Template editor messages.
#[derive(Debug, Clone)]
pub enum TemplateEditorMsg {
TitleChanged(String),
SlugChanged(String),
KindChanged(TemplateKindOption),
EnabledChanged(bool),
ContentChanged(String),
Save,
Validate,
Delete,
}
/// Render the template editor view.
pub fn view<'a>(
state: &'a TemplateEditorState,
locale: UiLocale,
) -> Element<'a, Message> {
let header = inputs::toolbar(
vec![
text(state.title.clone()).size(18).into(),
status_badge(&state.status),
],
vec![
button(text(t(locale, "common.save")).size(13))
.on_press(Message::TemplateEditor(TemplateEditorMsg::Save))
.style(inputs::primary_button)
.padding([6, 16])
.into(),
button(text(t(locale, "editor.validate")).size(13))
.on_press(Message::TemplateEditor(TemplateEditorMsg::Validate))
.padding([6, 16])
.into(),
button(text(t(locale, "modal.confirmDelete.delete")).size(13))
.on_press(Message::TemplateEditor(TemplateEditorMsg::Delete))
.style(inputs::danger_button)
.padding([6, 16])
.into(),
],
);
// Metadata row 1: title, slug
let title_input = inputs::labeled_input(
&t(locale, "editor.title"),
&t(locale, "editor.titlePlaceholder"),
&state.title,
|s| Message::TemplateEditor(TemplateEditorMsg::TitleChanged(s)),
);
let slug_input = inputs::labeled_input(
&t(locale, "editor.slug"),
&t(locale, "editor.slugPlaceholder"),
&state.slug,
|s| Message::TemplateEditor(TemplateEditorMsg::SlugChanged(s)),
);
let meta_row1 = row![title_input, slug_input].spacing(16).width(Length::Fill);
// Metadata row 2: kind (select), enabled (checkbox)
let kind_options = vec![
TemplateKindOption(TemplateKind::Post),
TemplateKindOption(TemplateKind::List),
TemplateKindOption(TemplateKind::NotFound),
TemplateKindOption(TemplateKind::Partial),
];
let selected_kind = Some(TemplateKindOption(state.kind.clone()));
let kind_select = inputs::labeled_select(
&t(locale, "editor.kind"),
&kind_options,
selected_kind.as_ref(),
|k| Message::TemplateEditor(TemplateEditorMsg::KindChanged(k)),
);
let enabled_check = inputs::labeled_checkbox(
&t(locale, "editor.enabled"),
state.enabled,
|b| Message::TemplateEditor(TemplateEditorMsg::EnabledChanged(b)),
);
let meta_row2 = row![kind_select, enabled_check].spacing(16).width(Length::Fill);
// Content editor (text area placeholder — will use CodeEditor widget for liquid)
let content_section: Element<'a, Message> = column![
inputs::section_header(&t(locale, "editor.content")),
container(
text_input("", &state.content)
.on_input(|s| Message::TemplateEditor(TemplateEditorMsg::ContentChanged(s)))
.size(14)
)
.width(Length::Fill)
.height(Length::Fixed(300.0)),
]
.spacing(8)
.width(Length::Fill)
.into();
// Validation error
let validation: Element<'a, Message> = if let Some(ref err) = state.validation_error {
container(
text(err.clone())
.size(12)
.color(Color::from_rgb(0.9, 0.3, 0.3)),
)
.padding(8)
.into()
} else {
Space::new(0, 0).into()
};
// Footer
let footer = row![
inputs::date_label(&t(locale, "editor.createdAt"), state.created_at),
Space::with_width(Length::Fixed(24.0)),
inputs::date_label(&t(locale, "editor.updatedAt"), state.updated_at),
]
.padding(8);
let body = scrollable(
column![
header,
meta_row1,
meta_row2,
content_section,
validation,
footer,
]
.spacing(12)
.padding(16)
.width(Length::Fill)
);
container(body)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
fn status_badge<'a>(status: &TemplateStatus) -> Element<'a, Message> {
let (label, color) = match status {
TemplateStatus::Draft => ("Draft", Color::from_rgb(0.8, 0.7, 0.2)),
TemplateStatus::Published => ("Published", Color::from_rgb(0.2, 0.7, 0.3)),
};
container(text(label).size(11).color(color))
.padding([2, 8])
.style(move |_: &Theme| container::Style {
border: iced::Border {
radius: 4.0.into(),
width: 1.0,
color,
},
..container::Style::default()
})
.into()
}

View File

@@ -0,0 +1,154 @@
use iced::widget::{button, column, container, row, scrollable, text, text_input, Space};
use iced::{Color, Element, Length, Theme};
use bds_core::i18n::UiLocale;
use crate::app::Message;
use crate::components::inputs;
use crate::i18n::t;
/// State for the translation editor (post translation).
#[derive(Debug, Clone)]
pub struct TranslationEditorState {
pub post_id: String,
pub post_title: String,
pub language: String,
pub title: String,
pub excerpt: String,
pub content: String,
pub status: String, // draft | published
pub created_at: i64,
pub updated_at: i64,
pub is_dirty: bool,
}
impl TranslationEditorState {
pub fn new(post_id: String, post_title: String, language: String) -> Self {
Self {
post_id,
post_title,
language,
title: String::new(),
excerpt: String::new(),
content: String::new(),
status: "draft".to_string(),
created_at: 0,
updated_at: 0,
is_dirty: false,
}
}
}
/// Translation editor messages.
#[derive(Debug, Clone)]
pub enum TranslationEditorMsg {
TitleChanged(String),
ExcerptChanged(String),
ContentChanged(String),
Save,
Publish,
Delete,
}
/// Render the translation editor view.
pub fn view<'a>(
state: &'a TranslationEditorState,
locale: UiLocale,
) -> Element<'a, Message> {
let header = inputs::toolbar(
vec![
text(format!("{} [{}]", &state.post_title, &state.language))
.size(18)
.into(),
status_badge(&state.status),
],
vec![
button(text(t(locale, "common.save")).size(13))
.on_press(Message::TranslationEditor(TranslationEditorMsg::Save))
.style(inputs::primary_button)
.padding([6, 16])
.into(),
button(text(t(locale, "editor.publish")).size(13))
.on_press(Message::TranslationEditor(TranslationEditorMsg::Publish))
.style(inputs::primary_button)
.padding([6, 16])
.into(),
button(text(t(locale, "modal.confirmDelete.delete")).size(13))
.on_press(Message::TranslationEditor(TranslationEditorMsg::Delete))
.style(inputs::danger_button)
.padding([6, 16])
.into(),
],
);
let title_input = inputs::labeled_input(
&t(locale, "editor.title"),
&t(locale, "editor.titlePlaceholder"),
&state.title,
|s| Message::TranslationEditor(TranslationEditorMsg::TitleChanged(s)),
);
let excerpt_input = inputs::labeled_input(
&t(locale, "editor.excerpt"),
&t(locale, "editor.excerptPlaceholder"),
&state.excerpt,
|s| Message::TranslationEditor(TranslationEditorMsg::ExcerptChanged(s)),
);
let content_section: Element<'a, Message> = column![
inputs::section_header(&t(locale, "editor.content")),
container(
text_input(&t(locale, "editor.contentPlaceholder"), &state.content)
.on_input(|s| Message::TranslationEditor(TranslationEditorMsg::ContentChanged(s)))
.size(14)
)
.width(Length::Fill)
.height(Length::Fixed(300.0)),
]
.spacing(8)
.width(Length::Fill)
.into();
let footer = row![
inputs::date_label(&t(locale, "editor.createdAt"), state.created_at),
Space::with_width(Length::Fixed(24.0)),
inputs::date_label(&t(locale, "editor.updatedAt"), state.updated_at),
]
.padding(8);
let body = scrollable(
column![
header,
title_input,
excerpt_input,
content_section,
footer,
]
.spacing(12)
.padding(16)
.width(Length::Fill),
);
container(body)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
fn status_badge<'a>(status: &str) -> Element<'a, Message> {
let (label, color) = match status {
"published" => ("Published", Color::from_rgb(0.2, 0.7, 0.3)),
_ => ("Draft", Color::from_rgb(0.8, 0.7, 0.2)),
};
container(text(label).size(11).color(color))
.padding([2, 8])
.style(move |_: &Theme| container::Style {
border: iced::Border {
radius: 4.0.into(),
width: 1.0,
color,
},
..container::Style::default()
})
.into()
}

View File

@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::path::Path; use std::path::Path;
use iced::widget::{button, column, container, mouse_area, row, stack, text, Space}; use iced::widget::{button, column, container, mouse_area, row, stack, text, Space};
@@ -12,7 +13,16 @@ use crate::state::navigation::{OutputEntry, PanelTab, SidebarView, TaskSnapshot}
use crate::state::sidebar_filter::{PostFilter, MediaFilter}; use crate::state::sidebar_filter::{PostFilter, MediaFilter};
use crate::state::tabs::{Tab, TabType}; use crate::state::tabs::{Tab, TabType};
use crate::state::toast::Toast; use crate::state::toast::Toast;
use crate::views::{activity_bar, modal, panel, project_selector, sidebar, status_bar, tab_bar, toast, welcome}; use crate::views::{
activity_bar, modal, panel, project_selector, sidebar, status_bar, tab_bar, toast, welcome,
post_editor::{self, PostEditorState},
media_editor::{self, MediaEditorState},
template_editor::{self, TemplateEditorState},
script_editor::{self, ScriptEditorState},
tags_view::{self, TagsViewState},
settings_view::{self, SettingsViewState},
dashboard::DashboardState,
};
/// Main content area background. /// Main content area background.
fn content_bg(_theme: &Theme) -> container::Style { fn content_bg(_theme: &Theme) -> container::Style {
@@ -31,7 +41,7 @@ fn drag_handle_style(_theme: &Theme) -> container::Style {
} }
/// Horizontal line separator (full width). /// Horizontal line separator (full width).
fn separator_h() -> iced::widget::Container<'static, Message> { fn separator_h<'a>() -> Element<'a, Message> {
container(Space::new(0, 0)) container(Space::new(0, 0))
.width(Length::Fill) .width(Length::Fill)
.height(Length::Fixed(1.0)) .height(Length::Fixed(1.0))
@@ -39,57 +49,70 @@ fn separator_h() -> iced::widget::Container<'static, Message> {
background: Some(Background::Color(Color::from_rgb(0.25, 0.25, 0.30))), background: Some(Background::Color(Color::from_rgb(0.25, 0.25, 0.30))),
..container::Style::default() ..container::Style::default()
}) })
.into()
} }
/// Compose the full workspace layout. /// Compose the full workspace layout.
pub fn view( pub fn view<'a>(
// Navigation // Navigation
sidebar_view: SidebarView, sidebar_view: SidebarView,
sidebar_visible: bool, sidebar_visible: bool,
sidebar_width: f32, sidebar_width: f32,
// Tabs // Tabs
tabs: &[Tab], tabs: &'a [Tab],
active_tab: Option<&str>, active_tab: Option<&'a str>,
// Panel // Panel
panel_visible: bool, panel_visible: bool,
panel_tab: PanelTab, panel_tab: PanelTab,
task_snapshots: &[TaskSnapshot], task_snapshots: &'a [TaskSnapshot],
output_entries: &[OutputEntry], output_entries: &'a [OutputEntry],
// Sidebar data // Sidebar data
sidebar_posts: &[Post], sidebar_posts: &'a [Post],
sidebar_media: &[Media], sidebar_media: &'a [Media],
sidebar_scripts: &[Script], sidebar_scripts: &'a [Script],
sidebar_templates: &[Template], sidebar_templates: &'a [Template],
// Sidebar filters // Sidebar filters
post_filter: &PostFilter, post_filter: &'a PostFilter,
media_filter: &MediaFilter, media_filter: &'a MediaFilter,
// Status bar // Status bar
active_project_name: Option<&str>, active_project_name: Option<&'a str>,
projects: &[Project], projects: &'a [Project],
active_project_id: Option<&str>, active_project_id: Option<&'a str>,
post_count: usize, post_count: usize,
media_count: usize, media_count: usize,
offline_mode: bool, offline_mode: bool,
locale_dropdown_open: bool, locale_dropdown_open: bool,
project_dropdown_open: bool, project_dropdown_open: bool,
theme_badge: &str, theme_badge: &'a str,
// i18n // i18n
locale: UiLocale, locale: UiLocale,
// Toasts // Toasts
toasts: &[Toast], toasts: &'a [Toast],
// Modal // Modal
active_modal: Option<&modal::ModalState>, active_modal: Option<&'a modal::ModalState>,
// Data directory (for thumbnail paths) // Data directory (for thumbnail paths)
data_dir: Option<&Path>, data_dir: Option<&'a Path>,
) -> Element<'static, Message> { // Editor states
post_editors: &'a HashMap<String, PostEditorState>,
media_editors: &'a HashMap<String, MediaEditorState>,
template_editors: &'a HashMap<String, TemplateEditorState>,
script_editors: &'a HashMap<String, ScriptEditorState>,
tags_view_state: Option<&'a TagsViewState>,
settings_state: Option<&'a SettingsViewState>,
dashboard_state: Option<&'a DashboardState>,
) -> Element<'a, Message> {
// Activity bar (leftmost column) // Activity bar (leftmost column)
let activity = activity_bar::view(sidebar_view, sidebar_visible, locale); let activity = activity_bar::view(sidebar_view, sidebar_visible, locale);
// Tab bar // Tab bar
let tabs_el = tab_bar::view(tabs, active_tab, locale); let tabs_el = tab_bar::view(tabs, active_tab, locale);
// Content area // Content area — route based on active tab type
let content_area = welcome::view(locale); let content_area = route_content_area(
tabs, active_tab, locale, data_dir,
post_editors, media_editors, template_editors, script_editors,
tags_view_state, settings_state, dashboard_state,
);
// Right column: tab bar + content + panel // Right column: tab bar + content + panel
let mut right_col = column![tabs_el, content_area]; let mut right_col = column![tabs_el, content_area];
@@ -163,14 +186,14 @@ pub fn view(
active_post_status.as_deref(), active_post_status.as_deref(),
); );
let base_layout: Element<'static, Message> = column![main_row, separator_h(), status] let base_layout: Element<'a, Message> = column![main_row, separator_h(), status]
.width(Length::Fill) .width(Length::Fill)
.height(Length::Fill) .height(Length::Fill)
.into(); .into();
// Overlay: either locale dropdown or project dropdown (mutually exclusive) // Overlay: either locale dropdown or project dropdown (mutually exclusive)
let overlay: Option<Element<'static, Message>> = if locale_dropdown_open { let overlay: Option<Element<'a, Message>> = if locale_dropdown_open {
let items: Vec<Element<'static, Message>> = UiLocale::all() let items: Vec<Element<'a, Message>> = UiLocale::all()
.iter() .iter()
.map(|&l| { .map(|&l| {
let flag_text = text(l.flag_emoji()) let flag_text = text(l.flag_emoji())
@@ -236,7 +259,7 @@ pub fn view(
}; };
// Collect overlays: dropdowns and toasts // Collect overlays: dropdowns and toasts
let mut overlays: Vec<Element<'static, Message>> = Vec::new(); let mut overlays: Vec<Element<'a, Message>> = Vec::new();
if let Some(toast_overlay) = toast::view(toasts) { if let Some(toast_overlay) = toast::view(toasts) {
overlays.push(toast_overlay); overlays.push(toast_overlay);
@@ -262,3 +285,83 @@ pub fn view(
.into() .into()
} }
} }
/// Route the content area based on the active tab type.
fn route_content_area<'a>(
tabs: &'a [Tab],
active_tab: Option<&'a str>,
locale: UiLocale,
data_dir: Option<&'a Path>,
post_editors: &'a HashMap<String, PostEditorState>,
media_editors: &'a HashMap<String, MediaEditorState>,
template_editors: &'a HashMap<String, TemplateEditorState>,
script_editors: &'a HashMap<String, ScriptEditorState>,
tags_view_state: Option<&'a TagsViewState>,
settings_state: Option<&'a SettingsViewState>,
_dashboard_state: Option<&'a DashboardState>,
) -> Element<'a, Message> {
let Some(tab_id) = active_tab else {
return welcome::view(locale);
};
let Some(tab) = tabs.iter().find(|t| t.id == tab_id) else {
return welcome::view(locale);
};
match tab.tab_type {
TabType::Post => {
if let Some(state) = post_editors.get(tab_id) {
post_editor::view(state, locale)
} else {
loading_view(locale)
}
}
TabType::Media => {
if let Some(state) = media_editors.get(tab_id) {
media_editor::view(state, locale, data_dir)
} else {
loading_view(locale)
}
}
TabType::Templates => {
if let Some(state) = template_editors.get(tab_id) {
template_editor::view(state, locale)
} else {
loading_view(locale)
}
}
TabType::Scripts => {
if let Some(state) = script_editors.get(tab_id) {
script_editor::view(state, locale)
} else {
loading_view(locale)
}
}
TabType::Tags => {
if let Some(state) = tags_view_state {
tags_view::view(state, locale)
} else {
loading_view(locale)
}
}
TabType::Settings => {
if let Some(state) = settings_state {
settings_view::view(state, locale)
} else {
loading_view(locale)
}
}
_ => welcome::view(locale),
}
}
fn loading_view<'a>(locale: UiLocale) -> Element<'a, Message> {
use crate::i18n::t;
container(
text(t(locale, "tabBar.loading")).size(14).color(Color::from_rgb(0.5, 0.5, 0.5)),
)
.width(Length::Fill)
.height(Length::Fill)
.center_x(Length::Fill)
.center_y(Length::Fill)
.into()
}

View File

@@ -171,5 +171,74 @@
"sidebar.filter.tags": "Tags", "sidebar.filter.tags": "Tags",
"sidebar.filter.categories": "Kategorien", "sidebar.filter.categories": "Kategorien",
"sidebar.filter.calendar": "Archiv", "sidebar.filter.calendar": "Archiv",
"sidebar.filter.noResults": "Keine Treffer" "sidebar.filter.noResults": "Keine Treffer",
"editor.title": "Titel",
"editor.titlePlaceholder": "Titel eingeben...",
"editor.slug": "Slug",
"editor.slugPlaceholder": "slug-eingeben",
"editor.content": "Inhalt",
"editor.contentPlaceholder": "Inhalt schreiben...",
"editor.excerpt": "Auszug",
"editor.excerptPlaceholder": "Kurze Zusammenfassung...",
"editor.author": "Autor",
"editor.templateSlug": "Vorlage",
"editor.doNotTranslate": "Nicht übersetzen",
"editor.publish": "Veröffentlichen",
"editor.validate": "Validieren",
"editor.run": "Ausführen",
"editor.checkSyntax": "Syntax prüfen",
"editor.kind": "Art",
"editor.enabled": "Aktiviert",
"editor.entrypoint": "Einstiegspunkt",
"editor.alt": "Alternativtext",
"editor.altPlaceholder": "Bild beschreiben...",
"editor.caption": "Bildunterschrift",
"editor.metadata": "Metadaten",
"editor.createdAt": "Erstellt",
"editor.updatedAt": "Aktualisiert",
"tags.noTags": "Noch keine Tags",
"tags.editTag": "Tag bearbeiten",
"tags.name": "Name",
"tags.color": "Farbe",
"tags.postTemplate": "Beitragsvorlage",
"tags.merge": "Zusammenführen",
"tags.mergeSource": "Quell-Tag",
"tags.mergeTarget": "Ziel-Tag",
"tags.selectTag": "Tag zum Bearbeiten auswählen",
"settings.projectName": "Projektname",
"settings.projectDescription": "Beschreibung",
"settings.dataPath": "Datenordner",
"settings.browse": "Durchsuchen...",
"settings.reset": "Zurücksetzen",
"settings.publicUrl": "Öffentliche URL",
"settings.defaultAuthor": "Standardautor",
"settings.maxPostsPerPage": "Beiträge pro Seite",
"settings.wrapLongLines": "Lange Zeilen umbrechen",
"settings.hideUnchangedRegions": "Unveränderte Bereiche ausblenden",
"settings.offlineMode": "Flugmodus",
"settings.systemPrompt": "System-Prompt",
"settings.resetToDefault": "Auf Standard zurücksetzen",
"settings.sshHost": "SSH-Host",
"settings.sshUsername": "SSH-Benutzername",
"settings.sshRemotePath": "Remote-Pfad",
"settings.clear": "Leeren",
"settings.rebuildPosts": "Beiträge neu aufbauen",
"settings.rebuildMedia": "Medien neu aufbauen",
"settings.rebuildScripts": "Skripte neu aufbauen",
"settings.rebuildTemplates": "Vorlagen neu aufbauen",
"settings.rebuildLinks": "Links neu aufbauen",
"settings.regenerateThumbnails": "Vorschaubilder regenerieren",
"settings.openDataFolder": "Datenordner öffnen",
"settings.contentPlaceholder": "Inhaltseinstellungen erscheinen hier",
"settings.technologyPlaceholder": "Technologieeinstellungen erscheinen hier",
"settings.mcpPlaceholder": "MCP-Server-Einstellungen erscheinen hier",
"dashboard.overview": "Übersicht",
"dashboard.posts": "Beiträge",
"dashboard.media": "Medien",
"dashboard.templates": "Vorlagen",
"dashboard.scripts": "Skripte",
"dashboard.drafts": "Entwürfe",
"dashboard.published": "Veröffentlicht",
"dashboard.entityCounts": "Anzahl Entitäten",
"dashboard.statusCounts": "Statusübersicht"
} }

View File

@@ -171,5 +171,74 @@
"sidebar.filter.tags": "Tags", "sidebar.filter.tags": "Tags",
"sidebar.filter.categories": "Categories", "sidebar.filter.categories": "Categories",
"sidebar.filter.calendar": "Archive", "sidebar.filter.calendar": "Archive",
"sidebar.filter.noResults": "No matching items" "sidebar.filter.noResults": "No matching items",
"editor.title": "Title",
"editor.titlePlaceholder": "Enter title...",
"editor.slug": "Slug",
"editor.slugPlaceholder": "enter-slug",
"editor.content": "Content",
"editor.contentPlaceholder": "Write your content...",
"editor.excerpt": "Excerpt",
"editor.excerptPlaceholder": "Brief summary...",
"editor.author": "Author",
"editor.templateSlug": "Template",
"editor.doNotTranslate": "Do Not Translate",
"editor.publish": "Publish",
"editor.validate": "Validate",
"editor.run": "Run",
"editor.checkSyntax": "Check Syntax",
"editor.kind": "Kind",
"editor.enabled": "Enabled",
"editor.entrypoint": "Entrypoint",
"editor.alt": "Alt Text",
"editor.altPlaceholder": "Describe the image...",
"editor.caption": "Caption",
"editor.metadata": "Metadata",
"editor.createdAt": "Created",
"editor.updatedAt": "Updated",
"tags.noTags": "No tags yet",
"tags.editTag": "Edit Tag",
"tags.name": "Name",
"tags.color": "Color",
"tags.postTemplate": "Post Template",
"tags.merge": "Merge",
"tags.mergeSource": "Source Tag",
"tags.mergeTarget": "Target Tag",
"tags.selectTag": "Select a tag to edit",
"settings.projectName": "Project Name",
"settings.projectDescription": "Description",
"settings.dataPath": "Data Folder",
"settings.browse": "Browse...",
"settings.reset": "Reset",
"settings.publicUrl": "Public URL",
"settings.defaultAuthor": "Default Author",
"settings.maxPostsPerPage": "Posts per Page",
"settings.wrapLongLines": "Wrap Long Lines",
"settings.hideUnchangedRegions": "Hide Unchanged Regions",
"settings.offlineMode": "Airplane Mode",
"settings.systemPrompt": "System Prompt",
"settings.resetToDefault": "Reset to Default",
"settings.sshHost": "SSH Host",
"settings.sshUsername": "SSH Username",
"settings.sshRemotePath": "Remote Path",
"settings.clear": "Clear",
"settings.rebuildPosts": "Rebuild Posts",
"settings.rebuildMedia": "Rebuild Media",
"settings.rebuildScripts": "Rebuild Scripts",
"settings.rebuildTemplates": "Rebuild Templates",
"settings.rebuildLinks": "Rebuild Links",
"settings.regenerateThumbnails": "Regenerate Thumbnails",
"settings.openDataFolder": "Open Data Folder",
"settings.contentPlaceholder": "Content settings will appear here",
"settings.technologyPlaceholder": "Technology settings will appear here",
"settings.mcpPlaceholder": "MCP server settings will appear here",
"dashboard.overview": "Overview",
"dashboard.posts": "Posts",
"dashboard.media": "Media",
"dashboard.templates": "Templates",
"dashboard.scripts": "Scripts",
"dashboard.drafts": "Drafts",
"dashboard.published": "Published",
"dashboard.entityCounts": "Entity Counts",
"dashboard.statusCounts": "Status Breakdown"
} }

View File

@@ -171,5 +171,74 @@
"sidebar.filter.tags": "Etiquetas", "sidebar.filter.tags": "Etiquetas",
"sidebar.filter.categories": "Categorías", "sidebar.filter.categories": "Categorías",
"sidebar.filter.calendar": "Archivo", "sidebar.filter.calendar": "Archivo",
"sidebar.filter.noResults": "Sin resultados" "sidebar.filter.noResults": "Sin resultados",
"editor.title": "Título",
"editor.titlePlaceholder": "Introducir título...",
"editor.slug": "Slug",
"editor.slugPlaceholder": "introducir-slug",
"editor.content": "Contenido",
"editor.contentPlaceholder": "Escribe tu contenido...",
"editor.excerpt": "Extracto",
"editor.excerptPlaceholder": "Breve resumen...",
"editor.author": "Autor",
"editor.templateSlug": "Plantilla",
"editor.doNotTranslate": "No traducir",
"editor.publish": "Publicar",
"editor.validate": "Validar",
"editor.run": "Ejecutar",
"editor.checkSyntax": "Verificar sintaxis",
"editor.kind": "Tipo",
"editor.enabled": "Habilitado",
"editor.entrypoint": "Punto de entrada",
"editor.alt": "Texto alternativo",
"editor.altPlaceholder": "Describir la imagen...",
"editor.caption": "Leyenda",
"editor.metadata": "Metadatos",
"editor.createdAt": "Creado",
"editor.updatedAt": "Actualizado",
"tags.noTags": "Sin etiquetas",
"tags.editTag": "Editar etiqueta",
"tags.name": "Nombre",
"tags.color": "Color",
"tags.postTemplate": "Plantilla de artículo",
"tags.merge": "Fusionar",
"tags.mergeSource": "Etiqueta origen",
"tags.mergeTarget": "Etiqueta destino",
"tags.selectTag": "Seleccione una etiqueta para editar",
"settings.projectName": "Nombre del proyecto",
"settings.projectDescription": "Descripción",
"settings.dataPath": "Carpeta de datos",
"settings.browse": "Explorar...",
"settings.reset": "Restablecer",
"settings.publicUrl": "URL pública",
"settings.defaultAuthor": "Autor predeterminado",
"settings.maxPostsPerPage": "Artículos por página",
"settings.wrapLongLines": "Ajuste de línea automático",
"settings.hideUnchangedRegions": "Ocultar regiones sin cambios",
"settings.offlineMode": "Modo avión",
"settings.systemPrompt": "Prompt del sistema",
"settings.resetToDefault": "Restaurar valores predeterminados",
"settings.sshHost": "Host SSH",
"settings.sshUsername": "Nombre de usuario SSH",
"settings.sshRemotePath": "Ruta remota",
"settings.clear": "Limpiar",
"settings.rebuildPosts": "Reconstruir artículos",
"settings.rebuildMedia": "Reconstruir medios",
"settings.rebuildScripts": "Reconstruir scripts",
"settings.rebuildTemplates": "Reconstruir plantillas",
"settings.rebuildLinks": "Reconstruir enlaces",
"settings.regenerateThumbnails": "Regenerar miniaturas",
"settings.openDataFolder": "Abrir carpeta de datos",
"settings.contentPlaceholder": "La configuración de contenido aparecerá aquí",
"settings.technologyPlaceholder": "La configuración tecnológica aparecerá aquí",
"settings.mcpPlaceholder": "La configuración del servidor MCP aparecerá aquí",
"dashboard.overview": "Resumen",
"dashboard.posts": "Artículos",
"dashboard.media": "Medios",
"dashboard.templates": "Plantillas",
"dashboard.scripts": "Scripts",
"dashboard.drafts": "Borradores",
"dashboard.published": "Publicados",
"dashboard.entityCounts": "Recuento de entidades",
"dashboard.statusCounts": "Desglose por estado"
} }

View File

@@ -171,5 +171,74 @@
"sidebar.filter.tags": "Tags", "sidebar.filter.tags": "Tags",
"sidebar.filter.categories": "Catégories", "sidebar.filter.categories": "Catégories",
"sidebar.filter.calendar": "Archives", "sidebar.filter.calendar": "Archives",
"sidebar.filter.noResults": "Aucun résultat" "sidebar.filter.noResults": "Aucun résultat",
"editor.title": "Titre",
"editor.titlePlaceholder": "Saisir le titre...",
"editor.slug": "Slug",
"editor.slugPlaceholder": "saisir-slug",
"editor.content": "Contenu",
"editor.contentPlaceholder": "Rédigez votre contenu...",
"editor.excerpt": "Extrait",
"editor.excerptPlaceholder": "Bref résumé...",
"editor.author": "Auteur",
"editor.templateSlug": "Modèle",
"editor.doNotTranslate": "Ne pas traduire",
"editor.publish": "Publier",
"editor.validate": "Valider",
"editor.run": "Exécuter",
"editor.checkSyntax": "Vérifier la syntaxe",
"editor.kind": "Type",
"editor.enabled": "Activé",
"editor.entrypoint": "Point d'entrée",
"editor.alt": "Texte alternatif",
"editor.altPlaceholder": "Décrivez l'image...",
"editor.caption": "Légende",
"editor.metadata": "Métadonnées",
"editor.createdAt": "Créé",
"editor.updatedAt": "Mis à jour",
"tags.noTags": "Aucun tag",
"tags.editTag": "Modifier le tag",
"tags.name": "Nom",
"tags.color": "Couleur",
"tags.postTemplate": "Modèle d'article",
"tags.merge": "Fusionner",
"tags.mergeSource": "Tag source",
"tags.mergeTarget": "Tag cible",
"tags.selectTag": "Sélectionnez un tag à modifier",
"settings.projectName": "Nom du projet",
"settings.projectDescription": "Description",
"settings.dataPath": "Dossier de données",
"settings.browse": "Parcourir...",
"settings.reset": "Réinitialiser",
"settings.publicUrl": "URL publique",
"settings.defaultAuthor": "Auteur par défaut",
"settings.maxPostsPerPage": "Articles par page",
"settings.wrapLongLines": "Retour à la ligne automatique",
"settings.hideUnchangedRegions": "Masquer les régions inchangées",
"settings.offlineMode": "Mode avion",
"settings.systemPrompt": "Prompt système",
"settings.resetToDefault": "Rétablir les valeurs par défaut",
"settings.sshHost": "Hôte SSH",
"settings.sshUsername": "Nom d'utilisateur SSH",
"settings.sshRemotePath": "Chemin distant",
"settings.clear": "Effacer",
"settings.rebuildPosts": "Reconstruire les articles",
"settings.rebuildMedia": "Reconstruire les médias",
"settings.rebuildScripts": "Reconstruire les scripts",
"settings.rebuildTemplates": "Reconstruire les modèles",
"settings.rebuildLinks": "Reconstruire les liens",
"settings.regenerateThumbnails": "Régénérer les miniatures",
"settings.openDataFolder": "Ouvrir le dossier de données",
"settings.contentPlaceholder": "Les paramètres de contenu apparaîtront ici",
"settings.technologyPlaceholder": "Les paramètres technologiques apparaîtront ici",
"settings.mcpPlaceholder": "Les paramètres du serveur MCP apparaîtront ici",
"dashboard.overview": "Aperçu",
"dashboard.posts": "Articles",
"dashboard.media": "Médias",
"dashboard.templates": "Modèles",
"dashboard.scripts": "Scripts",
"dashboard.drafts": "Brouillons",
"dashboard.published": "Publiés",
"dashboard.entityCounts": "Nombre d'entités",
"dashboard.statusCounts": "Répartition par statut"
} }

View File

@@ -171,5 +171,74 @@
"sidebar.filter.tags": "Tag", "sidebar.filter.tags": "Tag",
"sidebar.filter.categories": "Categorie", "sidebar.filter.categories": "Categorie",
"sidebar.filter.calendar": "Archivio", "sidebar.filter.calendar": "Archivio",
"sidebar.filter.noResults": "Nessun risultato" "sidebar.filter.noResults": "Nessun risultato",
"editor.title": "Titolo",
"editor.titlePlaceholder": "Inserisci titolo...",
"editor.slug": "Slug",
"editor.slugPlaceholder": "inserisci-slug",
"editor.content": "Contenuto",
"editor.contentPlaceholder": "Scrivi il tuo contenuto...",
"editor.excerpt": "Estratto",
"editor.excerptPlaceholder": "Breve riassunto...",
"editor.author": "Autore",
"editor.templateSlug": "Modello",
"editor.doNotTranslate": "Non tradurre",
"editor.publish": "Pubblica",
"editor.validate": "Valida",
"editor.run": "Esegui",
"editor.checkSyntax": "Controlla sintassi",
"editor.kind": "Tipo",
"editor.enabled": "Abilitato",
"editor.entrypoint": "Punto di ingresso",
"editor.alt": "Testo alternativo",
"editor.altPlaceholder": "Descrivi l'immagine...",
"editor.caption": "Didascalia",
"editor.metadata": "Metadati",
"editor.createdAt": "Creato",
"editor.updatedAt": "Aggiornato",
"tags.noTags": "Nessun tag",
"tags.editTag": "Modifica tag",
"tags.name": "Nome",
"tags.color": "Colore",
"tags.postTemplate": "Modello articolo",
"tags.merge": "Unisci",
"tags.mergeSource": "Tag sorgente",
"tags.mergeTarget": "Tag destinazione",
"tags.selectTag": "Seleziona un tag da modificare",
"settings.projectName": "Nome progetto",
"settings.projectDescription": "Descrizione",
"settings.dataPath": "Cartella dati",
"settings.browse": "Sfoglia...",
"settings.reset": "Ripristina",
"settings.publicUrl": "URL pubblica",
"settings.defaultAuthor": "Autore predefinito",
"settings.maxPostsPerPage": "Articoli per pagina",
"settings.wrapLongLines": "A capo automatico",
"settings.hideUnchangedRegions": "Nascondi regioni invariate",
"settings.offlineMode": "Modalità aereo",
"settings.systemPrompt": "Prompt di sistema",
"settings.resetToDefault": "Ripristina predefiniti",
"settings.sshHost": "Host SSH",
"settings.sshUsername": "Nome utente SSH",
"settings.sshRemotePath": "Percorso remoto",
"settings.clear": "Cancella",
"settings.rebuildPosts": "Ricostruisci articoli",
"settings.rebuildMedia": "Ricostruisci media",
"settings.rebuildScripts": "Ricostruisci script",
"settings.rebuildTemplates": "Ricostruisci modelli",
"settings.rebuildLinks": "Ricostruisci link",
"settings.regenerateThumbnails": "Rigenera miniature",
"settings.openDataFolder": "Apri cartella dati",
"settings.contentPlaceholder": "Le impostazioni del contenuto appariranno qui",
"settings.technologyPlaceholder": "Le impostazioni tecnologiche appariranno qui",
"settings.mcpPlaceholder": "Le impostazioni del server MCP appariranno qui",
"dashboard.overview": "Panoramica",
"dashboard.posts": "Articoli",
"dashboard.media": "Media",
"dashboard.templates": "Modelli",
"dashboard.scripts": "Script",
"dashboard.drafts": "Bozze",
"dashboard.published": "Pubblicati",
"dashboard.entityCounts": "Conteggio entità",
"dashboard.statusCounts": "Ripartizione per stato"
} }