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

@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
@@ -19,7 +20,17 @@ use crate::state::sidebar_filter::{
};
use crate::state::tabs::{self, Tab, TabType};
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
@@ -112,6 +123,21 @@ pub enum Message {
RunMetadataDiff,
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,
InitMenuBar,
}
@@ -185,6 +211,16 @@ pub struct BdsApp {
// Modal
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"),
toasts: Vec::new(),
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,
)
@@ -362,6 +406,8 @@ impl BdsApp {
let idx = tabs::open_tab(&mut self.tabs, tab);
if let Some(t) = self.tabs.get(idx) {
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.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::InitMenuBar => {
#[cfg(target_os = "macos")]
@@ -913,6 +1169,13 @@ impl BdsApp {
&self.toasts,
self.active_modal.as_ref(),
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::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 components;
pub mod i18n;
pub mod platform;
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 welcome;
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 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::tabs::{Tab, TabType};
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.
fn content_bg(_theme: &Theme) -> container::Style {
@@ -31,7 +41,7 @@ fn drag_handle_style(_theme: &Theme) -> container::Style {
}
/// 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))
.width(Length::Fill)
.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))),
..container::Style::default()
})
.into()
}
/// Compose the full workspace layout.
pub fn view(
pub fn view<'a>(
// Navigation
sidebar_view: SidebarView,
sidebar_visible: bool,
sidebar_width: f32,
// Tabs
tabs: &[Tab],
active_tab: Option<&str>,
tabs: &'a [Tab],
active_tab: Option<&'a str>,
// Panel
panel_visible: bool,
panel_tab: PanelTab,
task_snapshots: &[TaskSnapshot],
output_entries: &[OutputEntry],
task_snapshots: &'a [TaskSnapshot],
output_entries: &'a [OutputEntry],
// Sidebar data
sidebar_posts: &[Post],
sidebar_media: &[Media],
sidebar_scripts: &[Script],
sidebar_templates: &[Template],
sidebar_posts: &'a [Post],
sidebar_media: &'a [Media],
sidebar_scripts: &'a [Script],
sidebar_templates: &'a [Template],
// Sidebar filters
post_filter: &PostFilter,
media_filter: &MediaFilter,
post_filter: &'a PostFilter,
media_filter: &'a MediaFilter,
// Status bar
active_project_name: Option<&str>,
projects: &[Project],
active_project_id: Option<&str>,
active_project_name: Option<&'a str>,
projects: &'a [Project],
active_project_id: Option<&'a str>,
post_count: usize,
media_count: usize,
offline_mode: bool,
locale_dropdown_open: bool,
project_dropdown_open: bool,
theme_badge: &str,
theme_badge: &'a str,
// i18n
locale: UiLocale,
// Toasts
toasts: &[Toast],
toasts: &'a [Toast],
// Modal
active_modal: Option<&modal::ModalState>,
active_modal: Option<&'a modal::ModalState>,
// Data directory (for thumbnail paths)
data_dir: Option<&Path>,
) -> Element<'static, Message> {
data_dir: Option<&'a Path>,
// 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)
let activity = activity_bar::view(sidebar_view, sidebar_visible, locale);
// Tab bar
let tabs_el = tab_bar::view(tabs, active_tab, locale);
// Content area
let content_area = welcome::view(locale);
// Content area — route based on active tab type
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
let mut right_col = column![tabs_el, content_area];
@@ -163,14 +186,14 @@ pub fn view(
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)
.height(Length::Fill)
.into();
// Overlay: either locale dropdown or project dropdown (mutually exclusive)
let overlay: Option<Element<'static, Message>> = if locale_dropdown_open {
let items: Vec<Element<'static, Message>> = UiLocale::all()
let overlay: Option<Element<'a, Message>> = if locale_dropdown_open {
let items: Vec<Element<'a, Message>> = UiLocale::all()
.iter()
.map(|&l| {
let flag_text = text(l.flag_emoji())
@@ -236,7 +259,7 @@ pub fn view(
};
// 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) {
overlays.push(toast_overlay);
@@ -262,3 +285,83 @@ pub fn view(
.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()
}