From 2e75cea60db8cb091679368a2224a84f36f0c04d Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Thu, 3 Dec 2026 20:00:25 +0800 Subject: [PATCH] feat(xiaoyi): wire the three-stage creation wizard --- .../crates/ui-egui/src/jiansun/creation.rs | 1183 ++++++++++++----- .../ui-egui/src/jiansun/creation_reads.rs | 10 + .../ui-egui/src/jiansun/creation_wizard.rs | 321 ++--- .../src/jiansun/workspace_navigation.rs | 17 +- 4 files changed, 1019 insertions(+), 512 deletions(-) diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs index b4dacebd..78d76b9b 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs @@ -11,6 +11,25 @@ const PICKER_ROW_HEIGHT: f32 = 36.0; const MATERIAL_THUMB_SIDE: f32 = 32.0; const REFERENCE_DROP_HINT: &str = "请将图片拖入素材上传框内"; +use super::creation_reads::wizard::{self, CreationStage, WizardFooterOutcome, WizardFooterState}; + +const WIZARD_WIDTH: f32 = 800.0; + +fn wizard_column(ui: &mut Ui, draw: impl FnOnce(&mut Ui)) { + let width = ui.available_width().min(WIZARD_WIDTH); + let inset = (ui.available_width() - width) / 2.0; + let gap = ui.spacing().item_spacing.x; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + ui.add_space(inset); + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.x = gap; + ui.set_width(width); + draw(ui); + }); + }); +} + fn rect_value(rect: egui::Rect) -> Value { json!([rect.min.x, rect.min.y, rect.width(), rect.height()]) } @@ -97,50 +116,45 @@ fn structure_preview_card( status: Option<&str>, ) { let t = Tokens::get(ui.ctx()).agent(); - stitch_ui::surface(ui, stitch_ui::SurfaceRole::Task, |ui| { - ui.horizontal_top(|ui| { - ui.spacing_mut().item_spacing.x = space::MD; - let thumb_size = vec2(72.0, 98.0); - let (area, _) = ui.allocate_exact_size(thumb_size, egui::Sense::hover()); - ui.painter().rect_filled(area, radius::ROW, t.dock); - ui.painter().rect_stroke(area, radius::ROW, egui::Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); - if let Some(texture) = cover { - let size = preview_size(texture.size_vec2(), area.shrink(2.0).size()); - let rect = egui::Align2::CENTER_CENTER.align_size_within_rect(size, area); - ui.painter().image(texture.id(), rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text); - } else if let Some(preview) = preview { - paint_template_structure(ui, preview, area.shrink(2.0)); - } else { - crate::icons::paint(ui, area, "layers", icon::LG, t.text_dim); + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = space::MD; + let thumb_size = vec2(72.0, 98.0); + let (area, _) = ui.allocate_exact_size(thumb_size, egui::Sense::hover()); + ui.painter().rect_filled(area, radius::ROW, t.dock); + ui.painter().rect_stroke(area, radius::ROW, egui::Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); + if let Some(texture) = cover { + let size = preview_size(texture.size_vec2(), area.shrink(2.0).size()); + let rect = egui::Align2::CENTER_CENTER.align_size_within_rect(size, area); + ui.painter().image(texture.id(), rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text); + } else if let Some(preview) = preview { + paint_template_structure(ui, preview, area.shrink(2.0)); + } else { + crate::icons::paint(ui, area, "layers", icon::LG, t.text_dim); + } + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = space::XS; + ui.add(egui::Label::new(egui::RichText::new(name).font(Type::Body.semibold()).color(t.text)).wrap()); + let mut facts = Vec::new(); + if let Some(count) = screen_count { + facts.push(format!("{count} 屏")); + } + if canvas_width > 0 { + facts.push(format!("{canvas_width} px")); + } + if !version.is_empty() { + facts.push(version.to_owned()); + } + if let Some(status) = status { + facts.push(status.to_owned()); + } + if !facts.is_empty() { + stitch_kit::label(ui, facts.join(" · "), Type::Meta, Tone::Quiet); + } + if cover.is_some() { + stitch_kit::caption(ui, "模板原稿预览"); + } else if preview.is_some() { + stitch_kit::caption(ui, "首屏结构示意"); } - ui.vertical(|ui| { - ui.spacing_mut().item_spacing.y = space::XS; - ui.add(egui::Label::new(egui::RichText::new(name).font(Type::Body.semibold()).color(t.text)).wrap()); - let mut facts = Vec::new(); - if let Some(count) = screen_count { - facts.push(format!("{count} 屏")); - } - if canvas_width > 0 { - facts.push(format!("{canvas_width} px")); - } - if !version.is_empty() { - facts.push(version.to_owned()); - } - if let Some(status) = status { - facts.push(status.to_owned()); - } - if !facts.is_empty() { - stitch_kit::label(ui, facts.join(" · "), Type::Meta, Tone::Quiet); - } - let caption = if cover.is_some() { - "模板原稿预览" - } else if preview.is_some() { - "首屏结构示意 · 含文字与图位版式" - } else { - "模板版本随本项目保存" - }; - stitch_kit::caption(ui, caption); - }); }); }); } @@ -161,7 +175,20 @@ fn reference_image_path(path: &std::path::Path) -> bool { .is_some_and(|ext| ["png", "jpg", "jpeg", "webp"].iter().any(|allowed| ext.eq_ignore_ascii_case(allowed))) } -/// Keep product reference drops in the current document and use the same bounded import as the picker. +fn reference_folder_paths(folder: &std::path::Path) -> Result, String> { + let mut paths = Vec::new(); + for entry in std::fs::read_dir(folder).map_err(|_| "无法读取所选文件夹")? { + let path = entry.map_err(|_| "无法读取所选文件夹")?.path(); + if path.is_file() && reference_image_path(&path) { + if paths.len() == 8 { return Err("文件夹内图片超过 8 张,请改用文件选择".into()); } + paths.push(path.into_os_string().into_string().map_err(|_| "文件名无效")?); + } + } + if paths.is_empty() { return Err("文件夹里没有 PNG、JPG 或 WebP 图片".into()); } + paths.sort(); + Ok(paths) +} + impl PhotocraftApp { pub(crate) fn creation_reference_drop( &mut self, ctx: &egui::Context, files: &[egui::DroppedFileHandle], at: Option, @@ -188,7 +215,7 @@ impl PhotocraftApp { || target["layer"].as_u64() == Some(layer.id.value()))) }); let Some(target) = target else { - if files.iter().any(|file| file.path().extension().and_then(|ext| ext.to_str()) + if files.iter().any(|file| file.path().is_dir() || file.path().extension().and_then(|ext| ext.to_str()) .is_some_and(|ext| photocraft_codecs::from_extension(ext).is_some() || ext.eq_ignore_ascii_case("svg"))) { w.creation_reads.reference_import_error = REFERENCE_DROP_HINT.into(); @@ -197,7 +224,7 @@ impl PhotocraftApp { return false; }; let slot = target["slot"].clone(); - let reject = if w.creation_doc != doc || w.busy.is_some() { + let reject = if (!staged && w.creation_doc != doc) || w.busy.is_some() { Some("请等待当前操作完成,再添加参考图") } else if w.unknown { Some("原请求结果待核查,请先核查后再添加参考图") @@ -212,14 +239,21 @@ impl PhotocraftApp { w.creation_reads.reference_import_error = error.into(); return true; } - let paths = files.iter().map(|file| { + let paths = if slot.is_null() && matches!(files, [file] if file.path().is_dir()) { + reference_folder_paths(files[0].path()) + } else { + files.iter().map(|file| { let path = file.path(); let valid = path.is_absolute() && reference_image_path(path); valid.then(|| path.to_str().map(str::to_owned)).flatten() - }).collect::>>(); - let Some(paths) = paths else { - w.creation_reads.reference_import_error = "请选择 PNG、JPG 或 WebP 格式的本机图片".into(); - return true; + }).collect::>>().ok_or_else(|| "请选择 PNG、JPG 或 WebP 格式的本机图片".to_owned()) + }; + let paths = match paths { + Ok(paths) => paths, + Err(error) => { + w.creation_reads.reference_import_error = error; + return true; + } }; if let Err(error) = self.import_reference_paths(paths, slot) && let Some(w) = self.jiansun.as_mut() @@ -1055,7 +1089,7 @@ fn form_editor_with_error( stitch_ui::halo_field(ui, editor.with("halo"), error, reduced, |ui| ui.add(field).accessible_name(name)) } -fn creation_editor_id(ui: &Ui, id: impl std::hash::Hash + std::fmt::Debug) -> egui::Id { +pub(super) fn creation_editor_id(ui: &Ui, id: impl std::hash::Hash + std::fmt::Debug) -> egui::Id { let editor = egui::Id::unique("creation-field").with(id).with("editor"); ui.data_mut(|data| data.get_temp_mut_or_default::>(egui::Id::unique("creation-active-editors")).push(editor)); editor @@ -1304,6 +1338,9 @@ fn image_slot(template: &Value, field: &Value, barcode: Option<&str>) -> Value { fn current_image_slot(brief: &Value, slot: &Value) -> bool { let intake = &brief["intake"]; let barcode = slot["barcode"].as_str(); + if slot["scope"] == "barcode" { + return barcode.is_some_and(|barcode| project_barcodes(brief).any(|code| code == barcode)); + } let scope = if barcode.is_some() { "barcodeFields" } else { "productFields" }; barcode.is_none_or(|barcode| project_barcodes(brief).any(|code| code == barcode)) && intake["schema"][scope].as_array().into_iter().flatten().any(|field| @@ -1311,8 +1348,8 @@ fn current_image_slot(brief: &Value, slot: &Value) -> bool { } fn in_image_slot(image: &Value, slot: &Value) -> bool { - image["fieldKey"] == slot["fieldKey"] && image["templateId"] == slot["templateId"] - && image["barcode"] == slot["barcode"] + image["barcode"] == slot["barcode"] + && (slot["scope"] == "barcode" || (image["fieldKey"] == slot["fieldKey"] && image["templateId"] == slot["templateId"])) } fn uses_template_images(brief: &Value) -> bool { @@ -1480,16 +1517,19 @@ fn set_intake(brief: &mut Value, template_id: &Value, schema: &Value) { if let Some(fields) = brief.as_object_mut() { fields.remove("intake"); } - } else if brief["intake"]["templateId"] != *template_id { + } else if brief["intake"]["templateId"] != *template_id || brief["intake"]["schema"]["version"] != 1 { brief["intake"] = json!({"templateId":template_id,"schema":schema,"productValues":{},"barcodeValues":{}}); fill_platform_intake(brief); assign_platform_images(brief); + } else { + wizard::refresh_intake_schema_from_catalog(brief, &json!({"id": template_id, "intake": schema})); } } const BARCODE_HINT: &str = "如 DNZ030516N717V01"; const BARCODE_SEPARATORS: [char; 7] = ['\r', '\n', ',', ',', '、', ';', ';']; +#[cfg(test)] fn barcode_editor(ui: &mut Ui, id: egui::Id, value: &mut String, width: f32, name: &str) -> egui::Response { let id = creation_editor_id(ui, id); use crate::theme::agent_scale::Type; @@ -1521,6 +1561,7 @@ fn project_barcodes(brief: &Value) -> impl Iterator { from_bindings.chain(from_normalized).filter(move |code| seen.insert(*code)) } +#[cfg(test)] fn barcode_issue(brief: &Value, text: &str) -> Option<&'static str> { let text = text.trim(); if text.is_empty() { @@ -1532,6 +1573,85 @@ fn barcode_issue(brief: &Value, text: &str) -> Option<&'static str> { } } +fn structured_barcode_field(field: &Value) -> bool { + match (field_key(field).as_str(), field_kind(field).as_str()) { + (Some("length" | "width" | "height"), Some("number")) => true, + (Some("colorName" | "material" | "boardType"), Some("text")) => true, + _ => false, + } +} + +fn write_legacy_barcode_fields(brief: &mut Value, rows: &mut [Value], schema: &Value) { + let mut variants = brief_variants(brief); + let mut bindings = serde_json::Map::new(); + let mut owners = std::collections::HashMap::new(); + for row in rows.iter() { + if let Some(owner) = non_empty_str(&row["variantId"]) { + *owners.entry(owner.to_owned()).or_insert(0) += 1; + } + } + for row in rows.iter_mut() { + let Some(code) = non_empty_str(&row["barcode"]).map(str::to_owned) else { continue; }; + let color = non_empty_str(&row["colorName"]); + let matching = variants.iter().find(|variant| color.is_some_and(|color| variant["colorName"] == color || variant["name"] == color)); + let current = variants.iter().position(|variant| variant["id"] == row["variantId"]); + row["variantId"] = if let Some(variant) = matching { + variant["id"].clone() + } else if let Some(index) = current + && let Some(color) = color + && non_empty_str(&variants[index]["colorMaterialId"]).is_none() + && row["variantId"].as_str().and_then(|id| owners.get(id)) == Some(&1) + { + variants[index]["name"] = json!(color); + variants[index]["colorName"] = json!(color); + variants[index]["id"].clone() + } else if let Some(color) = color && variants.len() < 64 { + let id = uuid::Uuid::new_v4().to_string(); + variants.push(json!({"id":id,"name":color,"colorName":color,"colorMaterialId":"","images":[]})); + json!(id) + } else { + current.and_then(|index| variants.get(index)).or_else(|| variants.first()) + .map_or(Value::Null, |variant| variant["id"].clone()) + }; + let owner = row["variantId"].as_str().unwrap_or("default"); + let codes = bindings.entry(owner.to_owned()).or_insert_with(|| json!([])); + codes.as_array_mut().expect("barcode list").push(json!(code)); + + for field in schema.as_array().into_iter().flatten().filter(|field| structured_barcode_field(field)) { + let key = field_key(field).as_str().unwrap(); + let value = if field_kind(field) == "number" { + let mm_factor = |unit: &Value| match unit.as_str() { Some("cm" | "厘米") => 10.0, Some("m" | "米") => 1000.0, _ => 1.0 }; + let ratio = mm_factor(&row["dimensions"]["unit"]) / mm_factor(&field["unit"]); + row["dimensions"][key].as_str().and_then(|text| text.parse::().ok()) + .and_then(|value| serde_json::Number::from_f64(value * ratio)).map_or(Value::Null, Value::Number) + } else { + row[key].clone() + }; + brief["intake"]["barcodeValues"][&code][key] = value; + } + } + if variants != brief_variants(brief) { set_brief_variants(brief, variants); } + brief["barcodeBindings"] = Value::Object(bindings); + update_detail_barcode(brief); + if let Some(row) = rows.iter().find(|row| row["barcode"] == brief["detailBarcode"]).or_else(|| rows.first()) { + brief["dimensions"] = row["dimensions"].clone(); + if let Some(color) = non_empty_str(&row["colorName"]) { + brief["colorName"] = json!(color); + } + } +} + +pub(super) fn wizard_barcode_editor(ui: &mut Ui, id: egui::Id, value: &mut String) -> egui::Response { + stitch_kit::caption(ui, "条码编码"); + let id = creation_editor_id(ui, id); + let reduced = ui.style().animation_time == 0.0; + stitch_ui::halo_field(ui, id.with("halo"), None, reduced, |ui| { + ui.add(stitch_ui::text_input(value, BARCODE_HINT, true).id(id).return_key(None) + .desired_rows(1).font(Type::Body.font_id()).frame(egui::Frame::NONE) + .margin(egui::Margin::ZERO).desired_width(ui.available_width())).accessible_name("条码编码") + }) +} + fn update_detail_barcode(brief: &mut Value) -> bool { let selected = brief["detailBarcode"].as_str(); let next = { @@ -1590,6 +1710,7 @@ fn section_heading(ui: &mut Ui, title: &str, description: &str) { } } +#[cfg(test)] fn brief_step(ui: &mut Ui, title: &str, ready: bool, previous_ready: bool) { let (status, tone) = if ready { ("已就绪", Tone::Success) } else if previous_ready { ("当前步骤", Tone::Active) } @@ -1695,6 +1816,15 @@ pub(super) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, val next_brief = remerged; } assign_platform_images(&mut next_brief); + if edited.contains("barcodeEntries") { + for field in ["barcodeEntries", "barcodeBindings", "variants", "detailBarcode"] { + if let Some(value) = w.creation_brief.get(field) { + next_brief[field] = value.clone(); + } + } + } else if let Some(brief) = next_brief.as_object_mut() { + brief.remove("barcodeEntries"); + } w.creation_brief = next_brief; w.creation_dirty = true; w.sync_dirty = true; @@ -1737,7 +1867,15 @@ pub(super) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, val w.creation_submitted_draft.take().filter(|sent| *sent != w.creation_draft()).map(|_| w.creation_draft()) } else { None }; let edited_plan = (w.creation_plan != w.creation["plan"]["screens"]).then(|| w.creation_plan.clone()); + let entries = w.creation_brief.get("barcodeEntries").cloned(); + let same_doc = w.creation_doc == value["doc"].as_u64(); w.creation = value["creation"].clone(); + if same_doc && w.creation["brief"].is_object() + && w.creation["brief"].get("barcodeEntries").is_none() + && let Some(entries) = entries + { + w.creation["brief"]["barcodeEntries"] = entries; + } w.creation_doc = value["doc"].as_u64(); let template_binding = w.template_binding(app.session.active().map(|state| state.doc.id.0)); w.template_ui.bind_project(&template_binding); @@ -1925,6 +2063,10 @@ impl Workspace { return; } if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + if self.creation_step == 0 && let Some((_, stage)) = self.creation_reads.wizard_stage { + self.handle_wizard_navigation(app, if stage == CreationStage::Source { WizardFooterOutcome::Cancel } else { WizardFooterOutcome::Back }); + return; + } self.retain_creation_ui_draft(app); let previous = match self.creation_step { 2 => 1, 1 => 0, _ => 3 }; self.set_creation_destination(previous); @@ -1937,6 +2079,11 @@ impl Workspace { format!("{}|{}|{:?}", self.account["id"], self.origin, doc) } pub(super) fn creation_draft(&self) -> Value { + if self.creation_reads.staged_new_project + && let Some(draft) = &self.creation_reads.staged_prior_draft + { + return draft.clone(); + } if self.creation_restore_draft.is_object() { return self.creation_restore_draft.clone(); } @@ -2083,8 +2230,16 @@ impl Workspace { }); if closed { self.sync_confirm = false; } } - pub(super) fn begin_staged_new_project(&mut self, _app: &PhotocraftApp) { + pub(super) fn begin_staged_new_project(&mut self, app: &PhotocraftApp) { + self.retain_creation_ui_draft(app); + if !self.creation_reads.staged_new_project { + self.creation_reads.staged_prior_draft = app.session.active().map(|state| { + if self.creation_doc == Some(state.doc.id.0) { self.creation_draft() } else { Value::Null } + }); + } + self.creation_restore_draft = Value::Null; self.creation_reads.staged_new_project = true; + self.creation_reads.wizard_stage = None; self.library = false; self.material = false; self.creation_open = true; @@ -2129,10 +2284,25 @@ impl Workspace { self.creation_doc = doc_id; self.reference_intro_doc = doc_id; self.creation_reads.staged_new_project = false; + self.creation_reads.staged_prior_draft = None; + if let Some((_, stage)) = self.creation_reads.wizard_stage { + self.creation_reads.wizard_stage = Some((self.creation_field_scope(app), stage)); + } Ok(()) } pub(super) fn focus_brief_field(&mut self, field_key: &str, message: &str) { + if let Some((scope, stage)) = self.creation_reads.wizard_stage { + let template = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); + let stage = if matches!(field_key, "brand" | "category" | "template") || !template_identity(&template) { + CreationStage::Template + } else if stage != CreationStage::Details { + CreationStage::Details + } else { + stage + }; + self.creation_reads.wizard_stage = Some((scope, stage)); + } self.creation_reads.inline_errors.insert(field_key.to_owned(), message.to_owned()); self.creation_reads.scroll_to_field = Some(field_key.to_owned()); if let Some(rest) = field_key.strip_prefix("intake-barcode:") @@ -2170,6 +2340,8 @@ impl Workspace { return Err("请等待当前操作完成".into()); } self.creation_reads.staged_new_project = false; + self.creation_reads.staged_prior_draft = None; + self.creation_reads.wizard_stage = None; app.run("file.new", json!({"name":"未命名详情页","width":1440,"height":1800}))?; self.reference_intro_doc = app.session.active().map(|state| state.doc.id.0); self.creation_open = true; @@ -2193,7 +2365,10 @@ impl Workspace { { return Err("原请求结果待核查,不会重发".into()); } - if self.creation_reads.staged_new_project && app.session.active().is_none() { + if self.creation_reads.staged_new_project { + if input["doc"].as_u64().is_some() { + return Err("新建资料尚未关联画布".into()); + } self.ensure_creation_document(app)?; } let st = app.session.active().ok_or("请先新建项目")?; @@ -2303,9 +2478,9 @@ impl Workspace { ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { let t = Tokens::get(ui.ctx()).agent(); let doc = app.session.active().map(|s| s.doc.id.0); - let staged = self.creation_reads.staged_new_project && doc.is_none(); + let staged = self.creation_reads.staged_new_project; let avail_rect = ui.available_rect_before_wrap(); - ui.painter().rect_filled(avail_rect, 0.0, if self.creation_step == 0 { t.field } else { t.dock }); + ui.painter().rect_filled(avail_rect, 0.0, if self.creation_step == 0 { t.canvas } else { t.dock }); let pad_x: i8 = if avail_rect.width() >= 840.0 { 24 } else if avail_rect.width() >= 520.0 { 16 } else { 12 }; if !staged && self.creation_doc != doc { @@ -2377,40 +2552,7 @@ impl Workspace { } if self.creation_step == 0 { - let pending_id = egui::Id::unique(("creation-barcode-pending", self.creation_field_scope(app))); - let barcode_pending = ui.data(|d| d.get_temp::(pending_id)).unwrap_or(false); - let max_width = 920.0_f32; - egui::Panel::bottom("creation-sticky-footer") - .resizable(false) - .show_separator_line(true) - .frame(egui::Frame::NONE.fill(t.dock).inner_margin(egui::Margin::symmetric(pad_x, 10))) - .show(ui, |ui| { - let content_width = ui.available_width().min(max_width); - let inset = ((ui.available_width() - content_width) * 0.5).max(0.0); - ui.horizontal(|ui| { - ui.add_space(inset); - ui.vertical(|ui| { - ui.set_width(content_width.max(160.0)); - self.brief_footer_ui(app, ui, barcode_pending); - }); - }); - }); - let scrolled = egui::ScrollArea::vertical().id_salt("creation-body").auto_shrink([false, false]).show(ui, |ui| { - egui::Frame::NONE.inner_margin(egui::Margin::symmetric(pad_x, 16)).show(ui, |ui| { - let content_width = ui.available_width().min(max_width); - let inset = ((ui.available_width() - content_width) * 0.5).max(0.0); - ui.horizontal(|ui| { - ui.add_space(inset); - ui.vertical(|ui| { - ui.set_width(content_width.max(160.0)); - self.creation_notices_ui(app, ui); - let pending = self.brief_scroll_body_ui(app, ui); - ui.data_mut(|d| d.insert_temp(pending_id, pending)); - }); - }); - }); - }); - self.control_geometry("product-form-viewport", scrolled.inner_rect.intersect(ui.clip_rect())); + self.creation_wizard_ui(app, ui, pad_x); } else { egui::ScrollArea::vertical().id_salt("creation-body").auto_shrink([false, false]).show(ui, |ui| { egui::Frame::NONE.inner_margin(egui::Margin::symmetric(pad_x, 20)).show(ui, |ui| { @@ -2435,6 +2577,283 @@ impl Workspace { }); } + fn creation_wizard_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, pad_x: i8) { + let scope = self.creation_field_scope(app); + let selected = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); + let has_template = template_identity(&selected); + let mut stage = self.creation_reads.wizard_stage + .filter(|(owner, _)| *owner == scope) + .map(|(_, stage)| stage) + .unwrap_or_else(|| wizard::resolve_initial_stage(self.creation_reads.staged_new_project, has_template)); + if wizard::ensure_default_barcode(&mut self.creation_brief) { + wizard::migrate_legacy_top_dimensions_to_barcode(&mut self.creation_brief); + } + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(pad_x, 12)).show(ui, |ui| { + wizard_column(ui, |ui| { + wizard::wizard_stepper_ui(ui, &mut stage, true, has_template, self.reduce_motion); + stitch_ui::divider(ui); + }); + }); + self.creation_reads.wizard_stage = Some((scope, stage)); + + let pending_id = scope.with("wizard-barcode-pending"); + let barcode_pending = ui.data(|data| data.get_temp::(pending_id)).unwrap_or(false); + let background = Tokens::get(ui.ctx()).agent().dock; + egui::Panel::bottom("creation-sticky-footer") + .resizable(false) + .show_separator_line(true) + .frame(egui::Frame::NONE.fill(background).inner_margin(egui::Margin::symmetric(pad_x, 10))) + .show(ui, |ui| wizard_column(ui, |ui| { + if stage == CreationStage::Details { + self.brief_footer_ui(app, ui, barcode_pending); + } else { + self.reference_drop_warning_ui(ui); + if let Some((message, _, action)) = self.brief_setup_warning() { + let configure = stitch_ui::action_button(ui, action, stitch_ui::ButtonRole::Quiet, true).on_hover_text(message); + self.control_geometry(if self.key_saved { "select-model" } else { "configure-personal-key" }, configure.rect); + if configure.clicked() { + self.open_brief_setup_settings(); + } + } + let action = wizard::wizard_footer_ui(ui, WizardFooterState { + stage, + can_continue: form_editable(self.busy.as_deref(), self.unknown) + && (stage == CreationStage::Source || has_template), + can_enter_canvas: false, + can_start: false, + }, true, |_, _| {}); + self.handle_wizard_navigation(app, action); + } + })); + if !self.editing_product_brief() || self.creation_step != 0 { + return; + } + let (scope, stage) = self.creation_reads.wizard_stage.unwrap_or((scope, stage)); + let opacity = wizard::stage_reveal_opacity(ui.ctx(), scope.with("wizard-reveal"), stage, self.reduce_motion); + ui.spacing_mut().scroll.floating = true; + let scrolled = egui::ScrollArea::vertical().id_salt((scope, stage)).auto_shrink([false, false]).show(ui, |ui| { + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(pad_x, 12)).show(ui, |ui| { + wizard_column(ui, |ui| { + ui.multiply_opacity(opacity); + let title = ui.label(egui::RichText::new(stage.title()).font(Type::TitleLg.semibold()).color(Tokens::get(ui.ctx()).agent().text)); + self.control_geometry("brief-title", title.rect); + ui.add_space(space::SM); + self.creation_notices_ui(app, ui); + let editable = form_editable(self.busy.as_deref(), self.unknown && !self.scoped_production_pending()); + ui.add_enabled_ui(editable, |ui| { + let width = ui.available_width(); + match stage { + CreationStage::Source => self.wizard_source_ui(app, ui, scope, width), + CreationStage::Template => { + let np = normalized_product_summary(&self.creation_brief); + self.unmatched_platform_taxonomy_chips_ui(app, ui, &np); + self.template_and_brand_block_ui(app, ui, width); + } + CreationStage::Details => { + let pending = self.wizard_details_ui(app, ui, scope, width, editable); + ui.data_mut(|data| data.insert_temp(pending_id, pending)); + } + } + }); + }); + }); + }); + self.control_geometry("product-form-viewport", scrolled.inner_rect.intersect(ui.clip_rect())); + } + + fn handle_wizard_navigation(&mut self, app: &PhotocraftApp, action: WizardFooterOutcome) { + let Some((scope, stage)) = self.creation_reads.wizard_stage else { return }; + let next = match (stage, action) { + (_, WizardFooterOutcome::Cancel) => { + self.retain_creation_ui_draft(app); + if self.creation_reads.staged_new_project { + self.creation_reads.staged_new_project = false; + self.creation_restore_draft = self.creation_reads.staged_prior_draft.take().unwrap_or(Value::Null); + self.show_center(super::CenterView::Projects, app.session.active().is_some()); + self.creation_open = false; + } else { + self.set_creation_destination(3); + self.creation_open = false; + } + return; + } + (CreationStage::Source, WizardFooterOutcome::Next) | (CreationStage::Details, WizardFooterOutcome::Back) => CreationStage::Template, + (CreationStage::Template, WizardFooterOutcome::Next) => CreationStage::Details, + (CreationStage::Template, WizardFooterOutcome::Back) => CreationStage::Source, + _ => return, + }; + self.creation_reads.wizard_stage = Some((scope, next)); + } + + fn reference_drop_warning_ui(&mut self, ui: &mut Ui) { + if self.creation_reads.reference_import_error == REFERENCE_DROP_HINT { + let status = stitch_ui::status_label(ui, REFERENCE_DROP_HINT, stitch_ui::StatusTone::Warning); + self.control_geometry("reference-import-error", status.rect); + } + } + + fn wizard_source_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32) { + self.source_picker(ui); + ui.add_space(space::MD); + match self.creation_brief["source"].as_str() { + Some("product_platform") => { + let np = normalized_product_summary(&self.creation_brief); + self.platform_spu_ui(app, ui, scope, width, np.has_platform_data); + if np.has_platform_data { + stitch_kit::label(ui, format!("已同步 {} 张素材", selected_visual_asset_count(&self.creation_brief)), Type::Meta, Tone::Success); + } + if !self.creation_reads.platform_sync_note.is_empty() { + stitch_kit::label(ui, &self.creation_reads.platform_sync_note, Type::Meta, Tone::Quiet); + } + } + Some("library") => { + self.product_search_button(app, ui); + self.product_select_results(app, ui); + } + _ => { + wizard::section_heading_with_tip(ui, "本机资料", "支持 PNG、JPG、WebP。每次最多 8 张,单张不超过 20 MB。"); + ui.add_space(space::XS); + let rect = self.reference_picker(app, ui, width, scope.with("source-drop"), + Some(("拖入产品图片或文件夹", "拖入图片或文件夹,或点击浏览文件")), Value::Null); + self.control_geometry("reference-add", rect); + if ui.is_enabled() && let Some(target) = self.reference_drop_geometry(app, ui, rect) { + self.creation_view_geometry["referenceDrop"] = target; + } + if stitch_ui::action_button(ui, "选择文件夹", stitch_ui::ButtonRole::Quiet, true).clicked() { + self.open_reference_dialog(app, Value::Null, true); + } + let count = self.creation_brief["images"].as_array().map_or(0, Vec::len); + if count > 0 { + stitch_kit::label(ui, format!("已添加 {count} 张图片"), Type::Meta, Tone::Success); + } + if !self.creation_reads.reference_import_error.is_empty() && self.creation_reads.reference_import_error != REFERENCE_DROP_HINT { + stitch_ui::status_label(ui, &self.creation_reads.reference_import_error, stitch_ui::StatusTone::Error); + } + brief_section_break(ui); + wizard::section_heading_with_tip(ui, "文字简报(选填)", "可填写产品用途、需要呈现的卖点和制作要求。"); + ui.add_space(space::XS); + if edit_named(ui, (scope, "source-note"), &mut self.creation_brief["note"], width, true, + "输入产品说明或制作要求", "文字简报") + { + self.creation_reads.manual_edited_fields.insert("note".into()); + self.creation_dirty = true; + } + } + } + } + + fn wizard_barcode_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32) -> bool { + let seeded = wizard::ensure_default_barcode(&mut self.creation_brief); + if seeded { + wizard::migrate_legacy_top_dimensions_to_barcode(&mut self.creation_brief); + } + let previous = self.creation_brief["barcodeEntries"].as_array().cloned().unwrap_or_default(); + let mut rows = previous.clone(); + let schema = self.creation_brief["intake"]["schema"]["barcodeFields"].clone(); + let fields = schema.as_array().into_iter().flatten() + .filter(|field| field_kind(field) != "image" && !structured_barcode_field(field)) + .collect::>(); + let images = schema.as_array().into_iter().flatten().filter(|field| field_kind(field) == "image").collect::>(); + + let hint = |key| schema.as_array().into_iter().flatten() + .find(|field| structured_barcode_field(field) && field_key(field) == key).map(intake_hint).unwrap_or(""); + let action = wizard::barcode_cards_section_ui(ui, scope, &mut rows, self.reduce_motion, hint, |ui, id, row| { + let Some(code) = non_empty_str(&row["barcode"]) else { + stitch_ui::action_button(ui, "添加图片", stitch_ui::ButtonRole::Secondary, false) + .on_disabled_hover_text("先填写条码编码"); + return; + }; + if !project_barcodes(&self.creation_brief).any(|existing| existing == code) { return; } + self.barcode_intake_ui(app, ui, id, width, code, &fields, &images); + if images.is_empty() { + self.image_slot_control_ui(app, ui, width, "图片", "拖入或选择条码图片", + json!({"scope":"barcode","barcode":code,"purpose":"product","multiple":true})); + } + }); + if let Some(index) = action.remove_index { + rows.remove(index); + } + if action.add_barcode || rows.is_empty() { + rows.push(wizard::barcode_row("", &Value::Null, &Value::Null, &Value::Null)); + } + if action.changed { + for old in &previous { + let Some(code) = non_empty_str(&old["barcode"]) else { continue; }; + let new = rows.iter().find(|row| row["id"] == old["id"]).and_then(|row| non_empty_str(&row["barcode"])); + if new != Some(code) { + replace_barcode(&mut self.creation_brief, code, new); + if let Some(new) = new + && let Some(assets) = self.creation_brief.get_mut("normalizedProduct").and_then(|value| value.get_mut("assets")).and_then(Value::as_array_mut) + { + for asset in assets.iter_mut().filter(|asset| asset["barcode"] == code) { + asset["barcode"] = json!(new); + } + } + if let Some(variants) = self.creation_brief.get_mut("normalizedProduct").and_then(|value| value.get_mut("variants")).and_then(Value::as_array_mut) { + for variant in variants { + if let Some(barcodes) = variant["barcodes"].as_array_mut() { + if let Some(new) = new { + for row in barcodes.iter_mut().filter(|row| row["barcode"] == code) { + row["barcode"] = json!(new); + } + } else { + barcodes.retain(|row| row["barcode"] != code); + } + } + } + } + } + } + write_legacy_barcode_fields(&mut self.creation_brief, &mut rows, &schema); + self.creation_reads.manual_edited_fields.insert("barcodeEntries".into()); + self.creation_reads.manual_edited_fields.insert("barcodeBindings".into()); + self.creation_reads.manual_edited_fields.insert("dimensions".into()); + self.creation_dirty = true; + } + if self.creation_brief.get("barcodeEntries").is_some() { + let images = &self.creation_brief["images"]; + for row in &mut rows { + if let Some(code) = non_empty_str(&row["barcode"]) + && let Some(images) = images.as_array() + { + row["images"] = json!(images.iter().filter(|image| image["barcode"] == code).collect::>()); + } + } + if self.creation_brief["barcodeEntries"] != Value::Array(rows.clone()) { + self.creation_brief["barcodeEntries"] = Value::Array(rows); + } + } + let codes: Vec = project_barcodes(&self.creation_brief).map(str::to_owned).collect(); + if codes.len() > 1 { + ui.add_space(space::SM); + self.detail_barcode_selector_ui(ui, width, scope, &codes); + } + action.pending + } + + fn wizard_details_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32, editable: bool) -> bool { + self.core_identity_and_specs_ui(app, ui, scope, width); + brief_section_break(ui); + let pending = self.wizard_barcode_ui(app, ui, scope, width); + brief_section_break(ui); + self.references_ui(app, ui, width); + brief_section_break(ui); + wizard::section_heading_with_tip(ui, "制作设置", "选择要制作的成品和适用的花色。"); + self.output_tags_ui(ui); + stitch_ui::disclosure(ui, scope.with("wizard-output-colors"), "成品花色范围", false, self.reduce_motion, |ui| { + self.material_select(app, ui, width.min(420.0)); + self.sku_colors_bar_ui(ui, width, scope); + }); + self.special_requirements_ui(ui, scope); + if self.template_workflow["canvasFirst"] != true { + let doc = app.session.active().map(|state| state.doc.id.0); + let id = egui::Id::unique(("production-refinement", self.local_identity(""), doc)); + let _ = self.refinement_ui(ui, Some((id, editable))); + } + self.advanced_export_settings_ui(app, ui, scope, width, editable); + pending + } + fn creation_notices_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { if !self.error.is_empty() { super::operation_error::details(ui, egui::Id::unique("creation-operation-error"), &self.error, self.reduce_motion, None); @@ -2475,6 +2894,7 @@ impl Workspace { stitch_kit::label(ui, text, Type::Meta, tone); } + #[cfg(test)] fn brief_scroll_body_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) -> bool { let editable = form_editable(self.busy.as_deref(), self.unknown && !self.scoped_production_pending()); let t = Tokens::get(ui.ctx()).agent(); @@ -2499,6 +2919,7 @@ impl Workspace { ui.add_enabled_ui(editable, |ui| self.brief_content_ui(app, ui)).inner } + #[cfg(test)] fn brief_content_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) -> bool { let field_scope = self.creation_field_scope(app); let width = ui.available_width(); @@ -2543,6 +2964,7 @@ impl Workspace { barcode_pending } + #[cfg(test)] fn source_import_strip_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, field_scope: egui::Id, width: f32) { let t = Tokens::get(ui.ctx()).agent(); let np = normalized_product_summary(&self.creation_brief); @@ -2680,10 +3102,11 @@ impl Workspace { } fn core_identity_and_specs_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, field_scope: egui::Id, width: f32) { + #[cfg(test)] let dynamic = self.creation_brief["intake"]["schema"]["version"] == 1; let platform = self.creation_brief["source"] == "product_platform"; let gap = space::MD; - let show_spu_here = !platform; + let show_spu_here = !platform || self.creation_reads.wizard_stage.is_some(); // Row 1: Product Name + SPU (2 columns >= 560px, 1 column narrow) if show_spu_here && width >= 560.0 { @@ -2702,7 +3125,8 @@ impl Workspace { } } - stitch_ui::morph_surface(ui, field_scope.with("dimensions-reveal"), !dynamic, self.reduce_motion, |ui| { + #[cfg(test)] + stitch_ui::morph_surface(ui, field_scope.with("dimensions-reveal"), !dynamic && self.creation_reads.wizard_stage.is_none(), self.reduce_motion, |ui| { ui.add_space(space::SM); self.dimensions_row_ui(ui, field_scope, width); }); @@ -2819,6 +3243,7 @@ impl Workspace { }); } + #[cfg(test)] fn dimensions_row_ui(&mut self, ui: &mut Ui, field_scope: egui::Id, width: f32) { let row_width = width.min(580.0); field_group(ui, row_width, "产品尺寸(长 × 宽 × 高)", |ui| { @@ -2936,6 +3361,7 @@ impl Workspace { }); } + #[cfg(test)] fn sku_matrix_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, field_scope: egui::Id, width: f32) -> bool { let dynamic = self.creation_brief["intake"]["schema"]["version"] == 1; let platform = self.creation_brief["source"] == "product_platform"; @@ -3070,6 +3496,7 @@ impl Workspace { self.control_geometry("special-requirements", group.response.rect); } + #[cfg(test)] fn barcode_cards_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, scope: egui::Id) -> bool { let t = Tokens::get(ui.ctx()).agent(); let fields = self.creation_brief["intake"]["schema"]["barcodeFields"].clone(); @@ -3404,6 +3831,7 @@ impl Workspace { }); } + #[cfg(test)] fn barcode_entry_ui(&mut self, ui: &mut Ui, width: f32, scope: egui::Id, id: &str, label: &str, codes: &mut Vec) -> (bool, bool) { let draft_id = scope.with("new-barcode"); let mut draft = ui.data(|data| data.get_temp::(draft_id)); @@ -3477,6 +3905,7 @@ impl Workspace { } } + #[cfg(test)] fn brief_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { let barcode_pending = self.brief_scroll_body_ui(app, ui); ui.add_space(space::MD); @@ -3532,10 +3961,10 @@ impl Workspace { let names: Vec<&str> = missing_items.iter().map(|i| i.label.as_str()).collect(); Some(format!("待补齐:{}", names.join("、"))) } else { - setup_warning.map(|(message, _, _)| message.to_owned()) + None }; - // Row 1: Clickable readiness checklist OR concise pre-launch summary + Model pill + // Readiness and settings stay directly actionable. let mut clicked_missing: Option<(String, String)> = None; let hint_row = ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = space::SM; @@ -3590,20 +4019,14 @@ impl Workspace { self.control_geometry("entry-hint", hint_row.response.rect); if let Some((key, msg)) = clicked_missing { self.focus_brief_field(&key, &msg); + } - if let Some((message, _, _)) = setup_warning { - stitch_kit::label(ui, message, Type::Meta, Tone::Warning); - } - if self.creation_reads.reference_import_error == REFERENCE_DROP_HINT { - let status = stitch_ui::status_label(ui, REFERENCE_DROP_HINT, stitch_ui::StatusTone::Warning); - self.control_geometry("reference-import-error", status.rect); - } + self.reference_drop_warning_ui(ui); ui.add_space(space::XS); - // Row 2: Live autosave indicator (left) + Clear CTA hierarchy (right) let actions_ready = self.busy.is_none() && !self.unknown && !barcode_pending; let canvas_ready = actions_ready && missing_items.is_empty() && missing.is_empty(); - let production_ready = blocked.is_none(); + let production_ready = blocked.is_none() && setup_warning.is_none(); let refinement = if new_project { let doc = app.session.active().map(|state| state.doc.id.0); let id = egui::Id::unique(("production-refinement", self.local_identity(""), doc)); @@ -3611,20 +4034,46 @@ impl Workspace { } else { None }; - ui.horizontal_wrapped(|ui| { + if self.creation_reads.wizard_stage.is_some() { self.brief_autosave_status_ui(ui); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.spacing_mut().item_spacing.x = space::SM; - if self.has_production_stages() || self.has_paused_production() { - let resume = stitch_ui::action_button(ui, "继续整套制作", stitch_ui::ButtonRole::Primary, self.can_resume_product()); - self.control_geometry("resume-product", resume.rect); - if resume.clicked() { - self.resume_product_production(app); - } + let resume = self.has_production_stages() || self.has_paused_production(); + let action = wizard::wizard_footer_ui(ui, WizardFooterState { + stage: CreationStage::Details, + can_continue: resume, + can_enter_canvas: canvas_ready, + can_start: if resume { self.can_resume_product() } else { production_ready }, + }, new_project || resume, |action, response| { + match action { + WizardFooterOutcome::EnterCanvas => self.control_geometry("enter-canvas", response.rect), + WizardFooterOutcome::Start => self.control_geometry(if resume { "resume-product" } else { "start-product" }, response.rect), + _ => {} } - self.brief_enter_button(app, ui, &template, production_ready, canvas_ready, refinement); }); - }); + match action { + WizardFooterOutcome::Start if resume => self.resume_product_production(app), + WizardFooterOutcome::Start | WizardFooterOutcome::EnterCanvas => { + self.enter_creation_canvas(app, &template, action == WizardFooterOutcome::Start, refinement); + } + _ => self.handle_wizard_navigation(app, action), + } + } + #[cfg(test)] + if self.creation_reads.wizard_stage.is_none() { + ui.horizontal_wrapped(|ui| { + self.brief_autosave_status_ui(ui); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = space::SM; + if self.has_production_stages() || self.has_paused_production() { + let resume = stitch_ui::action_button(ui, "继续整套制作", stitch_ui::ButtonRole::Primary, self.can_resume_product()); + self.control_geometry("resume-product", resume.rect); + if resume.clicked() { + self.resume_product_production(app); + } + } + self.brief_enter_button(app, ui, &template, production_ready, canvas_ready, refinement); + }); + }); + } } fn sku_colors_bar_ui(&mut self, ui: &mut Ui, width: f32, scope: egui::Id) { @@ -3818,13 +4267,13 @@ impl Workspace { let files = &input.raw.hovered_files; !files.is_empty() && files.len() <= 8 && files.iter().all(|file| { if let Some(path) = &file.path { - reference_image_path(path) + reference_image_path(path) || (slot.is_null() && files.len() == 1 && path.is_dir()) } else { matches!(file.mime.as_str(), "image/png" | "image/jpeg" | "image/webp") } }) }); - let enabled = self.busy.is_none() && !self.unknown; + let enabled = ui.is_enabled() && self.busy.is_none() && !self.unknown; let drop_pointer = if supported && enabled { let to_local = ui.ctx().layer_transform_from_global(ui.layer_id()).unwrap_or_default(); app.services.cursor_pos.as_mut().and_then(|cursor| cursor(ui.ctx())) @@ -3840,42 +4289,52 @@ impl Workspace { .on_hover_text("支持 PNG、JPG、WebP;每次最多 8 张,单张不超过 20 MB"); if slot.is_null() { self.control_geometry("reference-add", add_reference.rect); } if enabled && add_reference.clicked() { - let id = app.session.active().map(|s| s.doc.id.0); - let staged = self.creation_reads.staged_new_project; - let account = self.account["id"].clone(); - let origin = self.origin.clone(); - let result = app.ask_file( - crate::FileDialogRequest::Open { - multiple: slot["multiple"] != false, - initial_dir: None, - extensions: Some(vec!["png".into(), "jpg".into(), "jpeg".into(), "webp".into()]), - }, - move |app, answer| { - if app.session.active().map(|s| s.doc.id.0) != id || app.jiansun.as_ref().is_none_or(|w| { - w.account["id"] != account || w.origin != origin || (w.creation_doc != id && !staged) || !w.creation_open || w.creation_step != 0 - }) { - return Err("账号或项目已切换,未导入到其他项目".into()); - } - match answer { - crate::FileDialogAnswer::Paths(paths) => { - if let Err(error) = app.import_reference_paths(paths, slot) - && let Some(w) = app.jiansun.as_mut() - { - w.creation_reads.reference_import_error = error; - } - Ok(Value::Null) - }, - _ => Err("请选择本机产品图片".into()), - } - }, - ); - if let Err(e) = result { - self.creation_reads.reference_import_error = e; - } + self.open_reference_dialog(app, slot, false); } add_reference.rect } + fn open_reference_dialog(&mut self, app: &mut PhotocraftApp, slot: Value, folder: bool) { + let id = app.session.active().map(|s| s.doc.id.0); + let staged = self.creation_reads.staged_new_project; + let stage = self.creation_reads.wizard_stage; + let account = self.account["id"].clone(); + let origin = self.origin.clone(); + let request = if folder { + crate::FileDialogRequest::Folder { initial_dir: None } + } else { + crate::FileDialogRequest::Open { + multiple: slot["multiple"] != false, + initial_dir: None, + extensions: Some(vec!["png".into(), "jpg".into(), "jpeg".into(), "webp".into()]), + } + }; + let result = app.ask_file(request, move |app, answer| { + if app.session.active().map(|s| s.doc.id.0) != id || app.jiansun.as_ref().is_none_or(|w| { + w.account["id"] != account || w.origin != origin || (w.creation_doc != id && !staged) + || w.creation_reads.staged_new_project != staged || w.creation_reads.wizard_stage != stage + || !w.creation_open || w.creation_step != 0 || w.library || w.material + }) { + return Err("账号或项目已切换,未导入到其他项目".into()); + } + let paths = match answer { + crate::FileDialogAnswer::Paths(paths) => Ok(paths), + crate::FileDialogAnswer::FolderTo(path) => reference_folder_paths(std::path::Path::new(&path)), + _ => Err("请选择本机产品图片".into()), + }; + if let Err(error) = paths.and_then(|paths| app.import_reference_paths(paths, slot)) + && let Some(w) = app.jiansun.as_mut() + { + w.creation_reads.reference_import_error = error; + } + Ok(Value::Null) + }); + if let Err(error) = result { + self.creation_reads.reference_import_error = error; + } + } + + #[cfg(test)] fn brief_enter_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, template: &Value, production_ready: bool, canvas_ready: bool, refinement: Option) { let whole_allowed = self.template_workflow["canvasFirst"] != true; // Right-to-left parent places Primary on the far right, Secondary beside it. @@ -3892,25 +4351,29 @@ impl Workspace { ); self.control_geometry("enter-canvas", enter.rect); if enter.clicked() || generate { - if let Err(error) = self.ensure_creation_document(app) { - self.error = error; - return; - } - let mut brief = self.creation_brief.clone(); - update_detail_barcode(&mut brief); - let variants = brief_variants(&brief); - set_brief_variants(&mut brief, variants); - brief["templateSelection"] = template.clone(); - if let Err(error) = self.slot_action(app, "slot-skeleton", json!({ - "brief": brief, - "template": template, - "outputId": "detail", - "generateProduct": generate, - "deliveryDir": self.creation_delivery_dir, - "refinement": refinement, - })) { - self.error = error; - } + self.enter_creation_canvas(app, template, generate, refinement); + } + } + + fn enter_creation_canvas(&mut self, app: &mut PhotocraftApp, template: &Value, generate: bool, refinement: Option) { + if let Err(error) = self.ensure_creation_document(app) { + self.error = error; + return; + } + let mut brief = self.creation_brief.clone(); + update_detail_barcode(&mut brief); + let variants = brief_variants(&brief); + set_brief_variants(&mut brief, variants); + brief["templateSelection"] = template.clone(); + if let Err(error) = self.slot_action(app, "slot-skeleton", json!({ + "brief": brief, + "template": template, + "outputId": "detail", + "generateProduct": generate, + "deliveryDir": self.creation_delivery_dir, + "refinement": refinement, + })) { + self.error = error; } } @@ -3992,11 +4455,13 @@ impl Workspace { fn image_slot_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, field: &Value, barcode: Option<&str>) { let slot = image_slot(&self.creation_brief["intake"]["templateId"], field, barcode); - let label = intake_label(field); - stitch_kit::label(ui, &label, Type::Meta, Tone::Quiet); + self.image_slot_control_ui(app, ui, width, &intake_label(field), intake_hint(field), slot); + } + + fn image_slot_control_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, label: &str, placeholder: &str, slot: Value) { + stitch_kit::label(ui, label, Type::Meta, Tone::Quiet); let key = self.creation_field_scope(app).with(("reference-image-slot", slot.to_string())); - let placeholder = intake_hint(field); - let drop = self.reference_picker(app, ui, width, key, Some((&label, placeholder)), slot.clone()); + let drop = self.reference_picker(app, ui, width, key, Some((label, placeholder)), slot.clone()); if ui.is_enabled() && let Some(mut target) = self.reference_drop_geometry(app, ui, drop) { target["slot"] = slot.clone(); target["label"] = json!(label); @@ -4026,30 +4491,23 @@ impl Workspace { } fn source_picker(&mut self, ui: &mut Ui) { - let t = Tokens::get(ui.ctx()).agent(); - let mut choices = Vec::new(); - let label = egui::RichText::new("资料来源").font(Type::Meta.font_id()).color(t.text_dim); - let narrow = ui.available_width() < 360.0; - if narrow { ui.label(label.clone()); } - let source = ui.horizontal_wrapped(|ui| { - if !narrow { ui.label(label); } - let option_width = if narrow { (ui.available_width() - 2.0 * ui.spacing().item_spacing.x) / 3.0 } else { 92.0 }; - for (value, label) in [("upload", "手工录入"), ("product_platform", "产品平台"), ("library", "素材库产品")] { - let selected = self.creation_brief["source"] == value; - let response = stitch_ui::segmented_option_sized(ui, label, selected, true, vec2(option_width, 28.0)); - self.control_geometry(&format!("source-{value}"), response.rect); - choices.push(json!({"id":value,"label":label,"ready":true,"rect":rect_value(response.rect)})); - if response.clicked() && !selected { - self.creation_brief["source"] = json!(value); - self.creation_dirty = true; - } - } - }); - self.control_geometry("source", source.response.rect); - for choice in &mut choices { - choice["selected"] = json!(choice["id"] == self.creation_brief["source"]); + let choices = [("upload", "手工录入"), ("product_platform", "产品平台"), ("library", "素材库产品")]; + let options = choices.map(|(_, label)| (label, true)); + let selected = choices.iter().position(|(value, _)| self.creation_brief["source"] == *value).unwrap_or(0); + let rail = stitch_ui::segmented_control(ui, ui.scope_id().with("creation-source"), &options, selected, self.reduce_motion); + if let Some(index) = rail.selected && index != selected { + self.creation_brief["source"] = json!(choices[index].0); + self.creation_dirty = true; } - self.creation_view_geometry["sourceChoices"] = json!(choices); + let mut bounds = egui::Rect::NOTHING; + let mut geometry = Vec::new(); + for ((value, label), response) in choices.into_iter().zip(rail.responses) { + bounds = bounds.union(response.rect); + self.control_geometry(&format!("source-{value}"), response.rect); + geometry.push(json!({"id":value,"label":label,"ready":true,"selected":self.creation_brief["source"] == value,"rect":rect_value(response.rect)})); + } + self.control_geometry("source", bounds); + self.creation_view_geometry["sourceChoices"] = json!(geometry); self.creation_view_geometry["popups"]["source"] = json!({"open":false,"loading":false,"ready":true,"rect":null,"rows":[]}); } @@ -4074,7 +4532,13 @@ impl Workspace { self.creation_view_geometry["referenceDrop"] = target; } } else { - stitch_kit::caption(ui, "请在「商品档案与款式」中上传模板所需图片。"); + if self.creation_reads.wizard_stage.is_none() { + stitch_kit::caption(ui, "请在「商品档案与款式」中上传模板所需图片。"); + } else if !self.creation_reads.reference_import_error.is_empty() + && self.creation_reads.reference_import_error != REFERENCE_DROP_HINT + { + stitch_ui::status_label(ui, &self.creation_reads.reference_import_error, stitch_ui::StatusTone::Error); + } } } @@ -4216,7 +4680,7 @@ impl Workspace { } ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { let meta = if sub.is_empty() { kind_label.to_owned() } else { format!("{kind_label} · {sub}") }; - ui.add(egui::Label::new(egui::RichText::new(meta).font(Type::Caption.font_id()).color(t.text_dim)).truncate()); + ui.add(egui::Label::new(egui::RichText::new(meta).font(Type::Meta.font_id()).color(t.text_dim)).truncate()); }); }); }); @@ -4570,6 +5034,13 @@ impl Workspace { use base64::Engine as _; let component = result["id"].as_str().unwrap_or(""); let choice = &result["choice"]; + if ui.is_enabled() && template_identity(choice) && choice["intake"]["version"] == 1 + && choice["id"] == self.creation_brief["templateSelection"]["id"] + && choice["version"] == self.creation_brief["templateSelection"]["version"] + && choice["contentHash"] == self.creation_brief["templateSelection"]["contentHash"] + { + self.creation_dirty |= wizard::refresh_intake_schema_from_catalog(&mut self.creation_brief, choice); + } if ui.is_enabled() && self.creation_brief["templateSelection"].is_null() && template_identity(choice) @@ -4677,7 +5148,8 @@ impl Workspace { { self.catalog(app, "templates", String::new()); } - let side_by_side = width >= 620.0 && template_identity(&selected); + let has_preview = selected_row.and_then(|row| verified_structure_preview(row, &selected, &brand, &category)).is_some(); + let side_by_side = width >= 620.0 && has_preview; let picker_width = if side_by_side { (width - 280.0 - space::MD).max(240.0) } else { width }; let mut geometry = Vec::new(); let draw_picker = |this: &mut Workspace, app: &mut PhotocraftApp, ui: &mut Ui, p_width: f32, geometry: &mut Vec| { @@ -4707,6 +5179,8 @@ impl Workspace { if item.clicked() && !fixed { if !is_selected { set_intake(&mut this.creation_brief, &row["id"], &row["intake"]); + } else { + wizard::refresh_intake_schema_from_catalog(&mut this.creation_brief, row); } this.creation_brief["templateSelection"] = choice; this.creation_reads.inline_errors.remove("template"); @@ -4791,13 +5265,12 @@ impl Workspace { } else { draw_picker(self, app, ui, picker_width, &mut geometry); let chosen = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); - if template_identity(&chosen) { + if let Some(preview) = rows.iter().find_map(|row| verified_structure_preview(row, &chosen, &brand, &category)) { ui.add_space(space::XS); - let preview = rows.iter().find_map(|row| verified_structure_preview(row, &chosen, &brand, &category)); let card = ui.scope(|ui| { structure_preview_card( ui, - preview, + Some(preview), None, name, version_label, @@ -5349,11 +5822,12 @@ mod tests { fn creation_escape_closes_popup_then_editor_then_view_without_losing_draft() { let (mut w, mut app, requests) = brief_fixture(); w.creation_open = true; + w.library = false; + w.material = false; w.creation_step = 0; w.creation_dirty = true; w.creation_brief["images"] = json!([]); w.creation_brief["variants"] = json!([]); - let before = w.creation_brief.clone(); let ctx = egui::Context::default(); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events| { @@ -5366,6 +5840,7 @@ mod tests { }; let key = |pressed| egui::Event::Key { key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed, repeat:false, modifiers:egui::Modifiers::NONE }; frame(&mut w,&mut app,vec![]); + let before = w.creation_brief.clone(); let editor = egui::Id::unique("creation-field").with((w.creation_field_scope(&app),"name")).with("editor"); ctx.memory_mut(|memory| memory.request_focus(editor)); frame(&mut w,&mut app,vec![]); @@ -5379,6 +5854,12 @@ mod tests { assert_eq!(w.creation_step,0); frame(&mut w,&mut app,vec![key(false)]); assert!(!frame(&mut w,&mut app,vec![key(true)])); + assert_eq!(w.creation_reads.wizard_stage.unwrap().1, CreationStage::Template); + frame(&mut w,&mut app,vec![key(false)]); + assert!(!frame(&mut w,&mut app,vec![key(true)])); + assert_eq!(w.creation_reads.wizard_stage.unwrap().1, CreationStage::Source); + frame(&mut w,&mut app,vec![key(false)]); + assert!(!frame(&mut w,&mut app,vec![key(true)])); assert_eq!(w.creation_step,3); assert!(w.creation_dirty); assert_eq!(w.creation_brief,before); @@ -7040,40 +7521,47 @@ mod tests { let (mut w, mut app, requests) = brief_fixture(); let original = w.creation_brief.clone(); let ctx = egui::Context::default(); + w.creation_open = true; + w.library = false; + w.material = false; for (window_width, dock_width) in [(1535.0, 519.0), (1100.0, 360.0), (850.0, 360.0)] { - let mut central = egui::Rect::NOTHING; - for _ in 0..2 { - let mut output = ctx.run_ui( - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(window_width, 1032.0))), ..Default::default() }, - |ui| { - ui.horizontal(|ui| { - ui.allocate_ui_with_layout( - vec2(window_width - dock_width - ui.spacing().item_spacing.x, 1032.0), - egui::Layout::left_to_right(egui::Align::Min), - |ui| { - central = ui.available_rect_before_wrap(); - w.creation_ui(&mut app, ui); - }, - ); - ui.allocate_exact_size(vec2(dock_width, 1032.0), egui::Sense::hover()); - }); - }, - ); - output.textures_delta.clear(); + for (stage, controls) in [ + (CreationStage::Source, &["source", "reference-add"][..]), + (CreationStage::Template, &["brand", "category", "template"][..]), + (CreationStage::Details, &["name", "identifier", "reference-0", "reference-1", "enter-canvas"][..]), + ] { + w.creation_reads.wizard_stage = Some((w.creation_field_scope(&app), stage)); + let mut central = egui::Rect::NOTHING; + for _ in 0..2 { + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(window_width, 1032.0))), ..Default::default() }, + |ui| { + ui.horizontal(|ui| { + ui.allocate_ui_with_layout( + vec2(window_width - dock_width - ui.spacing().item_spacing.x, 1032.0), + egui::Layout::left_to_right(egui::Align::Min), + |ui| { + central = ui.available_rect_before_wrap(); + w.creation_ui(&mut app, ui); + }, + ); + ui.allocate_exact_size(vec2(dock_width, 1032.0), egui::Sense::hover()); + }); + }, + ); + output.textures_delta.clear(); + } + for name in controls { + let rect = control_rect(&w, name); + assert!( + rect.left() >= central.left() && rect.right() <= central.right(), + "{name} escaped the real horizontal workspace at {window_width}px: {rect:?}, central {central:?}" + ); + } } - for name in - ["source", "name", "brand", "category", "dimensions", "identifier", "material", "reference-0", "reference-1", "template", "enter-canvas"] - { - let rect = control_rect(&w, name); - assert!( - rect.left() >= central.left() && rect.right() <= central.right(), - "{name} escaped the real horizontal workspace at {window_width}px: {rect:?}, central {central:?}" - ); + for (key, value) in original.as_object().unwrap() { + assert_eq!(&w.creation_brief[key], value, "{key}"); } - assert!(control_rect(&w, "source").bottom() < control_rect(&w, "name").top(), "the first fields follow the source section vertically"); - assert!(control_rect(&w, "material").top() > control_rect(&w, "name").bottom()); - assert!(control_rect(&w, "template").bottom() < control_rect(&w, "reference-0").top(), "template selection precedes the material references"); - assert_eq!(w.creation_brief, original); } assert!(requests.try_recv().is_err()); } @@ -7118,8 +7606,11 @@ mod tests { assert_eq!(w.creation_view_geometry["sourceChoices"][0]["selected"], true); assert_eq!(w.creation_view_geometry["sourceChoices"][1]["selected"], false); assert_eq!(w.creation_view_geometry["popups"]["source"]["open"], false); - assert!(control_rect(&w, "source-upload").width() >= 92.0); - assert!(control_rect(&w, "source-library").width() >= 92.0); + let rail = control_rect(&w, "source"); + for control in ["source-upload", "source-product_platform", "source-library"] { + let segment = control_rect(&w, control); + assert!(rail.contains_rect(segment) && segment.height() >= control::MENU_ROW); + } let library = control_rect(&w, "source-library").center(); brief_frame(&mut w, &mut app, &ctx, 850.0, click_events(library)); expected["source"] = json!("library"); @@ -7836,8 +8327,7 @@ mod tests { w.image_ready = true; h.run_steps(4); assert!(h.query_by_label("选择模型").is_none()); - assert!(h.query_by_label("个人 Key 未连接").is_some()); - assert_eq!(h.query_all_by_label("尚未连接个人 Key,请先配置个人 Key").count(), 2); + assert_eq!(h.query_all_by_label("配置个人 Key").count(), 2); let footer = control_rect(h.state().jiansun.as_ref().unwrap(), "configure-personal-key"); h.query_all_by_label("配置个人 Key") .find(|button| footer.contains(button.rect().center()) == from_footer).unwrap().click(); @@ -7882,6 +8372,47 @@ mod tests { } } + #[test] + fn staged_import_uses_a_new_document_and_preserves_the_active_draft() { + let (mut w, mut app, requests) = brief_fixture(); + let old_doc = app.session.active().unwrap().doc.id.0; + let old_draft = w.creation_draft(); + w.begin_staged_new_project(&app); + w.creation_brief["note"] = json!("新项目简报"); + assert_eq!(w.creation_draft(), old_draft); + assert_eq!(app.session.documents().len(), 1); + w.creation_action(&mut app, "creation-import", json!({"paths":["D:/references/new.png"]})).unwrap(); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected reference import") }; + assert_eq!(method, "creation-import"); + assert_ne!(input["doc"], old_doc); + assert_eq!(input["brief"]["note"], "新项目简报"); + assert_eq!(app.session.documents().len(), 2); + assert_eq!(app.session.documents()[0].doc.id.0, old_doc); + } + + #[test] + fn structured_barcode_save_sends_entries_and_legacy_template_values() { + let (mut w, mut app, requests) = brief_fixture(); + let schema = json!([{"id":"length","type":"number","unit":"mm"},{"id":"material","type":"text"}]); + w.creation_brief["intake"] = json!({"schema":{"version":1,"barcodeFields":schema},"productValues":{"origin":"佛山"},"barcodeValues":{}}); + let mut rows = vec![wizard::barcode_row("0007", &json!("oak"), &json!("原木色"), &Value::Null)]; + rows[0]["dimensions"] = json!({"length":"180","width":"85","height":"75","unit":"cm"}); + rows[0]["material"] = json!("白蜡木"); + write_legacy_barcode_fields(&mut w.creation_brief, &mut rows, &schema); + w.creation_brief["barcodeEntries"] = json!(rows); + w.creation_action(&mut app, "creation-save", json!({})).unwrap(); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected brief save") }; + let brief = &input["brief"]; + assert_eq!(method, "creation-save"); + assert_eq!(brief["barcodeEntries"][0]["barcode"], "0007"); + assert_eq!(brief["barcodeBindings"]["oak"], json!(["0007"])); + assert_eq!(brief["detailBarcode"], "0007"); + assert_eq!(brief["dimensions"], brief["barcodeEntries"][0]["dimensions"]); + assert_eq!(brief["intake"]["barcodeValues"]["0007"]["length"].as_f64(), Some(1800.0)); + assert_eq!(brief["intake"]["barcodeValues"]["0007"]["material"], "白蜡木"); + assert_eq!(brief["intake"]["productValues"]["origin"], "佛山"); + } + #[test] fn staged_new_project_defers_document_creation_until_entering_canvas() { let (tx, requests) = mpsc::channel(); @@ -7890,7 +8421,7 @@ mod tests { w.busy = None; w.account = json!({"id":"qa"}); w.origin = "http://localhost:3138".into(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); w.begin_staged_new_project(&app); assert!(app.session.documents().is_empty(), "starting a new project must not eagerly spawn an empty canvas tab"); @@ -7906,13 +8437,28 @@ mod tests { w.creation_brief["templateSelection"] = json!({ "id":"tpl","name":"标准模板","version":"1.0","contentHash":"a".repeat(64),"brandId":"brand","categoryId":"cat" }); - let ctx = egui::Context::default(); + use egui_kittest::kittest::Queryable; w.reduce_motion = true; - for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 900.0, vec![]); } - assert!(app.session.documents().is_empty(), "editing staged brief keeps session clean"); - - let enter = control_rect(&w, "enter-canvas").center(); - brief_frame(&mut w, &mut app, &ctx, 900.0, click_events(enter)); + let mut harness = egui_kittest::Harness::builder() + .with_size(vec2(900.0, 900.0)) + .with_context_setup(|ctx| { + PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(ctx); + }) + .build_ui_state(|ui, state: &mut (Workspace, PhotocraftApp)| { + egui::CentralPanel::default().frame(egui::Frame::NONE) + .show(ui, |ui| state.0.creation_ui(&mut state.1, ui)); + }, (w, app)); + harness.run_steps(3); + assert!(harness.state().1.session.documents().is_empty(), "editing staged brief keeps session clean"); + for (button, stage) in [("下一步:选择模板", CreationStage::Template), ("下一步:填写产品资料", CreationStage::Details)] { + harness.get_by_label(button).click(); + harness.run_steps(3); + assert_eq!(harness.state().0.creation_reads.wizard_stage.unwrap().1, stage); + } + harness.get_by_label("进入模板画布").click(); + harness.run(); + let (w, app) = harness.state(); assert_eq!(app.session.documents().len(), 1, "entering canvas materializes the document"); assert!(!w.creation_reads.staged_new_project); assert!(requests.try_iter().any(|r| matches!(r, Request::Save(_, _, _)))); @@ -7972,110 +8518,53 @@ mod tests { } #[test] - #[ignore = "offscreen GPU T5B visual acceptance; requires PHOTOCRAFT_AGENT_QA_OUT"] - fn t5b_creation_workspace_visual_acceptance() { + #[ignore = "Vulkan wizard visual inspection; requires PHOTOCRAFT_AGENT_QA_OUT"] + fn creation_wizard_visual_acceptance() { let _gpu = photocraft_testkit::gpu_lock(); - let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); + let directory = std::path::PathBuf::from(std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory")); std::fs::create_dir_all(&directory).unwrap(); - let setup_ctx = |ctx: &egui::Context| { - PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); - crate::cjk_fonts::install_system_provider_for_tests(ctx); - }; - - let render_case = |filename: &str, width: f32, height: f32, ppp: f32, show_copilot: bool, mut w: Workspace, app: PhotocraftApp| { - w.reduce_motion = true; - w.creation_open = true; - w.creation_step = 0; - w.library = false; - w.material = false; - let mut h = egui_kittest::Harness::builder() - .with_size(vec2(width, height)) - .with_pixels_per_point(ppp) - .with_context_setup(setup_ctx) - .wgpu() - .build_ui_state( - move |ui, state: &mut Box<(Workspace, PhotocraftApp)>| { - let (w, app) = &mut **state; - if show_copilot { - let dock_w = (width * 0.27).clamp(320.0, 380.0); - egui::Panel::right("qa-brief-copilot") - .resizable(false) - .exact_size(dock_w) + for (width, height) in [(1440.0, 900.0), (960.0, 720.0)] { + for (name, stage) in [("source", CreationStage::Source), ("template", CreationStage::Template), ("details", CreationStage::Details)] { + let (mut w, app, requests) = brief_fixture(); + w.reduce_motion = true; + w.creation_open = true; + w.creation_step = 0; + w.library = false; + w.material = false; + w.key_saved = false; + w.creation_brief["dimensions"] = json!({"length":"1800","width":"850","height":"750","unit":"mm"}); + if stage == CreationStage::Source { + w.creation_brief = empty_brief(); + } else if stage == CreationStage::Details { + w.creation_brief["barcodeBindings"]["oak"] = json!(["DNZ030516N717V01"]); + w.creation_brief["identifier"] = json!("DNZ030516"); + } + w.creation_reads.wizard_stage = Some((w.creation_field_scope(&app), stage)); + let mut setup = eframe::egui_wgpu::WgpuSetupCreateNew::without_display_handle(); + setup.instance_descriptor.backends = eframe::wgpu::Backends::VULKAN; + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(width, height)) + .with_context_setup(|ctx| { + PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(ctx); + }) + .wgpu_setup(eframe::egui_wgpu::WgpuSetup::CreateNew(setup)) + .build_ui_state( + |ui, state: &mut Box<(Workspace, PhotocraftApp)>| { + let (w, app) = &mut **state; + egui::Panel::right("qa-brief-copilot").resizable(false).exact_size(330.0) .frame(egui::Frame::NONE.fill(Tokens::get(ui.ctx()).agent().dock)) - .show(ui, |ui| { - stitch_ui::scope(ui, |ui| w.brief_copilot_header_ui(app, ui)); - }); - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| { - w.creation_ui(app, ui); - }); - } else { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| { - w.creation_ui(app, ui); - }); - } - }, - Box::new((w, app)), - ); - h.run_steps(4); - h.render().unwrap().save(std::path::Path::new(&directory).join(filename)).unwrap(); - }; - - // 1. Empty staged new project @ 1440x900 - { - let (tx, _) = mpsc::channel(); - let (_, rx) = mpsc::channel(); - let mut w = Workspace::new(tx, rx); - w.busy = None; - w.account = json!({"id":"qa"}); - w.creation_catalog.insert("brands".into(), vec![json!({"id":"b1","name":"原木生活家","ready":true})]); - w.creation_catalog.insert("materials".into(), vec![]); - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - w.begin_staged_new_project(&app); - render_case("t5b-empty-1440x900.png", 1440.0, 900.0, 1.0, true, w, app); - } - - // 2. Normalized multi-color Platform SPU + right-dock copilot @ 1440x900 - { - let (w, app, _) = normalized_product_fixture(); - render_case("t5b-platform-spu-1440x900.png", 1440.0, 900.0, 1.0, true, w, app); - } - - // 3. Normalized multi-color Platform SPU @ 1280x800 - { - let (w, app, _) = normalized_product_fixture(); - render_case("t5b-platform-spu-1280x800.png", 1280.0, 800.0, 1.0, true, w, app); - } - - // 4. Scaled 150% DPI @ 960x600 logical - { - let (w, app, _) = normalized_product_fixture(); - render_case("t5b-dpi150-960x600.png", 960.0, 600.0, 1.5, false, w, app); - } - - // 5. Inline error state + unmatched platformBrand + model-unready @ 1280x800 - { - let (mut w, app, _) = normalized_product_fixture(); - w.creation_brief["name"] = json!(""); - w.creation_brief["brandId"] = json!(""); - w.creation_brief["brandName"] = json!(""); - w.creation_brief["templateSelection"] = Value::Null; - w.model_ready = false; - w.image_ready = false; - w.creation_reads.inline_errors.insert("name".into(), "请输入产品名称".into()); - w.creation_reads.inline_errors.insert("brand".into(), "请选择品牌".into()); - render_case("t5b-inline-errors-1280x800.png", 1280.0, 800.0, 1.0, true, w, app); - } - - // 6. Narrow pane @ 420x1600 - { - let (w, app, _) = normalized_product_fixture(); - render_case("t5b-narrow-420x1600.png", 420.0, 1600.0, 1.0, false, w, app); - } - - // 7. Full scroll-free overview of all 4 blocks + sticky footer @ 960x2200 - { - let (w, app, _) = normalized_product_fixture(); - render_case("t5b-full-blocks-960x2200.png", 960.0, 2200.0, 1.0, false, w, app); + .show(ui, |ui| stitch_ui::scope(ui, |ui| w.brief_copilot_header_ui(app, ui))); + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| w.creation_ui(app, ui)); + }, + Box::new((w, app)), + ); + h.run_steps(4); + let image = h.render().unwrap(); + assert_eq!(image.dimensions(), (width as u32, height as u32)); + image.save(directory.join(format!("wizard-{name}-{width}x{height}.png"))).unwrap(); + drop(requests); + } } } } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs index adeb4244..947dc991 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs @@ -50,6 +50,8 @@ pub(super) struct UiState { pub(super) resource_query: String, pub(super) resource_image: Option<(String, egui::TextureHandle)>, pub(super) staged_new_project: bool, + pub(super) staged_prior_draft: Option, + pub(super) wizard_stage: Option<(egui::Id, wizard::CreationStage)>, pub(super) inline_errors: HashMap, pub(super) scroll_to_field: Option, pub(super) manual_edited_fields: HashSet, @@ -444,6 +446,14 @@ impl Workspace { self.creation_read_failed(pending.request, error, value["readError"] == "queue_busy"); } else if self.creation_reads.desired.get(kind(&pending.request)) == Some(&pending.request.signature) { if let Some(items) = value["catalog"]["items"].as_array() { + if kind(&pending.request) == "templates" { + let selected = &self.creation_brief["templateSelection"]; + if let Some(row) = items.iter().find(|row| row["id"] == selected["id"] + && row["version"] == selected["version"] && row["contentHash"] == selected["contentHash"]) + { + self.creation_dirty |= wizard::refresh_intake_schema_from_catalog(&mut self.creation_brief, row); + } + } self.creation_catalog.insert(kind(&pending.request).into(), items.clone()); self.creation_reads.catalog_errors.remove(kind(&pending.request)); } else { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_wizard.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_wizard.rs index 92ff2476..4f852173 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_wizard.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_wizard.rs @@ -1,16 +1,16 @@ //! Components for the native product creation flow. The owner dispatches navigation, //! image imports and saves. -#![allow(dead_code, reason = "The creation flow wires these components in a separate change")] use std::collections::HashSet; use crate::jiansun::{stitch_kit, stitch_ui}; +#[cfg(test)] use crate::theme::Tokens; -use crate::theme::agent_scale::{Type, control, icon, motion, radius, space}; -use egui::{Id, Ui}; +use crate::theme::agent_scale::{Type, control, motion, space}; +use egui::{Id, Response, Ui}; use serde_json::{Value, json}; -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] pub(crate) enum CreationStage { Source, Template, @@ -21,46 +21,33 @@ pub(crate) fn resolve_initial_stage(new_project: bool, has_template: bool) -> Cr if !new_project && has_template { CreationStage::Details } else { CreationStage::Source } } +impl CreationStage { + pub(crate) fn title(self) -> &'static str { + match self { + Self::Source => "资料来源", + Self::Template => "选择模板", + Self::Details => "填写产品资料", + } + } +} + /// Only earlier, completed stages are navigable. Forward actions live in the footer. pub(crate) fn wizard_stepper_ui(ui: &mut Ui, current: &mut CreationStage, source_done: bool, template_done: bool, reduce_motion: bool) -> bool { + let stages = [CreationStage::Source, CreationStage::Template, CreationStage::Details]; let before = *current; - stitch_ui::scope_with_motion(ui, reduce_motion, |ui| { - ui.horizontal_wrapped(|ui| { - for (stage, label, done) in [ - (CreationStage::Source, "1. 资料来源", source_done), - (CreationStage::Template, "2. 选择模板", template_done), - (CreationStage::Details, "3. 填写产品资料", false), - ] { - let active = stage == before; - let enabled = done && stage < before; - let tokens = Tokens::get(ui.ctx()).agent(); - let ink = if active { tokens.primary_text } else { tokens.text_dim }; - let text = egui::RichText::new(label).font(Type::Title.font_id()).color(ink); - let button = - if done && !active { egui::Button::image_and_text(crate::icons::image("check", icon::SM, ink), text) } else { egui::Button::new(text) }; - let fill = if active { - tokens.primary_bg - } else if enabled { - tokens.card - } else { - egui::Color32::TRANSPARENT - }; - let response = ui.add_enabled( - active || enabled, - button - .fill(fill) - .corner_radius(radius::CHIP) - .sense(if active { egui::Sense::hover() } else { egui::Sense::click() }) - .min_size(egui::vec2(0.0, control::DEFAULT)), - ); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, enabled && ui.is_enabled(), active, label)); - stitch_ui::focus_ring(ui, &response, radius::CHIP, stitch_ui::FocusRing::Control); - if response.clicked() { - *current = stage; - } - } - }); - }); + let options = [ + ("1. 资料来源", source_done), + ("2. 选择模板", before == CreationStage::Template || (template_done && before == CreationStage::Details)), + ("3. 填写产品资料", before == CreationStage::Details), + ]; + let id = ui.scope_id().with("creation-steps"); + let rail = ui.scope(|ui| { + ui.visuals_mut().disabled_alpha = 0.8; + stitch_ui::segmented_control(ui, id, &options, before as usize, reduce_motion) + }).inner; + if let Some(index) = rail.selected && stages[index] < before { + *current = stages[index]; + } *current != before } @@ -90,7 +77,7 @@ pub(crate) fn stage_reveal_opacity(ctx: &egui::Context, id: Id, stage: CreationS /// Keep the help available from the small icon by pointer or keyboard focus. pub(crate) fn section_heading_with_tip(ui: &mut Ui, title: &str, tip: &str) { ui.horizontal_wrapped(|ui| { - stitch_kit::section_heading(ui, title); + stitch_kit::label(ui, title, Type::Body, super::super::stitch_state::Tone::Active); if !tip.is_empty() { let response = crate::icons::agent_icon_button(ui, "info", control::STANDARD, false, "").accessible_name("查看说明"); if response.has_focus() && !response.hovered() { @@ -104,9 +91,9 @@ pub(crate) fn section_heading_with_tip(ui: &mut Ui, title: &str, tip: &str) { }); } -const AXES: [(&str, &str); 3] = [("length", "长"), ("width", "宽"), ("height", "高")]; +pub(crate) const AXES: [(&str, &str); 3] = [("length", "长"), ("width", "宽"), ("height", "高")]; -fn barcode_row(code: &str, variant_id: &Value, color: &Value, facts: &Value) -> Value { +pub(crate) fn barcode_row(code: &str, variant_id: &Value, color: &Value, facts: &Value) -> Value { json!({ "id": uuid::Uuid::new_v4().to_string(), "barcode": code, "variantId": variant_id, "colorName": field_text(color), @@ -247,7 +234,7 @@ pub(crate) fn ensure_default_barcode(brief: &mut Value) -> bool { add(code, single_variant, &Value::Null); } if rows.is_empty() { - let color = single_variant.get("colorName").unwrap_or(&brief["colorName"]); + let color = single_variant.get("colorName").or_else(|| single_variant.get("name")).unwrap_or(&brief["colorName"]); rows.push(barcode_row("", &single_variant["id"], color, &Value::Null)); } brief["barcodeEntries"] = json!(rows); @@ -273,119 +260,107 @@ pub(crate) fn migrate_legacy_top_dimensions_to_barcode(brief: &mut Value) -> boo true } -/// Row edits, add and remove are applied to `brief["barcodeEntries"]`. -/// The image intent carries a nonempty barcode and is handled by the owner. +/// The owner uses committed barcode edits to update legacy bindings and images. #[derive(Default, Debug, PartialEq, Eq)] pub(crate) struct BarcodeCardAction { pub changed: bool, - pub pick_image_for_barcode: Option, - /// Position in the list before removal. + pub pending: bool, pub remove_index: Option, pub add_barcode: bool, } -/// Edit the wizard's draft rows. The owner reconciles them with persistent -/// barcode bindings, intake values and scoped references before saving. -pub(crate) fn barcode_cards_section_ui( +pub(crate) fn barcode_cards_section_ui<'a>( ui: &mut Ui, scope: Id, - width: f32, - brief: &mut Value, - material_options: &[Value], + rows: &mut Vec, reduce_motion: bool, + hint: impl Fn(&'static str) -> &'a str, + mut related_fields: impl FnMut(&mut Ui, Id, &Value), ) -> BarcodeCardAction { - let mut action = BarcodeCardAction { changed: ensure_default_barcode(brief), ..Default::default() }; - if action.changed { - migrate_legacy_top_dimensions_to_barcode(brief); - } - let Value::Object(fields) = brief else { return action }; - let Some(Value::Array(mut rows)) = fields.remove("barcodeEntries") else { return action }; - let width = width.min(ui.available_width()); - let removable = rows.len() > 1; - let mut attached = std::collections::HashMap::new(); - for image in fields.get("images").and_then(Value::as_array).into_iter().flatten() { - if let Some(code) = image["barcode"].as_str() { - *attached.entry(code).or_insert(0usize) += 1; - } - } - let variants = fields.get("variants").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); - stitch_ui::scope_with_motion(ui, reduce_motion, |ui| { - ui.push_id(scope, |ui| { - ui.set_width(width); - stitch_kit::section_heading(ui, "产品条码"); - for (index, row) in rows.iter_mut().enumerate() { - let Some(row) = row.as_object_mut() else { continue }; - let id = row.get("id").and_then(Value::as_str).map_or_else(|| scope.with(index), |key| scope.with(key)); - ui.push_id(id, |ui| { - stitch_ui::surface_frame(ui.ctx(), stitch_ui::SurfaceRole::Task).show(ui, |ui| { - action.changed |= edit_text(ui, id, row.entry("barcode").or_insert(Value::Null), "条码编码", "如 DNZ030516N717V01", reduce_motion); - action.changed |= edit_text(ui, id, row.entry("colorName").or_insert(Value::Null), "花色", "填写花色", reduce_motion); - if !variants.is_empty() || !material_options.is_empty() { - let pick = stitch_ui::halo_select(ui, id.with("color"), ui.available_width(), "选择花色", reduce_motion, |ui| { - variants.iter().chain(material_options).find(|option| { - let name = option["colorName"].as_str().or_else(|| option["name"].as_str()); - name.is_some_and(|name| stitch_ui::menu_item(ui, name, true).clicked()) - }) - }); - if let Some(Some(choice)) = pick.inner { - let name = choice.get("colorName").or_else(|| choice.get("name")); - row.insert("colorName".into(), name.cloned().unwrap_or(Value::Null)); - let variant = variants.iter().find(|variant| { - variant["id"] == choice["id"] || variant["colorMaterialId"].as_str().is_some_and(|material| choice["id"] == material) - }); - row.insert("variantId".into(), variant.map(|row| row["id"].clone()).unwrap_or(Value::Null)); - action.changed = true; - } - } - let dimensions = row.entry("dimensions").or_insert(Value::Null); - if dimensions.is_null() { - *dimensions = json!({}); - } - if let Some(dimensions) = dimensions.as_object_mut() { - action.changed |= dimensions_ui(ui, id, dimensions, reduce_motion); - } - let code = row.get("barcode").and_then(Value::as_str).unwrap_or("").trim(); - let linked = attached.get(code).copied().unwrap_or(0); - let count = row.get("images").and_then(Value::as_array).map_or(linked, |images| images.len().max(linked)); - ui.horizontal_wrapped(|ui| { - stitch_kit::caption(ui, if count == 0 { "图片 · 未添加".into() } else { format!("图片 · 已添加 {count} 张") }); - let label = if count == 0 { "添加图片" } else { "更换图片" }; - if stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Secondary, !code.is_empty()) - .on_disabled_hover_text("请先填写条码编码") - .clicked() - { - action.pick_image_for_barcode = Some(code.to_owned()); - } - }); - action.changed |= edit_text(ui, id, row.entry("material").or_insert(Value::Null), "材质(选填)", "", reduce_motion); - action.changed |= edit_text(ui, id, row.entry("boardType").or_insert(Value::Null), "板材类型(选填)", "", reduce_motion); - if removable && stitch_ui::action_button(ui, "移除条码", stitch_ui::ButtonRole::QuietDanger, true).clicked() { + let mut action = BarcodeCardAction::default(); + let mut used_codes: HashSet<_> = rows.iter().filter_map(|row| row["barcode"].as_str()).filter(|code| !code.is_empty()).map(str::to_owned).collect(); + let removable = rows.len() > 1 || rows.first().is_some_and(|row| row["barcode"].as_str().is_some_and(|code| !code.is_empty())); + section_heading_with_tip(ui, "产品条码", "每个条码可填写自己的花色、规格与图片。"); + for (index, row) in rows.iter_mut().enumerate() { + let id = scope.with(row["id"].as_str()); + ui.push_id(id, |ui| { + if index > 0 { + ui.add_space(space::SM); + stitch_ui::divider(ui); + } + ui.add_space(space::XS); + ui.horizontal(|ui| { + stitch_kit::label(ui, format!("条码 {}", index + 1), Type::Body, super::super::stitch_state::Tone::Active); + if removable { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if stitch_ui::action_button(ui, "移除条码", stitch_ui::ButtonRole::QuietDanger, true).clicked() { action.remove_index = Some(index); } }); - ui.add_space(space::XS); - }); + } + }); + ui.add_space(space::XS); + let old = field_text(&row["barcode"]); + let draft_id = id.with("barcode-draft"); + let mut draft = ui.data(|data| data.get_temp::(draft_id)).unwrap_or_else(|| old.clone()); + ui.columns(2, |columns| { + let editor = super::super::creation::wizard_barcode_editor(&mut columns[0], id.with("code"), &mut draft); + let code = draft.trim(); + if code != old { + let issue = if used_codes.contains(code) { Some("此条码已录入当前项目") } + else if code.is_empty() && !old.is_empty() { Some("请填写条码或移除本条") } + else { None }; + if let Some(issue) = issue { + stitch_ui::status_label(&mut columns[0], issue, stitch_ui::StatusTone::Warning); + } else if editor.lost_focus() || (editor.has_focus() && columns[0].input(|input| input.key_pressed(egui::Key::Enter))) { + used_codes.remove(&old); + used_codes.insert(code.to_owned()); + row["barcode"] = json!(code); + action.changed = true; + } + } + action.pending |= row["barcode"] != code && action.remove_index != Some(index); + ui_data_draft(&columns[0], draft_id, draft, &row["barcode"]); + let color_hint = hint("colorName"); + action.changed |= edit_text(&mut columns[1], id, &mut row["colorName"], "花色", + if color_hint.is_empty() { "如 原木色" } else { color_hint }, reduce_motion); + }); + ui.add_space(space::XS); + if let Some(dimensions) = row["dimensions"].as_object_mut() { + action.changed |= dimensions_ui(ui, id, dimensions, reduce_motion, &hint); } - action.add_barcode = stitch_ui::action_button(ui, "+ 添加条码", stitch_ui::ButtonRole::Secondary, true).clicked(); + ui.add_space(space::XS); + ui.columns(2, |columns| { + action.changed |= edit_text(&mut columns[0], id, &mut row["material"], "材质(选填)", hint("material"), reduce_motion); + action.changed |= edit_text(&mut columns[1], id, &mut row["boardType"], "板材类型(选填)", hint("boardType"), reduce_motion); + }); + ui.add_space(space::XS); + related_fields(ui, id, row); }); - }); - if let Some(index) = action.remove_index { - rows.remove(index); - } - if action.add_barcode { - rows.push(barcode_row("", &Value::Null, &Value::Null, &Value::Null)); } + ui.add_space(space::SM); + action.add_barcode = stitch_ui::action_button(ui, "添加条码", stitch_ui::ButtonRole::Secondary, rows.len() < 200).clicked(); action.changed |= action.add_barcode || action.remove_index.is_some(); - fields.insert("barcodeEntries".into(), Value::Array(rows)); action } +fn ui_data_draft(ui: &Ui, id: Id, draft: String, committed: &Value) { + ui.data_mut(|data| { + if committed == draft.trim() { + data.remove::(id); + } else { + data.insert_temp(id, draft); + } + }); +} + fn edit_text(ui: &mut Ui, id: Id, value: &mut Value, label: &str, hint: &str, reduced: bool) -> bool { stitch_kit::caption(ui, label); let mut text = field_text(value); - let id = id.with(label); + let id = super::super::creation::creation_editor_id(ui, id.with(label)); let response = stitch_ui::halo_field(ui, id.with("halo"), None, reduced, |ui| { - let editor = stitch_ui::text_input(&mut text, hint, false).id(id).frame(egui::Frame::NONE).margin(egui::Margin::ZERO); + let editor = stitch_ui::text_input(&mut text, hint, false).id(id).frame(egui::Frame::NONE).margin(egui::Margin::ZERO) + .desired_width(ui.available_width()); ui.add(editor).accessible_name(label) }); if response.changed() { @@ -394,7 +369,10 @@ fn edit_text(ui: &mut Ui, id: Id, value: &mut Value, label: &str, hint: &str, re response.changed() } -fn dimensions_ui(ui: &mut Ui, id: Id, dimensions: &mut serde_json::Map, reduced: bool) -> bool { +fn dimensions_ui<'a>( + ui: &mut Ui, id: Id, dimensions: &mut serde_json::Map, reduced: bool, + hint: &impl Fn(&'static str) -> &'a str, +) -> bool { stitch_kit::caption(ui, "尺寸"); let per_row = if ui.available_width() >= 320.0 { 4 } else { 2 }; let fields = [AXES[0], AXES[1], AXES[2], ("unit", "单位")]; @@ -416,7 +394,7 @@ fn dimensions_ui(ui: &mut Ui, id: Id, dimensions: &mut serde_json::Map WizardFooterOutcome { +pub(crate) fn wizard_footer_ui( + ui: &mut Ui, state: WizardFooterState, show_production: bool, + mut on_button: impl FnMut(WizardFooterOutcome, &Response), +) -> WizardFooterOutcome { use WizardFooterOutcome::{Back, Cancel, EnterCanvas, Next, Start}; use stitch_ui::ButtonRole::{Primary, Quiet, Secondary}; @@ -491,19 +472,44 @@ pub(crate) fn wizard_footer_ui(ui: &mut Ui, state: WizardFooterState) -> WizardF CreationStage::Source => buttons.push(("下一步:选择模板", Primary, state.can_continue, Next)), CreationStage::Template => buttons.push(("下一步:填写产品资料", Primary, state.can_continue, Next)), CreationStage::Details => { - buttons.extend([("进入模板画布", Secondary, state.can_enter_canvas, EnterCanvas), ("确认并开始制作", Primary, state.can_start, Start)]) - } - } - ui.horizontal_wrapped(|ui| { - let mut outcome = WizardFooterOutcome::None; - for (label, role, enabled, intent) in buttons { - if stitch_ui::action_button(ui, label, role, enabled).clicked() { - outcome = intent; + let prioritize_canvas = !show_production || (!state.can_start && state.can_enter_canvas); + if prioritize_canvas && show_production { + buttons.push((if state.can_continue { "继续整套制作" } else { "确认并开始制作" }, Secondary, state.can_start, Start)); + } + buttons.push(("进入模板画布", if prioritize_canvas { Primary } else { Secondary }, state.can_enter_canvas, EnterCanvas)); + if show_production && !prioritize_canvas { + buttons.push((if state.can_continue { "继续整套制作" } else { "确认并开始制作" }, Primary, state.can_start, Start)); } } - outcome - }) - .inner + } + let mut outcome = WizardFooterOutcome::None; + let mut draw = |ui: &mut Ui, (label, role, enabled, intent)| { + let response = stitch_ui::action_button(ui, label, role, enabled); + on_button(intent, &response); + if response.clicked() { + outcome = intent; + } + }; + if ui.available_width() >= 420.0 { + ui.horizontal(|ui| { + let split = if state.stage == CreationStage::Source { 1 } else { 2 }; + for button in &buttons[..split] { + draw(ui, *button); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + for button in buttons[split..].iter().rev() { + draw(ui, *button); + } + }); + }); + } else { + ui.horizontal_wrapped(|ui| { + for button in buttons { + draw(ui, button); + } + }); + } + outcome } #[cfg(test)] @@ -632,7 +638,11 @@ mod tests { for width in [300.0, 720.0] { let mut h = Harness::builder().with_context_setup(setup).with_size(egui::vec2(width, 1100.0)).build_ui_state( |ui, state: &mut (Value, BarcodeCardAction)| { - let action = barcode_cards_section_ui(ui, Id::unique("cards"), width, &mut state.0, &[], true); + ensure_default_barcode(&mut state.0); + let rows = state.0["barcodeEntries"].as_array_mut().unwrap(); + let action = barcode_cards_section_ui(ui, Id::unique("cards"), rows, true, |_| "", |_, _, _| {}); + if let Some(index) = action.remove_index { rows.remove(index); } + if action.add_barcode { rows.push(barcode_row("", &Value::Null, &Value::Null, &Value::Null)); } if action != BarcodeCardAction::default() { state.1 = action; } @@ -640,16 +650,12 @@ mod tests { (json!({"barcodeBindings":{"default":["0001"]},"images":[{"barcode":"0001"}]}), BarcodeCardAction::default()), ); for label in - ["条码编码", "花色", "尺寸", "长", "宽", "高", "单位", "mm", "图片 · 已添加 1 张", "更换图片", "材质(选填)", "板材类型(选填)", "+ 添加条码"] + ["条码编码", "花色", "尺寸", "长", "宽", "高", "单位", "mm", "材质(选填)", "板材类型(选填)", "添加条码"] { let rect = h.query_all_by_label(label).next().unwrap_or_else(|| panic!("missing {label}")).rect(); assert!(rect.left() >= 0.0 && rect.right() <= width, "{label}: {rect:?}"); } - assert!(h.query_by_label("移除条码").is_none()); - h.get_by_label("更换图片").click(); - h.run(); - assert_eq!(h.state().1.pick_image_for_barcode.as_deref(), Some("0001")); - h.get_by_label("+ 添加条码").click(); + h.get_by_label("添加条码").click(); h.run(); assert!(h.state().1.add_barcode); assert_eq!(h.state().0["barcodeEntries"].as_array().unwrap().len(), 2); @@ -693,7 +699,7 @@ mod tests { let mut h = Harness::builder().with_context_setup(setup).with_size(egui::vec2(300.0, 220.0)).build_ui_state( move |ui, result| { let state = WizardFooterState { stage, can_continue: false, can_enter_canvas: false, can_start: false }; - let action = stitch_ui::scope_with_motion(ui, true, |ui| wizard_footer_ui(ui, state)).inner; + let action = stitch_ui::scope_with_motion(ui, true, |ui| wizard_footer_ui(ui, state, true, |_, _| {})).inner; if action != WizardFooterOutcome::None { *result = action; } @@ -721,10 +727,11 @@ mod tests { let mut stage = CreationStage::Details; wizard_stepper_ui(ui, &mut stage, true, true, true); ui.add_space(space::MD); - barcode_cards_section_ui(ui, Id::unique("sample"), ui.available_width(), brief, &[], true); + ensure_default_barcode(brief); + barcode_cards_section_ui(ui, Id::unique("sample"), brief["barcodeEntries"].as_array_mut().unwrap(), true, |_| "", |_, _, _| {}); ui.add_space(space::MD); stitch_ui::scope_with_motion(ui, true, |ui| { - wizard_footer_ui(ui, WizardFooterState { stage, can_continue: false, can_enter_canvas: true, can_start: true }); + wizard_footer_ui(ui, WizardFooterState { stage, can_continue: false, can_enter_canvas: true, can_start: true }, true, |_, _| {}); }); }); }, diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/workspace_navigation.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/workspace_navigation.rs index 29607ab6..91deb6f3 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/workspace_navigation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/workspace_navigation.rs @@ -35,7 +35,7 @@ impl Workspace { "materials" } else if self.library { "projects" - } else if self.creation_open && self.creation_step < 3 { + } else if self.editing_product_brief() { "brief" } else if app.session.active().is_none() { "projects" @@ -68,6 +68,7 @@ impl Workspace { return; } if intent == Intent::Spu { + self.creation_brief["source"] = json!("product_platform"); self.creation_brief["identifierType"] = json!("spu"); self.creation_brief["identifier"] = json!(text); self.creation_dirty = true; @@ -345,19 +346,18 @@ impl Workspace { // Header ui.horizontal(|ui| { - stitch_kit::label(ui, "建项协作者", Type::Heading, Tone::Active); + stitch_kit::label(ui, "建项协作者", Type::TitleLg, Tone::Active); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { stitch_kit::label(ui, format!("{ready_count}/{total_count} 项就绪"), Type::Meta, if missing.is_empty() { Tone::Success } else { Tone::Quiet }); }); }); - stitch_kit::caption(ui, "核对商品资料完整性、平台字段异常与企业规范,点击待补齐项可直接定位。"); stitch_ui::divider(ui); // Section A: Live Brief Readiness stitch_kit::label(ui, "资料核对清单", Type::Body, Tone::Active); let mut focus_target: Option<(String, String)> = None; if missing.is_empty() { - stitch_kit::inline_notice(ui, "check", Tone::Success, "核心建项资料已齐备,可点击底部「确认并开始制作」。", |_| {}); + stitch_kit::inline_notice(ui, "check", Tone::Success, "核心建项资料已齐备。", |_| {}); } else { egui::Frame::NONE .fill(t.field) @@ -368,8 +368,8 @@ impl Workspace { ui.set_width((inner_w - 2.0 * space::SM - 2.0).max(120.0)); ui.spacing_mut().item_spacing.y = space::XS; for item in &missing { - let text = format!("补齐 {} · {}", item.label, item.message); - if stitch_ui::menu_item(ui, &text, true).on_hover_text("点击定位并高亮该字段").clicked() { + let text = format!("补齐 {}", item.label); + if stitch_ui::menu_item(ui, &text, true).on_hover_text(&item.message).clicked() { focus_target = Some((item.field_key.clone(), item.message.clone())); } } @@ -422,8 +422,9 @@ impl Workspace { // Section C: Structured Raw-Material Paste & Knowledge Query (explicit actions, zero keyword guessing) ui.add_space(space::XS); stitch_ui::divider(ui); - stitch_kit::label(ui, "资料暂存与规范查询", Type::Body, Tone::Active); - stitch_kit::caption(ui, "粘贴运营文案、卖点清单或规范问题后,按需选择下方操作。"); + super::creation_reads::wizard::section_heading_with_tip( + ui, "资料暂存与规范查询", "可粘贴运营文案、卖点清单或规范问题。" + ); let pending_kb = self.workbench.pending.is_some(); let draft_resp = stitch_ui::halo_field(ui, Id::unique("brief-copilot-draft"), None, self.reduce_motion, |ui| { ui.add_enabled(