feat(xiaoyi): add three-stage creation wizard components

This commit is contained in:
WuYongJie 2026-12-03 18:38:10 +08:00
parent b2b63417c3
commit 2539e56e19
2 changed files with 738 additions and 0 deletions

View File

@ -2,6 +2,7 @@
//! owns global model busy/unknown state, changes product facts, or uploads data.
use super::{json, Duration, Value, Instant, Workspace, PhotocraftApp, Request};
use std::collections::{HashMap, HashSet, VecDeque};
#[path = "creation_wizard.rs"] pub(super) mod wizard;
const READ_WAIT: Duration = Duration::from_secs(45);
const CACHE_LIMIT: usize = 48;

View File

@ -0,0 +1,737 @@
//! 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};
use crate::theme::Tokens;
use crate::theme::agent_scale::{Type, control, icon, motion, radius, space};
use egui::{Id, Ui};
use serde_json::{Value, json};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum CreationStage {
Source,
Template,
Details,
}
pub(crate) fn resolve_initial_stage(new_project: bool, has_template: bool) -> CreationStage {
if !new_project && has_template { CreationStage::Details } else { CreationStage::Source }
}
/// 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 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;
}
}
});
});
*current != before
}
/// The first display is opaque. A stage change briefly softens the incoming
/// content, with no geometry changes or delayed interaction.
pub(crate) fn stage_reveal_opacity(ctx: &egui::Context, id: Id, stage: CreationStage, reduce_motion: bool) -> f32 {
let now = ctx.input(|input| input.time);
let started = ctx.data_mut(|data| {
let previous = data.get_temp::<(CreationStage, Option<f64>)>(id);
let started = match previous {
_ if reduce_motion => None,
Some((last, started)) if last == stage => started,
Some(_) => Some(now),
None => None,
};
data.insert_temp(id, (stage, started));
started
});
let Some(started) = started else { return 1.0 };
let progress = ((now - started) / motion::MATERIAL).clamp(0.0, 1.0) as f32;
if progress < 1.0 {
ctx.request_repaint();
}
1.0 - 0.18 * (1.0 - progress).powi(3)
}
/// 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);
if !tip.is_empty() {
let response = crate::icons::agent_icon_button(ui, "info", control::STANDARD, false, "").accessible_name("查看说明");
if response.has_focus() && !response.hovered() {
egui::Tooltip::for_widget(&response).show(|ui| {
ui.label(tip);
});
} else {
response.on_hover_text(tip);
}
}
});
}
const AXES: [(&str, &str); 3] = [("length", "长"), ("width", "宽"), ("height", "高")];
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),
"dimensions": editable_dimensions(&facts["dimensions"]), "images": [],
"material": field_text(&facts["material"]), "boardType": field_text(&facts["boardType"]),
})
}
fn editable_dimensions(source: &Value) -> Value {
let mut dimensions = json!({"length":"","width":"","height":"","unit":"mm"});
let unit = source["unit"].as_str().unwrap_or("mm").trim().to_ascii_lowercase();
let meters = matches!(unit.as_str(), "m" | "米");
if meters || matches!(unit.as_str(), "cm" | "厘米") {
dimensions["unit"] = json!("cm");
}
for (axis, _) in AXES {
let value = field_text(&source[axis]);
dimensions[axis] = json!(if meters && let Ok(length) = value.parse::<f64>() {
// Valid legacy drafts have at most three decimal places in meters.
((length * 1000.0).round() / 10.0).to_string()
} else {
value
});
}
dimensions
}
fn field_text(value: &Value) -> String {
match value {
Value::String(text) => text.clone(),
Value::Number(number) => number.to_string(),
_ => String::new(),
}
}
/// Seed editable rows from canonical barcode bindings and imported records.
/// Existing cards and all original source fields retain their values.
pub(crate) fn ensure_default_barcode(brief: &mut Value) -> bool {
if brief["barcodeEntries"].as_array().is_some_and(|rows| !rows.is_empty()) {
return false;
}
if brief.is_null() {
*brief = json!({});
}
if !brief.is_object() {
return false;
}
let variant_rows = brief["variants"].as_array().map(Vec::as_slice).unwrap_or_default();
let single_variant = match variant_rows {
[row] => row,
_ => &Value::Null,
};
let platform = &brief["platformFacts"]["barcodes"];
let intake = &brief["intake"];
let mut rows = Vec::new();
let mut seen = HashSet::new();
let mut add = |code: &str, variant: &Value, imported: &Value| {
let code = code.trim();
if code.is_empty() || !seen.insert(code.to_owned()) {
return;
}
let color = [&imported["colorName"], &platform[code]["colorName"], &variant["colorName"], &brief["colorName"]]
.into_iter()
.find(|value| value.as_str().is_some_and(|text| !text.is_empty()))
.unwrap_or(&Value::Null);
let mut facts = platform[code].as_object().cloned().unwrap_or_default();
if let Some(imported) = imported.as_object() {
facts.extend(imported.clone());
}
let facts = Value::Object(facts);
let mut row = barcode_row(code, &variant["id"], color, &facts);
let answers = &intake["barcodeValues"][code];
for (axis, _) in AXES {
if let Some(answer) = answers.get(axis) {
let schema_unit = intake["schema"]["barcodeFields"]
.as_array()
.into_iter()
.flatten()
.find(|field| field.get("id").unwrap_or(&field["key"]) == axis)
.and_then(|field| field["unit"].as_str());
let source_unit = &facts["dimensions"]["unit"];
let unit = schema_unit.or_else(|| source_unit.as_str()).unwrap_or("mm");
let answer = editable_dimensions(&json!({"unit":unit, axis:answer}));
let target_unit = &row["dimensions"]["unit"];
if target_unit == &answer["unit"] {
row["dimensions"][axis] = answer[axis].clone();
} else if let Ok(length) = field_text(&answer[axis]).parse::<f64>() {
let converted = if target_unit == "cm" { length / 10.0 } else { length * 10.0 };
row["dimensions"][axis] = json!(converted.to_string());
}
}
}
for key in ["colorName", "material", "boardType"] {
if let Some(answer) = answers[key].as_str() {
row[key] = json!(answer);
}
}
rows.push(row);
};
for (owner, binding) in brief["barcodeBindings"].as_object().into_iter().flatten() {
let variant = if owner == "default" { single_variant } else { variant_rows.iter().find(|row| row["id"] == *owner).unwrap_or(&Value::Null) };
let normalized = brief["normalizedProduct"]["variants"].as_array().into_iter().flatten().find(|row| row["id"] == variant["id"]);
let codes = binding
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
.chain(binding.as_str().into_iter().flat_map(|text| text.split(['\r', '\n', ',', ',', '、', ';', ';'])));
for code in codes {
let imported = normalized
.into_iter()
.flat_map(|row| row["barcodes"].as_array().into_iter().flatten())
.find(|row| row["barcode"] == code.trim())
.unwrap_or(&Value::Null);
add(code, variant, imported);
}
}
for variant in brief["normalizedProduct"]["variants"].as_array().into_iter().flatten() {
for row in variant["barcodes"].as_array().into_iter().flatten() {
if let Some(code) = row["barcode"].as_str() {
add(code, variant, row);
}
}
}
for row in brief["barcodes"].as_array().into_iter().flatten() {
if let Some(code) = row.as_str().or_else(|| row["barcode"].as_str()) {
let variant = variant_rows.iter().find(|variant| variant["id"] == row["variantId"]).unwrap_or(single_variant);
add(code, variant, row);
}
}
for (code, facts) in platform.as_object().into_iter().flatten() {
add(code, single_variant, facts);
}
if brief["identifierType"] == "barcode"
&& let Some(code) = brief["identifier"].as_str()
{
add(code, single_variant, &Value::Null);
}
if rows.is_empty() {
let color = single_variant.get("colorName").unwrap_or(&brief["colorName"]);
rows.push(barcode_row("", &single_variant["id"], color, &Value::Null));
}
brief["barcodeEntries"] = json!(rows);
true
}
/// Copy dimensions only to the first card and only while all its axes are blank.
/// Keep the legacy source intact for readers of older brief versions.
pub(crate) fn migrate_legacy_top_dimensions_to_barcode(brief: &mut Value) -> bool {
let legacy = &brief["dimensions"];
let has_axes = |dimensions: &Value| {
AXES.iter().any(|(axis, _)| {
let value = &dimensions[*axis];
value.is_number() || value.as_str().is_some_and(|text| !text.trim().is_empty())
})
};
if !has_axes(legacy) || has_axes(&brief["barcodeEntries"][0]["dimensions"]) {
return false;
}
let dimensions = editable_dimensions(legacy);
let Some(row) = brief.get_mut("barcodeEntries").and_then(|rows| rows.get_mut(0)).filter(|row| row.is_object()) else { return false };
row["dimensions"] = dimensions;
true
}
/// Row edits, add and remove are applied to `brief["barcodeEntries"]`.
/// The image intent carries a nonempty barcode and is handled by the owner.
#[derive(Default, Debug, PartialEq, Eq)]
pub(crate) struct BarcodeCardAction {
pub changed: bool,
pub pick_image_for_barcode: Option<String>,
/// Position in the list before removal.
pub remove_index: Option<usize>,
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(
ui: &mut Ui,
scope: Id,
width: f32,
brief: &mut Value,
material_options: &[Value],
reduce_motion: bool,
) -> 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() {
action.remove_index = Some(index);
}
});
ui.add_space(space::XS);
});
}
action.add_barcode = stitch_ui::action_button(ui, "+ 添加条码", stitch_ui::ButtonRole::Secondary, true).clicked();
});
});
if let Some(index) = action.remove_index {
rows.remove(index);
}
if action.add_barcode {
rows.push(barcode_row("", &Value::Null, &Value::Null, &Value::Null));
}
action.changed |= action.add_barcode || action.remove_index.is_some();
fields.insert("barcodeEntries".into(), Value::Array(rows));
action
}
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 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);
ui.add(editor).accessible_name(label)
});
if response.changed() {
*value = json!(text);
}
response.changed()
}
fn dimensions_ui(ui: &mut Ui, id: Id, dimensions: &mut serde_json::Map<String, Value>, reduced: bool) -> 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", "单位")];
let mut changed = false;
for group in fields.chunks(per_row) {
ui.columns(group.len(), |columns| {
for (ui, &(field, label)) in columns.iter_mut().zip(group) {
let value = dimensions.entry(field).or_insert(Value::Null);
if field == "unit" {
stitch_kit::caption(ui, label);
let selected = value.as_str().unwrap_or("mm");
let pick = stitch_ui::halo_select(ui, id.with(field), ui.available_width(), selected, reduced, |ui| {
["mm", "cm"].into_iter().find(|unit| stitch_ui::menu_item(ui, unit, true).clicked())
});
if let Some(Some(unit)) = pick.inner
&& unit != selected
{
*value = json!(unit);
changed = true;
}
} else {
changed |= edit_text(ui, id, value, label, "", reduced);
}
}
});
}
changed
}
/// Update the presentation metadata for matching fields of the same template.
/// Field identities and value types stay stable so existing answers still validate.
pub(crate) fn refresh_intake_schema_from_catalog(brief: &mut Value, catalog_template: &Value) -> bool {
let catalog_schema = &catalog_template["intake"];
let Some(id) = catalog_template["id"].as_str().filter(|id| !id.is_empty()) else { return false };
let Some(intake) = brief.get_mut("intake") else { return false };
if intake["templateId"] != id || intake["schema"]["version"] != 1 || catalog_schema["version"] != 1 {
return false;
}
fn field_key(field: &Value) -> Option<&str> {
field.get("id").or_else(|| field.get("key")).and_then(Value::as_str)
}
let mut changed = false;
for scope in ["productFields", "barcodeFields"] {
let Some(current) = intake.get_mut("schema").and_then(|schema| schema.get_mut(scope)).and_then(Value::as_array_mut) else { continue };
let Some(updated) = catalog_schema[scope].as_array() else { continue };
for field in current {
let Some(key) = field_key(field) else { continue };
let Some(update) = updated.iter().find(|update| field_key(update) == Some(key)) else { continue };
let Some(field) = field.as_object_mut() else { continue };
for property in ["label", "placeholder", "help"] {
match update.get(property).and_then(Value::as_str) {
Some(text) if field.get(property).and_then(Value::as_str) != Some(text) => {
field.insert(property.to_owned(), json!(text));
changed = true;
}
None if property != "label" => changed |= field.remove(property).is_some(),
_ => {}
}
}
}
}
changed
}
/// Action availability is supplied by the owner from validation and save state.
#[derive(Clone, Copy, Debug)]
pub(crate) struct WizardFooterState {
pub stage: CreationStage,
pub can_continue: bool,
pub can_enter_canvas: bool,
pub can_start: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum WizardFooterOutcome {
#[default]
None,
Cancel,
Back,
Next,
EnterCanvas,
Start,
}
pub(crate) fn wizard_footer_ui(ui: &mut Ui, state: WizardFooterState) -> WizardFooterOutcome {
use WizardFooterOutcome::{Back, Cancel, EnterCanvas, Next, Start};
use stitch_ui::ButtonRole::{Primary, Quiet, Secondary};
let mut buttons = vec![("取消", Quiet, true, Cancel)];
if state.stage != CreationStage::Source {
buttons.push(("上一步", Secondary, true, Back));
}
match state.stage {
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;
}
}
outcome
})
.inner
}
#[cfg(test)]
mod tests {
use super::*;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
fn setup(ctx: &egui::Context) {
crate::PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium);
crate::cjk_fonts::install_system_provider_for_tests(ctx);
}
#[test]
fn new_or_unbound_projects_start_at_source_and_bound_projects_open_details() {
assert_eq!(resolve_initial_stage(true, false), CreationStage::Source);
assert_eq!(resolve_initial_stage(true, true), CreationStage::Source);
assert_eq!(resolve_initial_stage(false, false), CreationStage::Source);
assert_eq!(resolve_initial_stage(false, true), CreationStage::Details);
}
#[test]
fn stepper_navigates_back_to_completed_steps_only() {
let mut h = Harness::builder().with_context_setup(setup).build_ui_state(
|ui, state: &mut (CreationStage, bool)| {
state.1 |= wizard_stepper_ui(ui, &mut state.0, true, true, true);
},
(CreationStage::Details, false),
);
h.get_by_label("2. 选择模板").click();
h.run();
assert_eq!(*h.state(), (CreationStage::Template, true));
h.get_by_label("3. 填写产品资料").click();
h.run();
assert_eq!(h.state().0, CreationStage::Template);
h.get_by_label("1. 资料来源").click();
h.run();
assert_eq!(h.state().0, CreationStage::Source);
}
#[test]
fn reveal_softens_only_stage_changes_and_obeys_reduced_motion() {
let ctx = egui::Context::default();
let id = Id::unique("wizard-stage");
let frame = |time, stage, reduced| {
let mut alpha = 0.0;
let mut frame = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| {
alpha = stage_reveal_opacity(ui.ctx(), id, stage, reduced);
});
frame.textures_delta.clear();
alpha
};
assert_eq!(frame(0.0, CreationStage::Source, false), 1.0);
let initial = frame(0.1, CreationStage::Template, false);
let later = frame(0.18, CreationStage::Template, false);
assert!(0.0 < initial && initial < later && later < 1.0);
assert_eq!(frame(0.4, CreationStage::Template, false), 1.0);
assert_eq!(frame(0.5, CreationStage::Details, true), 1.0);
assert_eq!(frame(0.6, CreationStage::Details, false), 1.0);
}
#[test]
fn section_title_keeps_its_explanation_off_the_form() {
let h = Harness::builder().with_context_setup(setup).build_ui(|ui| {
section_heading_with_tip(ui, "产品资料", "填写模板需要的内容");
});
h.get_by_label("产品资料");
h.get_by_label("查看说明");
assert!(h.query_by_label("填写模板需要的内容").is_none());
}
#[test]
fn empty_brief_gets_one_structured_row_and_top_dimensions_migrate_once() {
let mut brief = json!({
"colorName":"原木色",
"dimensions":{"length":"1600","width":"850","height":"750","unit":"cm"},
});
assert!(ensure_default_barcode(&mut brief));
assert!(!ensure_default_barcode(&mut brief));
let rows = brief["barcodeEntries"].as_array().unwrap();
assert_eq!(rows.len(), 1);
let row = &rows[0];
assert_eq!(row["barcode"], "");
assert_eq!(row["colorName"], "原木色");
assert_eq!(row["variantId"], Value::Null);
assert_eq!(row["images"], json!([]));
assert_eq!(row["material"], "");
assert_eq!(row["boardType"], "");
assert_eq!(row["dimensions"], json!({"length":"","width":"","height":"","unit":"mm"}));
assert!(migrate_legacy_top_dimensions_to_barcode(&mut brief));
assert_eq!(brief["barcodeEntries"][0]["dimensions"], brief["dimensions"]);
assert!(!migrate_legacy_top_dimensions_to_barcode(&mut brief));
brief["barcodeEntries"][0]["dimensions"]["length"] = json!("1700");
assert!(!migrate_legacy_top_dimensions_to_barcode(&mut brief));
assert_eq!(brief["barcodeEntries"][0]["dimensions"]["length"], "1700");
}
#[test]
fn imported_codes_and_variant_owners_survive_card_initialization() {
let mut brief = json!({
"source":"product_platform",
"barcodeBindings":{"natural":["0001,A","0002"]},
"variants":[{"id":"natural","colorName":"原木色"}],
"platformFacts":{"barcodes":{"0001,A":{"dimensions":{"height":750,"unit":"MM"}}}},
"intake":{"barcodeValues":{"0001,A":{"height":760,"material":"实木"}}},
});
let original = brief.clone();
assert!(ensure_default_barcode(&mut brief));
assert_eq!(brief["barcodeEntries"].as_array().unwrap().len(), 2);
assert_eq!(brief["barcodeEntries"][0]["barcode"], "0001,A");
assert_eq!(brief["barcodeEntries"][0]["variantId"], "natural");
assert_eq!(brief["barcodeEntries"][0]["dimensions"]["height"], "760");
assert_eq!(brief["barcodeEntries"][0]["material"], "实木");
assert_eq!(brief["barcodeEntries"][1]["barcode"], "0002");
for (key, value) in original.as_object().unwrap() {
assert_eq!(brief[key], *value);
}
let structured = brief.clone();
assert!(!ensure_default_barcode(&mut brief));
assert_eq!(brief, structured);
}
#[test]
fn cards_fit_narrow_and_wide_layouts_and_dispatch_card_actions() {
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);
if action != BarcodeCardAction::default() {
state.1 = action;
}
},
(json!({"barcodeBindings":{"default":["0001"]},"images":[{"barcode":"0001"}]}), BarcodeCardAction::default()),
);
for label in
["条码编码", "花色", "尺寸", "长", "宽", "高", "单位", "mm", "图片 · 已添加 1 张", "更换图片", "材质(选填)", "板材类型(选填)", "+ 添加条码"]
{
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.run();
assert!(h.state().1.add_barcode);
assert_eq!(h.state().0["barcodeEntries"].as_array().unwrap().len(), 2);
h.query_all_by_label("移除条码").next().unwrap().click();
h.run();
assert_eq!(h.state().1.remove_index, Some(0));
assert_eq!(h.state().0["barcodeEntries"][0]["barcode"], "");
}
}
#[test]
fn same_template_refreshes_feishu_metadata_without_changing_answers() {
let mut brief = json!({"intake":{"templateId":"table-v1","schema":{"version":1,
"productFields":[{"id":"origin","type":"text","label":"产地","help":"旧说明"}],
"barcodeFields":[{"key":"length","kind":"number","label":"长"}]},
"productValues":{"origin":"佛山"},"barcodeValues":{"00A":{"length":1600}}}});
let catalog = json!({"id":"table-v1","intake":{"version":1,
"productFields":[{"id":"origin","type":"text","label":"产品产地","help":"填写城市","placeholder":"如广州"}],
"barcodeFields":[{"id":"length","type":"number","label":"长度","placeholder":"如1800"}]}});
let before = brief.clone();
let mut other = catalog.clone();
other["id"] = json!("other");
assert!(!refresh_intake_schema_from_catalog(&mut brief, &other));
assert_eq!(brief, before);
assert!(refresh_intake_schema_from_catalog(&mut brief, &catalog));
let intake = &brief["intake"];
assert_eq!(intake["schema"]["productFields"][0], catalog["intake"]["productFields"][0]);
assert_eq!(intake["schema"]["barcodeFields"][0]["placeholder"], "如1800");
assert_eq!(intake["productValues"], before["intake"]["productValues"]);
assert_eq!(intake["barcodeValues"], before["intake"]["barcodeValues"]);
assert!(!refresh_intake_schema_from_catalog(&mut brief, &catalog));
}
#[test]
fn each_footer_renders_stage_actions_and_cancel_is_always_available() {
for (stage, labels) in [
(CreationStage::Source, &["下一步:选择模板"][..]),
(CreationStage::Template, &["上一步", "下一步:填写产品资料"][..]),
(CreationStage::Details, &["上一步", "进入模板画布", "确认并开始制作"][..]),
] {
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;
if action != WizardFooterOutcome::None {
*result = action;
}
},
WizardFooterOutcome::None,
);
for label in labels {
h.get_by_label(label);
}
h.get_by_label("取消").click();
h.run();
assert_eq!(*h.state(), WizardFooterOutcome::Cancel);
}
}
#[test]
#[ignore = "offscreen GPU inspection; requires an explicit WIZARD_QA_DIR"]
fn render_wizard_components_at_wide_and_narrow_widths() {
let _gpu = photocraft_testkit::gpu_lock();
let directory = std::path::PathBuf::from(std::env::var_os("WIZARD_QA_DIR").unwrap());
for width in [300.0, 720.0] {
let mut h = Harness::builder().with_context_setup(setup).with_size(egui::vec2(width, 820.0)).wgpu().build_ui_state(
|ui, brief: &mut Value| {
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(Tokens::get(ui.ctx()).agent().dock).inner_margin(space::SM)).show(ui, |ui| {
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);
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 });
});
});
},
json!({"barcodeBindings":{"default":["DNZ030516N717V01"]},"colorName":"原木色"}),
);
h.run_steps(4);
h.render().unwrap().save(directory.join(format!("wizard-{width}.png"))).unwrap();
}
}
}