refactor(photocraft): split agent_panel and creation, add chunked upload progress, and fix Linux baseline tests
This commit is contained in:
parent
f6e474fb07
commit
36dedf8459
@ -655,11 +655,123 @@ impl Backend {
|
||||
self.material_response(self.http.post(format!("{}/api/{endpoint}", self.origin))
|
||||
.bearer_auth(token).json(payload).timeout(Duration::from_secs(300)))
|
||||
}
|
||||
}
|
||||
|
||||
struct UploadProgressTracker {
|
||||
account_id: Value,
|
||||
origin: String,
|
||||
request_id: String,
|
||||
total_files: usize,
|
||||
total_bytes: u64,
|
||||
total_chunks: u64,
|
||||
uploaded_bytes: u64,
|
||||
completed_chunks: u64,
|
||||
session_bytes: u64,
|
||||
file_index: usize,
|
||||
started_at: std::time::Instant,
|
||||
}
|
||||
|
||||
impl UploadProgressTracker {
|
||||
fn new(account_id: Value, origin: String, request_id: String, files: &[Artifact], state: &Value) -> Self {
|
||||
let mut total_bytes = 0u64;
|
||||
let mut total_chunks = 0u64;
|
||||
let mut uploaded_bytes = 0u64;
|
||||
let mut completed_chunks = 0u64;
|
||||
for (index, artifact) in files.iter().enumerate() {
|
||||
let chunks = artifact.size.div_ceil(CHUNK_SIZE).max(1);
|
||||
total_bytes = total_bytes.saturating_add(artifact.size);
|
||||
total_chunks = total_chunks.saturating_add(chunks);
|
||||
let upload = &state["uploads"][index.to_string()];
|
||||
if upload["complete"] == true {
|
||||
uploaded_bytes = uploaded_bytes.saturating_add(artifact.size);
|
||||
completed_chunks = completed_chunks.saturating_add(chunks);
|
||||
} else if let Some(next_chunk) = upload["nextChunk"].as_u64() {
|
||||
let done_chunks = next_chunk.min(chunks);
|
||||
completed_chunks = completed_chunks.saturating_add(done_chunks);
|
||||
uploaded_bytes = uploaded_bytes.saturating_add(done_chunks.saturating_mul(CHUNK_SIZE).min(artifact.size));
|
||||
}
|
||||
}
|
||||
Self {
|
||||
account_id,
|
||||
origin,
|
||||
request_id,
|
||||
total_files: files.len(),
|
||||
total_bytes,
|
||||
total_chunks,
|
||||
uploaded_bytes,
|
||||
completed_chunks,
|
||||
session_bytes: 0,
|
||||
file_index: 0,
|
||||
started_at: std::time::Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn advance_chunk(&mut self, bytes: u64) {
|
||||
self.completed_chunks = (self.completed_chunks + 1).min(self.total_chunks);
|
||||
self.uploaded_bytes = self.uploaded_bytes.saturating_add(bytes).min(self.total_bytes);
|
||||
self.session_bytes = self.session_bytes.saturating_add(bytes);
|
||||
}
|
||||
|
||||
fn eta_seconds(&self) -> Option<u64> {
|
||||
let remaining = self.total_bytes.saturating_sub(self.uploaded_bytes);
|
||||
if remaining == 0 {
|
||||
return Some(0);
|
||||
}
|
||||
let elapsed = self.started_at.elapsed().as_secs_f64();
|
||||
if self.session_bytes == 0 || elapsed < 0.05 {
|
||||
return None;
|
||||
}
|
||||
let bytes_per_sec = self.session_bytes as f64 / elapsed;
|
||||
if bytes_per_sec <= 1.0 {
|
||||
return None;
|
||||
}
|
||||
Some((remaining as f64 / bytes_per_sec).ceil().clamp(1.0, 86_400.0) as u64)
|
||||
}
|
||||
|
||||
fn snapshot(&self, artifact: &Artifact, stage: &str) -> Value {
|
||||
json!({
|
||||
"accountId": self.account_id,
|
||||
"origin": self.origin,
|
||||
"requestId": self.request_id,
|
||||
"fileIndex": self.file_index,
|
||||
"totalFiles": self.total_files,
|
||||
"fileName": artifact.name,
|
||||
"uploadedBytes": self.uploaded_bytes,
|
||||
"totalBytes": self.total_bytes,
|
||||
"completedChunks": self.completed_chunks,
|
||||
"totalChunks": self.total_chunks,
|
||||
"stage": stage,
|
||||
"etaSeconds": self.eta_seconds(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
fn emit_upload_progress(&self, payload: Value) {
|
||||
if let Some((events, ctx)) = &self.access.notifications {
|
||||
let _ = events.send(super::Event::Json("delivery-upload-progress".into(), Ok(payload)));
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
}
|
||||
|
||||
fn upload_material_file(&self, state_file: &Path, state: &mut Value, key: &str, artifact: &Artifact,
|
||||
purpose: &str, token: &str,
|
||||
) -> R<String> {
|
||||
let chunks = artifact.size.div_ceil(CHUNK_SIZE);
|
||||
self.upload_material_file_with_progress(state_file, state, key, artifact, purpose, token, None)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn upload_material_file_with_progress(
|
||||
&self,
|
||||
state_file: &Path,
|
||||
state: &mut Value,
|
||||
key: &str,
|
||||
artifact: &Artifact,
|
||||
purpose: &str,
|
||||
token: &str,
|
||||
mut progress: Option<&mut UploadProgressTracker>,
|
||||
) -> R<String> {
|
||||
let chunks = artifact.size.div_ceil(CHUNK_SIZE).max(1);
|
||||
let mut repaired = false;
|
||||
loop {
|
||||
if state["uploads"][key]["uploadId"].is_null() {
|
||||
@ -674,31 +786,45 @@ impl Backend {
|
||||
}
|
||||
let upload = &state["uploads"][key];
|
||||
let upload_id = upload["uploadId"].as_str().ok_or("素材库未返回上传编号")?.to_owned();
|
||||
if upload["complete"] == true { return Ok(upload_id); }
|
||||
if upload["complete"] == true {
|
||||
if let Some(tracker) = progress.as_deref_mut() {
|
||||
self.emit_upload_progress(tracker.snapshot(artifact, "uploading"));
|
||||
}
|
||||
return Ok(upload_id);
|
||||
}
|
||||
|
||||
let mut file = File::open(&artifact.path).map_err(|_| "成品文件无法读取")?;
|
||||
let start = upload["nextChunk"].as_u64().unwrap_or(0);
|
||||
let mut expired = false;
|
||||
for index in start..chunks {
|
||||
let offset = index * CHUNK_SIZE;
|
||||
let size = (artifact.size - offset).min(CHUNK_SIZE);
|
||||
file.seek(SeekFrom::Start(offset)).map_err(|_| "成品文件读取中断")?;
|
||||
let mut bytes = vec![0; size as usize];
|
||||
file.read_exact(&mut bytes).map_err(|_| "成品文件读取中断")?;
|
||||
let (status, value) = self.material_response(self.http.post(format!("{}/api/materials/upload/chunk", self.origin))
|
||||
.bearer_auth(token).header("Content-Type", "application/octet-stream")
|
||||
.header("X-Upload-Id", &upload_id).header("X-Chunk-Index", index.to_string())
|
||||
.header("X-File-Name", &artifact.name).header("X-Chunk-Size", size.to_string())
|
||||
.timeout(Duration::from_secs(300)).body(bytes))?;
|
||||
if status == 404 {
|
||||
expired = true;
|
||||
break;
|
||||
let size = artifact.size.saturating_sub(offset).min(CHUNK_SIZE);
|
||||
if size > 0 {
|
||||
file.seek(SeekFrom::Start(offset)).map_err(|_| "成品文件读取中断")?;
|
||||
let mut bytes = vec![0; size as usize];
|
||||
file.read_exact(&mut bytes).map_err(|_| "成品文件读取中断")?;
|
||||
let (status, value) = self.material_response(self.http.post(format!("{}/api/materials/upload/chunk", self.origin))
|
||||
.bearer_auth(token).header("Content-Type", "application/octet-stream")
|
||||
.header("X-Upload-Id", &upload_id).header("X-Chunk-Index", index.to_string())
|
||||
.header("X-File-Name", &artifact.name).header("X-Chunk-Size", size.to_string())
|
||||
.timeout(Duration::from_secs(300)).body(bytes))?;
|
||||
if status == 404 {
|
||||
expired = true;
|
||||
break;
|
||||
}
|
||||
if status != 200 { return Err(material_error(&value)); }
|
||||
}
|
||||
if status != 200 { return Err(material_error(&value)); }
|
||||
state["uploads"][key]["nextChunk"] = json!(index + 1);
|
||||
write_json(state_file, state)?;
|
||||
if let Some(tracker) = progress.as_deref_mut() {
|
||||
tracker.advance_chunk(size);
|
||||
self.emit_upload_progress(tracker.snapshot(artifact, "uploading"));
|
||||
}
|
||||
}
|
||||
|
||||
if !expired && let Some(tracker) = progress.as_deref_mut() {
|
||||
self.emit_upload_progress(tracker.snapshot(artifact, "merging"));
|
||||
}
|
||||
let (status, completed) = if expired {
|
||||
(404, json!({"error":"素材上传会话已失效"}))
|
||||
} else {
|
||||
@ -780,13 +906,35 @@ impl Backend {
|
||||
let purpose = format!("xiaoyi:{cloud_id}:{request_id}");
|
||||
let mut repaired = false;
|
||||
let result = loop {
|
||||
let mut tracker = UploadProgressTracker::new(
|
||||
self.auth["account"]["id"].clone(),
|
||||
self.origin.clone(),
|
||||
request_id.clone(),
|
||||
delivery_files,
|
||||
&state,
|
||||
);
|
||||
if let Some(first) = delivery_files.first() {
|
||||
self.emit_upload_progress(tracker.snapshot(first, "uploading"));
|
||||
}
|
||||
let mut groups = json!({"main":[],"sku":[],"detail":[]});
|
||||
for (index, artifact) in delivery_files.iter().enumerate() {
|
||||
let upload_id = self.upload_material_file(&state_file, &mut state, &index.to_string(), artifact, &purpose, token)?;
|
||||
tracker.file_index = index;
|
||||
let upload_id = self.upload_material_file_with_progress(
|
||||
&state_file,
|
||||
&mut state,
|
||||
&index.to_string(),
|
||||
artifact,
|
||||
&purpose,
|
||||
token,
|
||||
Some(&mut tracker),
|
||||
)?;
|
||||
let mut file = artifact.file_info();
|
||||
file["uploadId"] = json!(upload_id);
|
||||
groups[artifact.group].as_array_mut().ok_or("素材分组无效")?.push(file);
|
||||
}
|
||||
if let Some(last) = delivery_files.last() {
|
||||
self.emit_upload_progress(tracker.snapshot(last, "submitting"));
|
||||
}
|
||||
if read_json(&project.join("context.json"))?["revision"].as_u64() != Some(revision)
|
||||
|| detail_artifacts(project)? != artifacts
|
||||
|| creation::load(project)?["brief"] != brief
|
||||
@ -1068,4 +1216,48 @@ mod tests {
|
||||
assert_eq!(meta["specId"], "带轮款");
|
||||
assert_eq!(meta["variantName"], "原木色");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upload_progress_tracker_tracks_resumed_chunks_and_eta() {
|
||||
let art_a = Artifact {
|
||||
path: PathBuf::from("a.psd"), name: "a.psd".into(), group: "detail",
|
||||
size: CHUNK_SIZE * 2, sha256: "a".repeat(64), width: 100, height: 100,
|
||||
sku_variant: None, sku_spec_id: None, sku_variant_name: None, sku: None,
|
||||
};
|
||||
let art_b = Artifact {
|
||||
path: PathBuf::from("b.jpg"), name: "b.jpg".into(), group: "main",
|
||||
size: 512, sha256: "b".repeat(64), width: 100, height: 100,
|
||||
sku_variant: None, sku_spec_id: None, sku_variant_name: None, sku: None,
|
||||
};
|
||||
let state = json!({"uploads": {"0": {"nextChunk": 1}}});
|
||||
let mut tracker = UploadProgressTracker::new(
|
||||
json!("acc-1"),
|
||||
"https://sc.jiansun.vip".into(),
|
||||
"req-1".into(),
|
||||
&[art_a.clone(), art_b.clone()],
|
||||
&state,
|
||||
);
|
||||
let snap0 = tracker.snapshot(&art_a, "uploading");
|
||||
assert_eq!(snap0["totalFiles"], 2);
|
||||
assert_eq!(snap0["totalChunks"], 3);
|
||||
assert_eq!(snap0["completedChunks"], 1);
|
||||
assert_eq!(snap0["uploadedBytes"], CHUNK_SIZE);
|
||||
assert_eq!(snap0["totalBytes"], CHUNK_SIZE * 2 + 512);
|
||||
assert!(snap0["etaSeconds"].is_null());
|
||||
|
||||
tracker.started_at = std::time::Instant::now() - Duration::from_secs(2);
|
||||
tracker.advance_chunk(CHUNK_SIZE);
|
||||
let snap1 = tracker.snapshot(&art_a, "uploading");
|
||||
assert_eq!(snap1["completedChunks"], 2);
|
||||
assert_eq!(snap1["uploadedBytes"], CHUNK_SIZE * 2);
|
||||
assert_eq!(snap1["etaSeconds"], 1);
|
||||
|
||||
tracker.file_index = 1;
|
||||
tracker.advance_chunk(512);
|
||||
let snap2 = tracker.snapshot(&art_b, "submitting");
|
||||
assert_eq!(snap2["completedChunks"], 3);
|
||||
assert_eq!(snap2["uploadedBytes"], CHUNK_SIZE * 2 + 512);
|
||||
assert_eq!(snap2["etaSeconds"], 0);
|
||||
assert_eq!(snap2["stage"], "submitting");
|
||||
}
|
||||
}
|
||||
|
||||
@ -1204,6 +1204,7 @@ pub struct Workspace {
|
||||
listing_read_at: Option<(u64, Instant)>,
|
||||
listing_read_error: Option<String>,
|
||||
delivery_completion: bool,
|
||||
delivery_upload_progress: Option<Value>,
|
||||
finished_web_pending: bool,
|
||||
finished_web_error: Option<String>,
|
||||
sync_dirty: bool,
|
||||
@ -1875,6 +1876,7 @@ impl Workspace {
|
||||
listing_read_at: None,
|
||||
listing_read_error: None,
|
||||
delivery_completion: false,
|
||||
delivery_upload_progress: None,
|
||||
finished_web_pending: false,
|
||||
finished_web_error: None,
|
||||
sync_dirty: true,
|
||||
@ -2597,6 +2599,26 @@ impl Workspace {
|
||||
.chain(self.unknown_image_task.as_deref().map(|id| ("image-recover", id)))
|
||||
}
|
||||
|
||||
fn unknown_recovery_delay(&self, now: Instant) -> Option<Duration> {
|
||||
if !self.unknown {
|
||||
return None;
|
||||
}
|
||||
let production = self.product_production.as_ref();
|
||||
self.original_image_recoveries()
|
||||
.filter(|(_, id)| !production.is_some_and(|run| run.owns_deferred_image(id)))
|
||||
.filter_map(|(_, id)| {
|
||||
let keep_checking = production.is_some_and(|run| run.waiting_for_image(id));
|
||||
match self.image_recovery_schedules.get(id) {
|
||||
Some(schedule) if !schedule.exhausted() || keep_checking => {
|
||||
Some(schedule.due.saturating_duration_since(now))
|
||||
}
|
||||
Some(_) => None,
|
||||
None => Some(Duration::ZERO),
|
||||
}
|
||||
})
|
||||
.min()
|
||||
}
|
||||
|
||||
fn automatic_image_recovery(&mut self, app: &PhotocraftApp, now: Instant) {
|
||||
if !self.unknown { return; }
|
||||
let Some(doc) = self.automatic_recovery_doc(app).filter(|doc| self.loaded_draft == Some(*doc)) else { return };
|
||||
@ -3624,6 +3646,18 @@ impl Workspace {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if method == "delivery-upload-progress" {
|
||||
if let Ok(value) = result
|
||||
&& value["accountId"] == self.account["id"]
|
||||
&& value["origin"] == self.origin
|
||||
{
|
||||
self.delivery_upload_progress = Some(value);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if method == "project-sync" {
|
||||
self.delivery_upload_progress = None;
|
||||
}
|
||||
if method == "delivery-status" {
|
||||
if let Ok(value) = result {
|
||||
creation::listing_status_received(self, app, &value);
|
||||
@ -4178,6 +4212,7 @@ impl Workspace {
|
||||
self.creation_progress.clear();
|
||||
self.sync_confirm = false;
|
||||
self.delivery_completion = false;
|
||||
self.delivery_upload_progress = None;
|
||||
self.finished_web_pending = false;
|
||||
self.finished_web_error = None;
|
||||
self.agent_rule = Value::Null;
|
||||
@ -4517,8 +4552,8 @@ impl Workspace {
|
||||
let interval = if self.project_refresh_requested { PROJECT_REFRESH_COOLDOWN } else { PROJECT_REFRESH_INTERVAL };
|
||||
ctx.request_repaint_after(interval.saturating_sub(self.project_refresh.elapsed()));
|
||||
}
|
||||
if self.unknown {
|
||||
ctx.request_repaint_after(Duration::from_secs(1));
|
||||
if let Some(delay) = self.unknown_recovery_delay(Instant::now()) {
|
||||
ctx.request_repaint_after(delay);
|
||||
}
|
||||
if self.waiting_for_external_agent() {
|
||||
ctx.request_repaint_after(Duration::from_secs(10).saturating_sub(self.pi_touched.elapsed()));
|
||||
@ -6469,20 +6504,49 @@ mod tests {
|
||||
assert_eq!(w.creation_brief["name"], "已保存的资料");
|
||||
}
|
||||
|
||||
fn module_tree_sources(stem: &str) -> Vec<(String, String)> {
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/jiansun");
|
||||
let mut out = Vec::new();
|
||||
let parent = root.join(format!("{stem}.rs"));
|
||||
if let Ok(src) = std::fs::read_to_string(&parent) {
|
||||
out.push((stem.to_owned(), src));
|
||||
}
|
||||
let dir = root.join(stem);
|
||||
let mut stack = vec![dir];
|
||||
while let Some(cur) = stack.pop() {
|
||||
let Ok(entries) = std::fs::read_dir(&cur) else { continue };
|
||||
let mut paths: Vec<_> = entries.filter_map(Result::ok).map(|e| e.path()).collect();
|
||||
paths.sort();
|
||||
for path in paths {
|
||||
if path.is_dir() {
|
||||
stack.push(path);
|
||||
} else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
|
||||
let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
|
||||
if name == "tests.rs" || name.ends_with("_tests.rs") {
|
||||
continue;
|
||||
}
|
||||
if let Ok(src) = std::fs::read_to_string(&path) {
|
||||
let rel = path.strip_prefix(&root).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
out.push((rel, src));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_ui_callers_use_shared_stitch_controls() {
|
||||
let files = [
|
||||
let mut files: Vec<(String, String)> = [
|
||||
("jiansun", include_str!("jiansun.rs")),
|
||||
("account_dialog", include_str!("jiansun/account_dialog.rs")),
|
||||
("agent_canvas_read", include_str!("jiansun/agent_canvas_read.rs")),
|
||||
("agent_motion", include_str!("jiansun/agent_motion.rs")),
|
||||
("agent_native", include_str!("jiansun/agent_native.rs")),
|
||||
("agent_panel", include_str!("jiansun/agent_panel.rs")),
|
||||
("canvas_workspace", include_str!("jiansun/canvas_workspace.rs")),
|
||||
("composer_attachments", include_str!("jiansun/composer_attachments.rs")),
|
||||
("composer_references", include_str!("jiansun/composer_references.rs")),
|
||||
("creation_reads", include_str!("jiansun/creation_reads.rs")),
|
||||
("creation", include_str!("jiansun/creation.rs")),
|
||||
("native_copy_warnings", include_str!("jiansun/native_copy_warnings.rs")),
|
||||
("onboarding", include_str!("jiansun/onboarding.rs")),
|
||||
("pi_bridge", include_str!("jiansun/pi_bridge.rs")),
|
||||
@ -6499,7 +6563,12 @@ mod tests {
|
||||
("stitch_state", include_str!("jiansun/stitch_state.rs")),
|
||||
("stitch_kit", include_str!("jiansun/stitch_kit.rs")),
|
||||
("stitch_timeline", include_str!("jiansun/stitch_timeline.rs")),
|
||||
];
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(n, s)| (n.to_owned(), s.to_owned()))
|
||||
.collect();
|
||||
files.extend(module_tree_sources("agent_panel"));
|
||||
files.extend(module_tree_sources("creation"));
|
||||
let forbidden = ["egui::Button::", "egui::Separator::", "egui::Spinner::", "egui::Window::", "egui::ComboBox::from_", ".button(", ".small_button(", ".checkbox(", ".radio(", ".selectable_", ".spinner(", ".separator("];
|
||||
for (name, source) in files {
|
||||
let normalized = source.replace("\r\n", "\n");
|
||||
@ -6660,10 +6729,18 @@ mod tests {
|
||||
/// 第 3 批结束把全部归零并改成硬禁用。
|
||||
#[test]
|
||||
fn agent_callers_never_gain_font_size_literals() {
|
||||
for (stem, ceiling) in [("agent_panel", 33usize), ("creation", 23)] {
|
||||
let count: usize = module_tree_sources(stem)
|
||||
.into_iter()
|
||||
.map(|(_, source)| size_literals(&production_of(&source)))
|
||||
.sum();
|
||||
assert!(
|
||||
count <= ceiling,
|
||||
"{stem} grew to {count} hard-coded font sizes (ceiling {ceiling}); take the size from `theme::agent_scale::Type`"
|
||||
);
|
||||
}
|
||||
let baseline = [
|
||||
("agent_panel", include_str!("jiansun/agent_panel.rs"), 33usize),
|
||||
("canvas_workspace", include_str!("jiansun/canvas_workspace.rs"), 8),
|
||||
("creation", include_str!("jiansun/creation.rs"), 23),
|
||||
("canvas_workspace", include_str!("jiansun/canvas_workspace.rs"), 8usize),
|
||||
("jiansun", include_str!("jiansun.rs"), 0),
|
||||
("project_browser", include_str!("jiansun/project_browser.rs"), 8),
|
||||
("prompt_library_ui", include_str!("jiansun/prompt_library_ui.rs"), 8),
|
||||
@ -6688,9 +6765,8 @@ mod tests {
|
||||
/// `panel_geometry` 的字符串键是外部 QA 脚本与 `jiansun.state` 控制通道的契约,只许原样保留。
|
||||
#[test]
|
||||
fn panel_geometry_keys_keep_their_names_for_the_external_qa_contract() {
|
||||
let writers = [
|
||||
let mut writers: Vec<String> = [
|
||||
include_str!("jiansun.rs"),
|
||||
include_str!("jiansun/agent_panel.rs"),
|
||||
include_str!("jiansun/canvas_workspace.rs"),
|
||||
include_str!("jiansun/composer_attachments.rs"),
|
||||
include_str!("jiansun/visual_preview_ui.rs"),
|
||||
@ -6698,11 +6774,15 @@ mod tests {
|
||||
include_str!("jiansun/workflow_export.rs"),
|
||||
include_str!("jiansun/workspace_navigation.rs"),
|
||||
include_str!("jiansun/production_controls.rs"),
|
||||
];
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
writers.extend(module_tree_sources("agent_panel").into_iter().map(|(_, s)| s));
|
||||
let marker = "panel_geometry[\"";
|
||||
let mut found = std::collections::BTreeSet::new();
|
||||
for source in writers {
|
||||
let production = production_of(source);
|
||||
let production = production_of(&source);
|
||||
let mut rest = production.as_str();
|
||||
while let Some(at) = rest.find(marker) {
|
||||
let tail = &rest[at + marker.len()..];
|
||||
@ -6717,6 +6797,30 @@ mod tests {
|
||||
assert!(found.is_empty(), "new panel_geometry keys are not registered: {found:?}");
|
||||
}
|
||||
|
||||
/// 无头子模块(`agent_panel/`、`creation/` 下非 `*_ui.rs`)不得直接依赖 `egui::` 绘制接口。
|
||||
#[test]
|
||||
fn headless_submodules_do_not_use_egui_drawing() {
|
||||
for stem in ["agent_panel", "creation"] {
|
||||
for (rel, source) in module_tree_sources(stem) {
|
||||
if !rel.contains('/') || rel.ends_with("_ui.rs") {
|
||||
continue;
|
||||
}
|
||||
for (idx, line) in production_of(&source).lines().enumerate() {
|
||||
if !line.contains("egui::") {
|
||||
continue;
|
||||
}
|
||||
let allowed = line.contains("ctx: &egui::Context")
|
||||
|| line.contains("ctx.request_repaint")
|
||||
|| line.contains("egui::ViewportId::ROOT")
|
||||
|| line.contains("egui::ColorImage")
|
||||
|| line.contains("egui::Id")
|
||||
|| line.trim() == "use egui::{Id, Rect};";
|
||||
assert!(allowed, "{rel}:{} uses disallowed egui:: in headless module: {line}", idx + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 白标:组件库与状态模型里带中文的文案行,不得出现实现方的产品名。
|
||||
#[test]
|
||||
fn agent_library_copy_never_names_the_implementation_products() {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,314 @@
|
||||
use super::super::RichText;
|
||||
use egui::Stroke;
|
||||
use super::super::{Tokens, Ui, Value, Workspace, json};
|
||||
use egui::{Color32, Id, Layout, Rect, Vec2, vec2};
|
||||
use egui::Sense;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(in crate::jiansun) struct ArtifactPreviewSnapshot {
|
||||
pub(in crate::jiansun) scope: String,
|
||||
pub(in crate::jiansun) key: String,
|
||||
pub(in crate::jiansun) texture: egui::TextureHandle,
|
||||
pub(in crate::jiansun) view: ArtifactPreviewView,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(in crate::jiansun) struct ArtifactPreviewView {
|
||||
pub(in crate::jiansun) zoom: Option<f32>,
|
||||
pub(in crate::jiansun) center: Vec2,
|
||||
pub(in crate::jiansun) drag_position: Option<egui::Pos2>,
|
||||
}
|
||||
|
||||
impl Default for ArtifactPreviewView {
|
||||
fn default() -> Self { Self { zoom: None, center: Vec2::splat(0.5), drag_position: None } }
|
||||
}
|
||||
|
||||
impl ArtifactPreviewView {
|
||||
pub(in crate::jiansun) fn scale(&self, viewport: Vec2, image: Vec2, pixels_per_point: f32) -> f32 {
|
||||
self.zoom.map_or((viewport.x / image.x).min(viewport.y / image.y).min(1.0 / pixels_per_point), |zoom| zoom / pixels_per_point)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn zoom_at(&mut self, zoom: f32, at: Vec2, viewport: Vec2, image: Vec2, pixels_per_point: f32) {
|
||||
let old = self.scale(viewport, image, pixels_per_point);
|
||||
let fit = (viewport.x / image.x).min(viewport.y / image.y).min(1.0 / pixels_per_point);
|
||||
self.zoom = Some(zoom.clamp(fit * pixels_per_point, 4.0));
|
||||
let new = self.scale(viewport, image, pixels_per_point);
|
||||
self.center += at / image * (1.0 / old - 1.0 / new);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn image_preview_button(ui: &mut Ui, rect: Rect, key: &str) -> egui::Response {
|
||||
let button = Rect::from_min_size(rect.right_top() + vec2(-34.0, 6.0), vec2(28.0, 28.0));
|
||||
let response = preview_icon_at(ui, button, key, "maximize-2", "放大预览");
|
||||
if response.clicked() {
|
||||
ui.data_mut(|data| data.insert_temp(Id::unique("jiansun-image-expanded"), key.to_owned()));
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn preview_icon_at(ui: &mut Ui, rect: Rect, key: &str, icon: &str, label: &str) -> egui::Response {
|
||||
let mut controls = ui.new_child(egui::UiBuilder::new().id_salt(("preview-control", key)).max_rect(rect)
|
||||
.layout(Layout::top_down(egui::Align::Min)));
|
||||
controls.set_clip_rect(ui.clip_rect().intersect(rect));
|
||||
let mut frame = egui::Frame::NONE.corner_radius(8).begin(&mut controls);
|
||||
let response = super::stitch_ui::icon_action_button(&mut frame.content_ui, icon, label, true, 28.0, true);
|
||||
frame.frame.fill = Color32::from_black_alpha(if response.hovered() { 230 } else { 185 });
|
||||
frame.end(&mut controls);
|
||||
response.on_hover_text(label)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn preview_neighbors<'a>(workflow: &'a Value, key: &str) -> (Option<&'a str>, Option<&'a str>) {
|
||||
for slot in workflow["slots"].as_array().into_iter().flatten() {
|
||||
let mut keys = slot["candidates"].as_array().into_iter().flatten()
|
||||
.filter(|candidate| candidate["status"] == "complete")
|
||||
.filter_map(|candidate| candidate.get("taskId").unwrap_or(&candidate["id"]).as_str());
|
||||
let mut previous = None;
|
||||
while let Some(candidate) = keys.next() {
|
||||
if candidate == key { return (previous, keys.next()); }
|
||||
previous = Some(candidate);
|
||||
}
|
||||
}
|
||||
(None, None)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn artifact_preview_contents(ui: &mut Ui, texture: &egui::TextureHandle, view: &mut ArtifactPreviewView, rect: Rect) {
|
||||
let image = texture.size_vec2();
|
||||
let viewport = rect.size();
|
||||
let pixels_per_point = ui.ctx().pixels_per_point();
|
||||
let response = ui.interact(rect, ui.scope_id().with("preview-image"), Sense::click_and_drag());
|
||||
let response = response.on_hover_text("滚轮缩放 · 拖动查看 · 双击适应窗口");
|
||||
if response.double_clicked() { *view = ArtifactPreviewView::default(); }
|
||||
if response.hovered() && ui.is_enabled() {
|
||||
let (scroll, pinch) = ui.input_mut(|input| {
|
||||
let values = (input.smooth_scroll_delta.y, input.zoom_delta());
|
||||
input.smooth_scroll_delta = Vec2::ZERO;
|
||||
values
|
||||
});
|
||||
let factor = if pinch != 1.0 { pinch } else { (scroll * 0.005).exp() };
|
||||
if factor != 1.0 {
|
||||
let zoom = view.scale(viewport, image, pixels_per_point) * pixels_per_point * factor;
|
||||
view.zoom_at(zoom, response.hover_pos().unwrap_or(rect.center()) - rect.center(), viewport, image, pixels_per_point);
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
let scale = view.scale(viewport, image, pixels_per_point);
|
||||
if ui.is_enabled() {
|
||||
ui.input(|input| {
|
||||
for event in &input.events {
|
||||
match event {
|
||||
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } if rect.contains(*pos) => view.drag_position = Some(*pos),
|
||||
egui::Event::PointerMoved(pos) => {
|
||||
if let Some(previous) = view.drag_position {
|
||||
view.center -= (*pos - previous) / (image * scale);
|
||||
view.drag_position = Some(*pos);
|
||||
}
|
||||
}
|
||||
egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, .. } | egui::Event::PointerGone => view.drag_position = None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
} else { view.drag_position = None; }
|
||||
let half = (viewport / (image * scale) * 0.5).min(Vec2::splat(0.5));
|
||||
view.center = view.center.clamp(half, Vec2::splat(1.0) - half);
|
||||
let can_pan = image.x * scale > viewport.x + 0.5 || image.y * scale > viewport.y + 0.5;
|
||||
if can_pan {
|
||||
let cursor = if view.drag_position.is_some() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab };
|
||||
response.on_hover_cursor(cursor);
|
||||
}
|
||||
let painter = ui.painter_at(rect.intersect(ui.clip_rect()));
|
||||
painter.image(texture.id(), Rect::from_min_size(rect.center() - view.center * image * scale, image * scale),
|
||||
Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn artifact_preview_zoom_bar(ui: &mut Ui, texture: &egui::TextureHandle, view: &mut ArtifactPreviewView, viewport: Vec2, loading: bool, reduced: bool) {
|
||||
let image = texture.size_vec2();
|
||||
let pixels_per_point = ui.ctx().pixels_per_point();
|
||||
let zoom = view.scale(viewport, image, pixels_per_point) * pixels_per_point;
|
||||
let fit = ArtifactPreviewView::default().scale(viewport, image, pixels_per_point) * pixels_per_point;
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
egui::Frame::NONE.fill(t.field).stroke(Stroke::new(1.0, t.field_border)).corner_radius(18)
|
||||
.inner_margin(egui::Margin::symmetric(8, 0)).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
use super::stitch_ui::{ButtonRole, action_button, icon_action_button};
|
||||
ui.spacing_mut().item_spacing.x = 3.0;
|
||||
ui.spacing_mut().button_padding.x = 5.0;
|
||||
if action_button(ui, "适应窗口", ButtonRole::Quiet, true).clicked() {
|
||||
*view = ArtifactPreviewView::default();
|
||||
}
|
||||
if action_button(ui, "原始大小", ButtonRole::Quiet, true).clicked() {
|
||||
view.zoom_at(1.0, Vec2::ZERO, viewport, image, pixels_per_point);
|
||||
}
|
||||
if icon_action_button(ui, "minus", "缩小预览", true, 28.0, zoom > fit + 0.001).on_hover_text("缩小预览").clicked() {
|
||||
view.zoom_at(zoom / 1.25, Vec2::ZERO, viewport, image, pixels_per_point);
|
||||
}
|
||||
if icon_action_button(ui, "plus", "放大预览", true, 28.0, zoom < 4.0).on_hover_text("放大预览").clicked() {
|
||||
view.zoom_at(zoom * 1.25, Vec2::ZERO, viewport, image, pixels_per_point);
|
||||
}
|
||||
let percent = format!("{:.0}%", view.scale(viewport, image, pixels_per_point) * pixels_per_point * 100.0);
|
||||
ui.add_sized(vec2(38.0, 28.0), egui::Label::new(RichText::new(percent).weak()).truncate());
|
||||
if loading {
|
||||
super::stitch_ui::ai_loader(ui, ui.scope_id().with("artifact-preview-loading"), true, reduced);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn image_location(value: &Value, id: &str) -> Value {
|
||||
let mut target = json!({"kind":"candidate","taskId":id,"candidateId":id});
|
||||
for key in ["slotId", "productVariantId", "outputId", "documentId", "nativeLayerId"] {
|
||||
if let Some(field) = value.get(key).filter(|field| !field.is_null())
|
||||
.or_else(|| value["target"].get(key).filter(|field| !field.is_null())) {
|
||||
target[key] = field.clone();
|
||||
}
|
||||
}
|
||||
if value["variantId"].is_string() && !target["productVariantId"].is_string() {
|
||||
target["productVariantId"] = value["variantId"].clone();
|
||||
}
|
||||
if let Some(candidate) = value["candidateId"].as_str().or_else(|| value["target"]["candidateId"].as_str()) {
|
||||
target["candidateId"] = json!(candidate);
|
||||
}
|
||||
target
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn image_reference_target(value: &Value, id: &str, label: &str, original: bool) -> Value {
|
||||
let mut target = json!({"taskId":id,"label":label});
|
||||
for key in ["documentId", "nativeLayerId", "slotId", "fieldId", "candidateId", "outputId",
|
||||
"productVariantId", "pageId", "status", "source"] {
|
||||
let field = value.get(key).filter(|field| !field.is_null())
|
||||
.or_else(|| if original { None } else { value["target"].get(key) });
|
||||
if let Some(field) = field { target[key] = field.clone(); }
|
||||
}
|
||||
if target["productVariantId"].is_null() {
|
||||
target["productVariantId"] = value["variantId"].clone();
|
||||
}
|
||||
target["kind"] = json!(if original { "template-image" }
|
||||
else if target["slotId"].is_string() || target["candidateId"].is_string() { "candidate" }
|
||||
else { "image" });
|
||||
if target["kind"] == "candidate" && target["candidateId"].is_null() {
|
||||
target["candidateId"] = json!(id);
|
||||
}
|
||||
target
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn activate_reference(ui: &mut Ui, reference: &Value, preview: Option<&str>) -> Option<Value> {
|
||||
if reference["slotId"].is_string() || reference["nativeLayerId"].is_number() {
|
||||
return Some(reference.clone());
|
||||
}
|
||||
if let Some(id) = preview.or_else(|| reference["taskId"].as_str()) {
|
||||
ui.data_mut(|data| data.insert_temp(Id::unique("jiansun-image-expanded"), id.to_owned()));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Match explicit identities only: a reused slot or a similar label alone is
|
||||
/// never enough to identify an earlier response.
|
||||
pub(in crate::jiansun) fn candidate_matches_message(target: &Value, image: &Value) -> bool {
|
||||
let saved = &image["target"];
|
||||
let mut identity = false;
|
||||
for key in ["candidateId", "taskId", "run"] {
|
||||
let requested = target[key].as_str().filter(|value| !value.is_empty());
|
||||
let recorded = image[key].as_str().or_else(|| saved[key].as_str()).filter(|value| !value.is_empty());
|
||||
if let Some(requested) = requested {
|
||||
if let Some(recorded) = recorded {
|
||||
if requested != recorded { return false; }
|
||||
if key != "run" { identity = true; }
|
||||
} else if key == "run" { return false; }
|
||||
}
|
||||
}
|
||||
if !identity { return false; }
|
||||
for key in ["slotId", "productVariantId", "outputId"] {
|
||||
if let (Some(requested), Some(recorded)) = (target[key].as_str(), image[key].as_str().or_else(|| saved[key].as_str()))
|
||||
&& requested != recorded { return false; }
|
||||
}
|
||||
identity
|
||||
}
|
||||
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn artifact_window(&self, ui: &mut Ui) {
|
||||
let id = Id::unique("jiansun-image-expanded");
|
||||
let snapshot_id = id.with("exit-snapshot");
|
||||
let transition_id = id.with("transition");
|
||||
let scope = json!([self.origin, self.account["id"], self.project_context["localId"], self.owner_doc]).to_string();
|
||||
let selected = ui.data(|d| d.get_temp::<String>(id));
|
||||
let mut snapshot = ui.data(|d| d.get_temp::<ArtifactPreviewSnapshot>(snapshot_id));
|
||||
if snapshot.as_ref().is_some_and(|old| old.scope != scope) {
|
||||
ui.data_mut(|d| { d.remove::<ArtifactPreviewSnapshot>(snapshot_id); d.remove::<String>(id); });
|
||||
super::stitch_ui::overlay_transition(ui.ctx(), transition_id, false, true);
|
||||
return;
|
||||
}
|
||||
if let Some(selected) = selected.as_ref() {
|
||||
self.agent_images.mark_visible(selected);
|
||||
if let Some(texture) = self.agent_images.get(selected) {
|
||||
let view = snapshot.as_ref().filter(|old| old.key == *selected).map(|old| old.view.clone()).unwrap_or_default();
|
||||
let current = ArtifactPreviewSnapshot { scope, key: selected.clone(), texture: texture.clone(), view };
|
||||
ui.data_mut(|d| d.insert_temp(snapshot_id, current.clone()));
|
||||
snapshot = Some(current);
|
||||
} else if snapshot.is_none() {
|
||||
if ui.input(|input| input.key_pressed(egui::Key::Escape)) {
|
||||
ui.data_mut(|data| data.remove::<String>(id));
|
||||
}
|
||||
super::stitch_ui::overlay_transition(ui.ctx(), transition_id, false, true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
let visual = super::stitch_ui::overlay_transition(ui.ctx(), transition_id, selected.is_some(), self.reduce_motion);
|
||||
if !visual.render {
|
||||
ui.data_mut(|d| d.remove::<ArtifactPreviewSnapshot>(snapshot_id));
|
||||
return;
|
||||
}
|
||||
if let Some(saved) = snapshot.as_mut() {
|
||||
self.agent_images.mark_visible_existing(&saved.key);
|
||||
let texture = &saved.texture;
|
||||
let screen = ui.ctx().content_rect();
|
||||
let image = texture.size_vec2();
|
||||
let available = (screen.size() - vec2(104.0, 112.0)).max(Vec2::splat(1.0));
|
||||
let viewport = image * ArtifactPreviewView::default().scale(available, image, ui.ctx().pixels_per_point());
|
||||
let (previous, next) = preview_neighbors(&self.template_workflow, &saved.key);
|
||||
let loading = selected.as_ref().is_some_and(|key| *key != saved.key);
|
||||
let mut close = false;
|
||||
let mut switch = None;
|
||||
let modal = egui::Modal::new(id.with("lightbox"))
|
||||
.frame(egui::Frame::NONE)
|
||||
.backdrop_color(Color32::from_black_alpha((208.0 * visual.opacity) as u8))
|
||||
.show(ui.ctx(), |ui| {
|
||||
let size = vec2((viewport.x + 80.0).max(260.0), viewport.y + 84.0);
|
||||
let (body, _) = ui.allocate_exact_size(size, Sense::hover());
|
||||
super::stitch_ui::overlay_contents(ui, visual, |ui| {
|
||||
let photo = Rect::from_center_size(egui::pos2(body.center().x, body.top() + 36.0 + viewport.y / 2.0), viewport);
|
||||
artifact_preview_contents(ui, texture, &mut saved.view, photo);
|
||||
let close_rect = Rect::from_min_size(body.right_top() - vec2(28.0, 0.0), Vec2::splat(28.0));
|
||||
close = preview_icon_at(ui, close_rect, "close", "x", "关闭预览").clicked();
|
||||
for (key, x, icon, label, shortcut) in [
|
||||
(previous, photo.left() - 24.0, "chevron-left", "上一张", egui::Key::ArrowLeft),
|
||||
(next, photo.right() + 24.0, "chevron-right", "下一张", egui::Key::ArrowRight),
|
||||
] {
|
||||
if let Some(key) = key {
|
||||
let rect = Rect::from_center_size(egui::pos2(x, photo.center().y), Vec2::splat(28.0));
|
||||
if preview_icon_at(ui, rect, icon, icon, label).clicked()
|
||||
|| (ui.is_enabled() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, shortcut))) {
|
||||
switch = Some(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
let width = if loading { 274.0 } else { 252.0 };
|
||||
let bar = Rect::from_center_size(egui::pos2(photo.center().x, photo.bottom() + 29.0), vec2(width, 38.0));
|
||||
let mut controls = ui.new_child(egui::UiBuilder::new().id_salt("zoom-bar").max_rect(bar)
|
||||
.layout(Layout::top_down(egui::Align::Min)));
|
||||
artifact_preview_zoom_bar(&mut controls, texture, &mut saved.view, viewport, loading, self.reduce_motion);
|
||||
});
|
||||
});
|
||||
ui.data_mut(|d| d.insert_temp(snapshot_id, saved.clone()));
|
||||
if visual.interactive && (close || modal.should_close()) {
|
||||
ui.data_mut(|d| d.remove::<String>(id));
|
||||
ui.ctx().request_repaint();
|
||||
} else if let Some(key) = switch {
|
||||
ui.data_mut(|d| d.insert_temp(id, key.to_owned()));
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,226 @@
|
||||
use super::super::Instant;
|
||||
use super::turn_ui::frame_image_ratio;
|
||||
use super::super::{PhotocraftApp, Request, Value, Workspace, json, stitch_state::WorkerStage};
|
||||
use super::turns::ProductionWorker;
|
||||
use super::composer_ui::insert_suggestion;
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn fill_prompt(&mut self, prompt: &str) {
|
||||
insert_suggestion(&mut self.composer, prompt);
|
||||
self.canvas_workspace.composer_edited();
|
||||
self.image_mode = "chat".into();
|
||||
self.focus_composer = true;
|
||||
self.draft_changed = true;
|
||||
self.touched = Instant::now();
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn pending(&self) -> bool {
|
||||
matches!(
|
||||
self.busy.as_deref(),
|
||||
Some(
|
||||
"agent"
|
||||
| "agent-stopping"
|
||||
| "pi-agent"
|
||||
| "recover"
|
||||
| "image"
|
||||
| "image-recover"
|
||||
| "image-use"
|
||||
| "slot-generate"
|
||||
| "slot-append"
|
||||
| "slot-recover"
|
||||
| "slot-copy"
|
||||
)
|
||||
) || self.pi_run.is_some()
|
||||
|| self.canvas_workspace.adoption_preparing()
|
||||
|| !self.queue.is_empty()
|
||||
|| self.pending_image.is_some()
|
||||
|| (self.workflow_waiting.is_some() && self.busy.is_some())
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn result_needs_check(&self) -> bool {
|
||||
// A dispatched request is protected from replay while it is still
|
||||
// running. That protection is not a terminal unknown-result message.
|
||||
self.unknown && !self.pending() && self.product_production.is_none() && !self.product_start_queued
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn batch_progress_visible(&self) -> bool {
|
||||
!self.agent_effects_paused && (self.product_start_queued || self.product_production.is_some()
|
||||
|| self.pi_product_production && self.pending())
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_workers(&self) -> Vec<ProductionWorker<'_>> {
|
||||
let progress = self.workflow.production_progress();
|
||||
let jobs = self.pi_run.as_deref().map_or_else(Vec::new, |run| self.workflow.worker_generations(run));
|
||||
let mut used = std::collections::HashSet::new();
|
||||
let rows = progress["workers"].as_array().into_iter().flatten().map(|row| (row, false))
|
||||
.chain(progress["reviews"].as_array().into_iter().flatten().map(|row| (row, true)));
|
||||
let rows: Vec<_> = rows.filter(|(row, review)| row["active"] == true || (!review && row["step"] != "已交验图")).collect();
|
||||
let reserved: std::collections::HashSet<_> = rows.iter().filter_map(|(row, _)| row["number"].as_u64().filter(|n| *n > 0)).collect();
|
||||
let mut next = (1_u64..).filter(|n| !reserved.contains(n));
|
||||
rows.into_iter().map(|(row, review)| {
|
||||
let number = row["number"].as_u64().filter(|n| *n > 0 && used.insert(*n))
|
||||
.unwrap_or_else(|| next.next().unwrap());
|
||||
let active = row["active"] == true;
|
||||
let job = (!review && active && row["slotId"].is_string()).then(|| jobs.iter().rev().find(|job|
|
||||
job["slotId"] == row["slotId"] && job["phase"] == "submitted"
|
||||
&& (row["number"].is_null() || job["workerNumber"] == row["number"]))).flatten();
|
||||
let image_step = job.and_then(|job| job["imageStep"].as_str());
|
||||
let step = image_step.or_else(|| row["step"].as_str()).unwrap_or("");
|
||||
let stage = WorkerStage::infer(step, review, image_step.is_some());
|
||||
ProductionWorker {
|
||||
row, number, active, stage, step: step.to_owned(), review,
|
||||
slot: row["label"].as_str().unwrap_or("").to_owned(),
|
||||
frame: job.map(|job| job["imageFrame"].clone()).unwrap_or_default(),
|
||||
}
|
||||
}).collect()
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn projected_worker_jobs(&self) -> Vec<Value> {
|
||||
if self.product_start_queued || self.product_production.as_ref().is_some_and(|run| !run.showing_agent_progress()) {
|
||||
return Vec::new();
|
||||
}
|
||||
let progress = self.workflow.production_progress();
|
||||
let current = self.messages.iter().rposition(|row| row["role"] == "user").map_or(&self.messages[..], |i| &self.messages[i..]);
|
||||
self.production_workers().into_iter().filter_map(|worker| {
|
||||
if !worker.active || worker.stage != WorkerStage::Generating { return None; }
|
||||
let slot_id = &worker.row["slotId"];
|
||||
if current.iter().any(|image| image["kind"] == "image-job" && image["finished"].is_null()
|
||||
&& self.pi_run.as_deref().is_some_and(|run| image["run"] == run)
|
||||
&& if slot_id.is_string() && image["target"]["slotId"].is_string() {
|
||||
image["target"]["slotId"] == *slot_id
|
||||
&& (worker.row["number"].is_null() || image["workerNumber"].is_null() || image["workerNumber"] == worker.row["number"])
|
||||
&& (image["target"]["outputId"].is_null() || progress["outputId"].is_null() || image["target"]["outputId"] == progress["outputId"])
|
||||
&& (image["target"]["productVariantId"].is_null() || progress["variantId"].is_null()
|
||||
|| image["target"]["productVariantId"] == progress["variantId"])
|
||||
} else {
|
||||
image["workerNumber"] == worker.number
|
||||
}) { return None; }
|
||||
let frame = [Some(&worker.frame), Some(worker.row), worker.row.get("imageFrame"),
|
||||
self.template_workflow["slots"].as_array().into_iter().flatten().find(|slot|
|
||||
slot["id"] == *slot_id && (progress["outputId"].is_null() || slot["outputId"] == progress["outputId"])
|
||||
&& (progress["variantId"].is_null() || slot["variantId"].is_null() || slot["variantId"] == progress["variantId"]))
|
||||
.map(|slot| &slot["frame"])]
|
||||
.into_iter().flatten().find(|frame| frame_image_ratio(frame).is_some());
|
||||
Some(json!({
|
||||
"kind":"image-job", "taskId":format!("worker-preview-{}", worker.number), "projected":true,
|
||||
"workerNumber":worker.number, "slotLabel":worker.slot,
|
||||
"width":frame.map(|frame| &frame["width"]), "height":frame.map(|frame| &frame["height"]),
|
||||
}))
|
||||
}).collect()
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn production_assets(&self) -> impl Iterator<Item = &Value> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
self.messages.iter().filter(move |message|
|
||||
matches!(message["kind"].as_str(), Some("image" | "template-image"))
|
||||
&& message["taskId"].as_str().is_some_and(|task| seen.insert(task)))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn open_generated_folder(&mut self, doc: u64) {
|
||||
let action = json!({"doc":doc,"accountId":self.account["id"],"origin":self.origin});
|
||||
let result = self.tx.send(Request::Action("open-generated-folder".into(), action));
|
||||
self.canvas_workspace.generated_folder_status = Some((doc, if result.is_ok() {
|
||||
"正在查找本地生成图…".into()
|
||||
} else {
|
||||
"本机服务暂不可用,请稍后再试。".into()
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn can_send(&self, app: &PhotocraftApp) -> bool {
|
||||
self.can_send_with(app, self.image_mode != "chat")
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn can_send_with(&self, app: &PhotocraftApp, image: bool) -> bool {
|
||||
if !image && self.can_steer(app) { return true; }
|
||||
if !image && self.has_paused_production() && self.turn_idle() {
|
||||
return self.can_resume_product() && self.composer_draft_ready(app)
|
||||
&& !self.library_blocked() && !self.composer.trim().is_empty();
|
||||
}
|
||||
let target_ready = !image
|
||||
|| self.template_workflow["canvasFirst"] != true
|
||||
|| (self.template_workflow["capabilities"]["imageDispatchAllowed"] == true
|
||||
&& self.canvas_workspace.context.as_ref().is_some_and(|target| {
|
||||
target["kind"] != "selection"
|
||||
&& target["productVariantId"] == self.canvas_workspace.variant
|
||||
&& target["slotId"]
|
||||
.as_str()
|
||||
.filter(|id| !id.is_empty())
|
||||
.is_some_and(|id| self.template_workflow["slots"].as_array().into_iter().flatten().any(|slot| slot["id"] == id))
|
||||
}));
|
||||
!self.professional_child_active(app) && self.composer_draft_ready(app)
|
||||
&& !self.library_blocked()
|
||||
&& (image || self.composer_text_send_allowed_for(app))
|
||||
&& target_ready
|
||||
&& self.can_start_turn()
|
||||
&& !self.pi_review
|
||||
&& (if image { self.image_ready } else { self.model_ready })
|
||||
&& !self.composer.trim().is_empty()
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn send_discussion(&mut self, app: &PhotocraftApp) {
|
||||
if !self.can_steer(app) && !self.has_paused_production() && !self.composer_text_send_allowed_for(app) {
|
||||
self.error = "当前对话模型暂不支持图片,请先移除附件或使用生图".into();
|
||||
return;
|
||||
}
|
||||
if self.can_send_with(app, false) {
|
||||
self.image_mode = "chat".into();
|
||||
self.send_composer(app);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn send_image_once(&mut self, app: &PhotocraftApp) {
|
||||
if self.can_send_with(app, true) {
|
||||
if self.template_workflow["canvasFirst"] == true {
|
||||
// The canvas-first workspace owns its immutable candidate
|
||||
// append and ACK. Never route this to the legacy replacement.
|
||||
if let Err(error) = self.canvas_generate_selected(app) {
|
||||
self.error = error;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// This is an explicit one-shot action. Ordinary Send/Ctrl+Enter
|
||||
// always discuss through Pi; a previous image action is not a mode
|
||||
// that can silently turn the next user message into a paid image.
|
||||
if self.image_mode != "regenerate" {
|
||||
self.image_mode = "generate".into();
|
||||
}
|
||||
self.send_composer(app);
|
||||
self.image_mode = "chat".into();
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn send_composer(&mut self, app: &PhotocraftApp) {
|
||||
if !self.can_send(app) {
|
||||
return;
|
||||
}
|
||||
let text = self.composer.clone();
|
||||
if self.image_mode == "chat" {
|
||||
if self.can_steer(app) {
|
||||
if self.steer(app, text, "steer") {
|
||||
self.composer.clear();
|
||||
self.draft_changed = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.has_paused_production() && self.turn_idle() {
|
||||
self.resume_product_production_with(app, Some(text));
|
||||
if !self.has_paused_production() {
|
||||
self.composer.clear();
|
||||
self.draft_changed = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.submit(app, text);
|
||||
} else {
|
||||
self.generate(app, text, &self.image_mode.clone());
|
||||
}
|
||||
// Preflight errors keep the user's draft available to correct and resubmit deliberately.
|
||||
if matches!(self.busy.as_deref(), Some("agent" | "pi-agent" | "image")) {
|
||||
self.composer.clear();
|
||||
self.draft_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,677 @@
|
||||
use super::super::{Arc, CenterView, Instant, LayerContent, PhotocraftApp, RichText, Tokens, Ui, Value, Workspace, agent_motion, json, prompt_library_ui, stitch_timeline as timeline};
|
||||
use super::{CONTINUE_PRODUCTION, rect_value};
|
||||
use super::model_picker_ui::context_meter;
|
||||
use super::models::{context_for_model, context_fraction};
|
||||
use super::notifications::{AgentNotifications, notification_id, toast_id};
|
||||
use super::notifications_ui::{draw_draft_toast, post_draft_toast};
|
||||
use super::reference_shelf_ui::reference_shelf_height;
|
||||
use super::turn_ui::icon;
|
||||
use super::turns::{conversation_settled, turns};
|
||||
use egui::{Align, Color32, FontId, Frame, Id, Layout, Rect, Response, Sense, Stroke, Vec2, vec2};
|
||||
|
||||
pub(in crate::jiansun) fn copy_visible_text(ui: &mut Ui, text: &str, label: &str) -> Response {
|
||||
let response = super::stitch_ui::icon_button(ui, "copy", 24.0, false, label);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
|
||||
if response.clicked() { ui.ctx().copy_text(text.to_owned()); }
|
||||
response
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn copy_reply(ui: &mut Ui, text: &str) -> Response {
|
||||
copy_visible_text(ui, text, "复制这条回复")
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn has_comparable_candidates(workflow: &Value, subject: &Value) -> bool {
|
||||
let (Some(slot_id), Some(variant)) = (subject["slotId"].as_str().filter(|s| !s.is_empty()), subject["productVariantId"].as_str().filter(|s| !s.is_empty())) else {
|
||||
return false;
|
||||
};
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
for slot in workflow["slots"].as_array().into_iter().flatten().filter(|slot| {
|
||||
slot["id"] == slot_id && (slot["variantId"].is_null() || slot["variantId"] == variant)
|
||||
}) {
|
||||
for candidate in slot["candidates"].as_array().into_iter().flatten() {
|
||||
let candidate_variant = candidate["variantId"].as_str().or_else(|| candidate["variant"].as_str());
|
||||
let same_variant = candidate_variant == Some(variant) || (candidate_variant.is_none() && slot["variantId"] == variant);
|
||||
if same_variant && candidate["status"] == "complete" && let Some(id) = candidate["id"].as_str().filter(|id| !id.is_empty()) {
|
||||
ids.insert(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
ids.len() >= 2
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn insert_suggestion(draft: &mut String, prompt: &str) {
|
||||
if draft.trim().is_empty() {
|
||||
*draft = prompt.to_owned();
|
||||
} else {
|
||||
if !draft.ends_with('\n') { draft.push('\n'); }
|
||||
draft.push_str(prompt);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn composer_galley(ui: &Ui, text: &str, width: f32) -> Arc<egui::Galley> {
|
||||
let mut job = egui::text::LayoutJob::simple(text.to_owned(), FontId::proportional(14.0), Tokens::get(ui.ctx()).agent().text, width);
|
||||
for section in &mut job.sections { section.format.line_height = Some(24.0); }
|
||||
ui.fonts_mut(|fonts| fonts.layout_job(job))
|
||||
}
|
||||
|
||||
|
||||
/// Read the submit key before TextEdit consumes it. IME confirmation belongs to
|
||||
/// the editor, never to the model request; repeats are consumed without dispatch.
|
||||
pub(in crate::jiansun) fn composer_enter(ui: &mut Ui, id: Id) -> bool {
|
||||
let state_id = id.with("ime-submit-guard");
|
||||
if !ui.memory(|memory| memory.has_focus(id)) {
|
||||
ui.data_mut(|data| data.remove::<(bool, u64)>(state_id));
|
||||
return false;
|
||||
}
|
||||
let frame = ui.ctx().cumulative_frame_nr();
|
||||
let (mut composing, mut confirmed) = ui.data(|data| data.get_temp::<(bool, u64)>(state_id)).unwrap_or((false, u64::MAX));
|
||||
let mut ime_event = false;
|
||||
ui.input(|input| {
|
||||
for event in &input.events {
|
||||
match event {
|
||||
egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) => {
|
||||
composing = !text.is_empty();
|
||||
ime_event = true;
|
||||
confirmed = frame;
|
||||
}
|
||||
egui::Event::Ime(egui::ImeEvent::Commit(_)) => {
|
||||
composing = false;
|
||||
ime_event = true;
|
||||
confirmed = frame;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.data_mut(|data| data.insert_temp(state_id, (composing, confirmed)));
|
||||
let blocked = composing || ime_event || confirmed != u64::MAX && frame.saturating_sub(confirmed) <= 1;
|
||||
let mut submit = false;
|
||||
ui.input_mut(|input| {
|
||||
input.events.retain(|event| {
|
||||
if let egui::Event::Key { key: egui::Key::Enter, pressed: true, repeat, modifiers, .. } = event
|
||||
&& !modifiers.shift
|
||||
&& !modifiers.alt
|
||||
{
|
||||
submit |= !blocked && !repeat;
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
});
|
||||
submit
|
||||
}
|
||||
|
||||
|
||||
impl Workspace {
|
||||
/// What the canvas holds for the suggestion row: selected text, and a
|
||||
/// selected object.
|
||||
pub(in crate::jiansun) fn suggestion_scope(&self, app: &PhotocraftApp) -> (bool, bool) {
|
||||
let has_text = app
|
||||
.session
|
||||
.active()
|
||||
.is_some_and(|s| s.selected_layers().iter().any(|id| matches!(s.doc.layer(*id).map(|l| &l.content), Some(LayerContent::Text(_)))));
|
||||
let selected = self.canvas_workspace.context.as_ref().is_some_and(|context| context["kind"] != "project");
|
||||
(has_text, selected)
|
||||
}
|
||||
|
||||
/// Suggestions follow what the canvas holds: selected text, a selected
|
||||
/// object, or nothing. Choosing one only fills the composer.
|
||||
pub(in crate::jiansun) fn suggestion_prompts(&self, has_text: bool, selected: bool) -> [(&'static str, &'static str); 2] {
|
||||
let suggestions = if has_text {
|
||||
[("精简文案", "请精简当前选中的文字,保留原有事实和语气。"), ("检查排版", "请检查当前文字的层级和间距,先讨论调整建议。")]
|
||||
} else if selected {
|
||||
let compare = self.canvas_workspace.context.as_ref().is_some_and(|subject| has_comparable_candidates(&self.template_workflow, subject));
|
||||
[
|
||||
("讨论选中对象", "请结合当前选中的对象讨论可以改进的地方,先不要自动生成或替换。"),
|
||||
if compare {
|
||||
("比较候选", "请比较当前图位的已有候选,说明各自特点,不自动采纳。")
|
||||
} else {
|
||||
("讨论调整方向", "请结合选中对象和项目资料,先讨论可以调整的方向。")
|
||||
},
|
||||
]
|
||||
} else {
|
||||
[
|
||||
("梳理资料", "请读取当前项目资料,梳理已有事实和需要补充的内容。"),
|
||||
("讨论页面", "请结合项目模板和产品资料,和我讨论页面的重点与安排。"),
|
||||
]
|
||||
};
|
||||
suggestions
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn suggestion_row(&mut self, app: &PhotocraftApp, ui: &mut Ui, key: &str, suggestions: [(&'static str, &'static str); 2], resume_production: Option<bool>, size: super::agent_stream::SuggestionSize, wrap: bool) {
|
||||
use super::agent_stream::{SUGGESTION_CHIP_HEIGHT, SUGGESTION_GAP, suggestion_chip};
|
||||
let mut rects = Vec::new();
|
||||
let draft_ready = self.composer_draft_ready(app);
|
||||
let layout = egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(wrap);
|
||||
ui.allocate_ui_with_layout(vec2(ui.available_width(), SUGGESTION_CHIP_HEIGHT), layout, |ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(SUGGESTION_GAP, SUGGESTION_GAP);
|
||||
if let Some(enabled) = resume_production {
|
||||
let hint = "按图位完成剩余图片,保留已采纳结果和现有图层";
|
||||
let response = suggestion_chip(ui, "sparkles", CONTINUE_PRODUCTION, enabled, self.reduce_motion, size)
|
||||
.on_hover_text(hint).on_disabled_hover_text(hint);
|
||||
rects.push(json!({"label":CONTINUE_PRODUCTION,"rect":rect_value(response.rect)}));
|
||||
if response.clicked() {
|
||||
self.resume_product_production(app);
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
let items = suggestions.map(|(label, _)| ("sparkles", label));
|
||||
let responses = timeline::suggestion_row(ui, &items, draft_ready, self.reduce_motion, size);
|
||||
for ((label, prompt), response) in suggestions.into_iter().zip(responses) {
|
||||
let response = response.on_hover_text(prompt);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, response.enabled(), format!("填入输入框:{label}")));
|
||||
rects.push(json!({"label":label,"rect":rect_value(response.rect)}));
|
||||
if response.clicked() {
|
||||
self.fill_prompt(prompt);
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
});
|
||||
// Leave space between the shortcuts and the input surface.
|
||||
ui.add_space(6.0);
|
||||
self.panel_geometry[key] = json!(rects);
|
||||
}
|
||||
|
||||
/// Nothing has been said yet: a few lines say what 小壹 does here and
|
||||
/// where to start. They name only what this client's tools can do.
|
||||
pub(in crate::jiansun) fn empty_conversation_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let document_open = app.session.active().is_some();
|
||||
ui.add_space(24.0);
|
||||
ui.add(egui::Label::new(RichText::new("小壹可以帮你").size(14.0).strong().color(t.text)));
|
||||
ui.add_space(6.0);
|
||||
for line in ["为图位生成候选图,采纳后放进画布", "写详情页文案,并核对卖点依据", "整套制作详情、主图和 SKU"] {
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.add_space(1.0);
|
||||
ui.add(egui::Label::new(RichText::new("·").size(12.0).color(t.text_faint)));
|
||||
ui.add(egui::Label::new(RichText::new(line).size(12.0).color(t.text_dim)).wrap());
|
||||
});
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
let start = if document_open { "在下面的输入框里写下需求,或点一条建议开始。" } else { "打开一个项目后,在下面的输入框里写下需求。" };
|
||||
ui.add(egui::Label::new(RichText::new(start).size(12.0).color(t.text_faint)).wrap());
|
||||
if !document_open && super::stitch_ui::action_button(ui, "我的项目", super::stitch_ui::ButtonRole::Secondary, true).clicked() {
|
||||
self.show_center(CenterView::Projects, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Follow-ups close a settled reply. They name the next step from the
|
||||
/// reply's own receipt and never send anything by themselves.
|
||||
pub(in crate::jiansun) fn followup_prompts(&self, production: bool) -> Option<[(&'static str, &'static str); 2]> {
|
||||
if !conversation_settled(self, production) { return None; }
|
||||
let index = self.messages.iter().rposition(|message| message["text"].as_str().is_some_and(|text| !text.is_empty()))?;
|
||||
if turns(&self.messages).last().and_then(|turn| turn.last_reply.map(|(_, last)| last)) != Some(index) { return None; }
|
||||
let summary = &self.messages[index]["productionSummary"];
|
||||
Some(if summary.is_object() {
|
||||
if summary["exported"] == summary["total"] {
|
||||
[("验收整套", "请检查本轮详情、主图和 SKU 的导出结果,逐项指出需要调整的地方。"),
|
||||
("核对卖点和配图", "请核对整页的卖点与配图是否对应,列出证据不足的地方。")]
|
||||
} else {
|
||||
[("查看未完成项", "请梳理这轮未完成的文案、图位和输出,说明每项卡在哪里。"),
|
||||
("核对已有结果", "请检查目前已保留的文案和配图,指出需要调整的地方。")]
|
||||
}
|
||||
} else {
|
||||
[("展开下一步", "请把上一条建议展开为具体的下一步和验收标准。"),
|
||||
("核对依据", "请结合当前项目资料,核对上一条回复中的判断和依据。")]
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn composer_surface_height(&self, app: &PhotocraftApp, ui: &Ui, width: f32, progress: f32) -> f32 {
|
||||
let references = reference_shelf_height(self.composer_reference_list(app).len(), (width - 28.0).max(1.0));
|
||||
if progress == 0.0 {
|
||||
return 56.0 + references;
|
||||
}
|
||||
let attachment = if self.composer_text_send_allowed_for(app) { 0.0 } else { self.composer_attachments_extra_height() };
|
||||
let wrap_width = (width - 32.0).max(1.0);
|
||||
let layout_key = (wrap_width, ui.pixels_per_point(), Tokens::get(ui.ctx()).kind);
|
||||
let height_id = ui.scope_id().with("composer-draft-height");
|
||||
type DraftHeight = ((f32, f32, crate::theme::ThemeKind), String, f32);
|
||||
let cached = ui.data_mut(|data| data.remove_temp::<Option<DraftHeight>>(height_id)).flatten();
|
||||
let (key, draft, text_height) = cached
|
||||
.filter(|(key, draft, _)| *key == layout_key && draft == &self.composer)
|
||||
.unwrap_or_else(|| (layout_key, self.composer.clone(),
|
||||
composer_galley(ui, &self.composer, wrap_width).size().y.max(24.0)));
|
||||
ui.data_mut(|data| data.insert_temp(height_id, Some((key, draft, text_height))));
|
||||
let expanded = (text_height + 74.0 + attachment).max(168.0)
|
||||
.min((ui.ctx().content_rect().height() * 0.5 - references).max(168.0));
|
||||
56.0 + references + (expanded - 56.0) * progress
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn composer_notice_height(&self, ui: &Ui) -> f32 {
|
||||
let gap = 6.0;
|
||||
let row = ui.spacing().interact_size.y;
|
||||
let button = 34.0_f32.max(row);
|
||||
let mut height = 0.0;
|
||||
if self.pi_review && self.busy.is_none() { height += button + 16.0 + gap; }
|
||||
if self.result_needs_check() || (!self.pending() && self.ready_image.is_some()) { height += button + 16.0 + gap; }
|
||||
if !self.error.is_empty() && self.error != self.library_message { height += super::operation_error::inline_height(ui,&self.error,(ui.available_width()-20.0).max(1.0)) + gap; }
|
||||
if !self.needs_library_login() && !self.library_blocked() && !self.key_saved { height += button + gap; }
|
||||
height + self.steering_queue_height()
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn steering_queue_height(&self) -> f32 {
|
||||
if self.pi_run.is_none() || self.agent_effects_paused || self.loaded_draft != self.owner_doc { return 0.0; }
|
||||
let groups = usize::from(!self.pi_queued_steering.is_empty()) + usize::from(!self.pi_queued_followup.is_empty());
|
||||
if groups == 0 { 0.0 } else { (groups as f32 * 19.0).max(26.0) + 6.0 }
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn steering_queue_ui(&mut self, ui: &mut Ui) {
|
||||
let height = self.steering_queue_height();
|
||||
if height == 0.0 { return; }
|
||||
let tint = Tokens::get(ui.ctx()).agent().text_dim;
|
||||
ui.allocate_ui_with_layout(vec2(ui.available_width(), height - 6.0), Layout::right_to_left(Align::Center), |ui| {
|
||||
let clear = super::stitch_ui::icon_button(ui, "x", 26.0, false, "清空待发送消息");
|
||||
if clear.clicked() { self.clear_steer_queue(); }
|
||||
ui.vertical(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 0.0;
|
||||
for (title, messages) in [
|
||||
("待插话 · 当前步骤后注入", &self.pi_queued_steering),
|
||||
("已排队 · 本轮结束后发送", &self.pi_queued_followup),
|
||||
] {
|
||||
if messages.is_empty() { continue; }
|
||||
let preview = messages.join(" / ").replace('\n', " ");
|
||||
ui.add(egui::Label::new(RichText::new(format!("{title} {preview}")).size(12.0).color(tint)).truncate())
|
||||
.on_hover_text(format!("{title}\n{}", messages.join("\n")));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn composer_escape(&mut self, ui: &mut Ui) {
|
||||
let input_id = super::composer_input_id();
|
||||
let ime_composing = ui.data(|data| data.get_temp::<(bool, u64)>(input_id.with("ime-submit-guard")))
|
||||
.is_some_and(|(composing, _)| composing)
|
||||
|| ui.input(|input| input.events.iter().any(|event| matches!(event, egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) if !text.is_empty())));
|
||||
let owns_focus = ui.memory(|memory| memory.has_focus(input_id)
|
||||
|| (memory.focused().is_none() && memory.had_focus_last_frame(input_id)));
|
||||
if !self.model_settings && !self.prompt_library.is_open()
|
||||
&& !ime_composing && ui.memory(|memory| memory.top_modal_layer().is_none())
|
||||
&& owns_focus
|
||||
&& ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
|
||||
let mut selection = egui::text_edit::TextEditState::load(ui.ctx(), input_id);
|
||||
let range = selection.as_ref().and_then(|state| state.cursor.char_range());
|
||||
if let Some(range) = range.filter(|range| range.primary != range.secondary) {
|
||||
if let Some(state) = selection.as_mut() {
|
||||
state.cursor.set_char_range(Some(egui::text::CCursorRange::one(range.primary)));
|
||||
}
|
||||
if let Some(state) = selection { state.store(ui.ctx(), input_id); }
|
||||
} else if self.composer.is_empty() {
|
||||
self.focus_composer = false;
|
||||
ui.memory_mut(|memory| memory.surrender_focus(input_id));
|
||||
}
|
||||
if !self.composer.is_empty() { ui.memory_mut(|memory| memory.request_focus(input_id)); }
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn composer_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
super::glow_pill::bind(ui, app.gpu_render_state.as_ref());
|
||||
let messages_before_send = self.messages.len();
|
||||
let mut prompt_anchor = None;
|
||||
self.composer_reference_sync(app);
|
||||
if self.notifications_ui(ui) { self.show_center(CenterView::Canvas, app.session.active().is_some()); }
|
||||
self.composer_escape(ui);
|
||||
let input_id = super::composer_input_id();
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
ui.spacing_mut().item_spacing = vec2(6.0, 6.0);
|
||||
self.panel_geometry["productionProgress"] = Value::Null;
|
||||
self.panel_geometry["productionProgressRail"] = Value::Null;
|
||||
self.panel_geometry["productionWorkers"] = Value::Null;
|
||||
self.panel_geometry["productionShelf"] = Value::Null;
|
||||
self.panel_geometry["productionWorkersTag"] = Value::Null;
|
||||
self.panel_geometry["productionProgressTag"] = Value::Null;
|
||||
self.panel_geometry["productionImageCells"] = Value::Null;
|
||||
self.panel_geometry["productionCopyCells"] = Value::Null;
|
||||
self.panel_geometry["productionResume"] = Value::Null;
|
||||
self.panel_geometry["productionStopPause"] = Value::Null;
|
||||
self.panel_geometry["productionStopEnd"] = Value::Null;
|
||||
self.panel_geometry["productionStopDeliver"] = Value::Null;
|
||||
self.panel_geometry["productionStopStatus"] = Value::Null;
|
||||
self.panel_geometry["productionBudget"] = Value::Null;
|
||||
if self.pi_review && self.busy.is_none() {
|
||||
self.status_row(ui, "info", "原建议未执行", t.warning, |this, ui| {
|
||||
if super::stitch_ui::action_button(ui, "放弃原建议", super::stitch_ui::ButtonRole::Secondary, true).on_hover_text("保留原响应和已完成的修改;不重新运行模型或工具").clicked() {
|
||||
this.send("pi-review", json!({"doc":app.session.active().map(|s|s.doc.id.0)}));
|
||||
}
|
||||
});
|
||||
}
|
||||
self.panel_geometry["recoverResult"] = Value::Null;
|
||||
if self.result_needs_check() {
|
||||
let title = if self.original_image_recoveries().next().is_some() {
|
||||
if self.original_image_recoveries().all(|(_, id)| {
|
||||
self.image_recovery_schedules.get(id).is_some_and(|schedule| schedule.exhausted())
|
||||
}) {
|
||||
"原图片暂未取回,已保留请求"
|
||||
} else {
|
||||
"图片结果待自动核查"
|
||||
}
|
||||
}
|
||||
else if self.unknown_image { "有一张图片未确认结果" }
|
||||
else { "有一项操作未确认结果" };
|
||||
self.status_row(ui, "info", title, t.warning, |this, ui| {
|
||||
let action = super::stitch_ui::action_button(ui, "核查结果", super::stitch_ui::ButtonRole::Secondary, this.busy.is_none())
|
||||
.on_hover_text("只读取原请求结果,不重新生成");
|
||||
this.panel_geometry["recoverResult"] = rect_value(action.rect);
|
||||
if action.clicked() { this.recover(app); }
|
||||
});
|
||||
} else if !self.pending() && self.ready_image.is_some() {
|
||||
self.status_row(ui, "image", "图片已就绪", t.text_dim, |this, ui| {
|
||||
if super::stitch_ui::action_button(ui, "应用到画布", super::stitch_ui::ButtonRole::Primary, this.busy.is_none()).clicked() {
|
||||
this.use_image(app);
|
||||
}
|
||||
});
|
||||
}
|
||||
self.panel_geometry["reconnect"] = Value::Null;
|
||||
self.error_notice_ui(ui);
|
||||
self.steering_queue_ui(ui);
|
||||
self.panel_geometry["send"] = Value::Null;
|
||||
self.panel_geometry["stop"] = Value::Null;
|
||||
let shortcut = composer_enter(ui, input_id);
|
||||
let morph = self.panel_geometry["composerMorph"].as_f64().unwrap_or(1.0) as f32;
|
||||
let can_stop = self.pending() && !self.batch_progress_visible() && !self.agent_effects_paused;
|
||||
let compact_stop = can_stop && morph < 0.95;
|
||||
let surface_height = self.composer_surface_height(app, ui, ui.available_width(), morph);
|
||||
let (surface_rect, surface_response) = ui.allocate_exact_size(vec2(ui.available_width(), surface_height), Sense::hover());
|
||||
let radius = 28.0 - 4.0 * morph;
|
||||
let material = super::stitch_ui::surface_frame(ui.ctx(), super::stitch_ui::SurfaceRole::Composer);
|
||||
ui.painter().rect_filled(surface_rect, radius, material.fill);
|
||||
ui.painter().rect_stroke(surface_rect, radius, material.stroke, egui::StrokeKind::Inside);
|
||||
let drop_active = self.panel_geometry["composerExpanded"].as_bool().unwrap_or(false);
|
||||
self.composer_attachment_drop_surface(app, ui, surface_rect, radius, drop_active);
|
||||
let light = agent_motion::reserve_background(ui);
|
||||
let send_background = agent_motion::reserve_background(ui);
|
||||
let mut content = ui.new_child(egui::UiBuilder::new().id_salt("composer-stable-surface")
|
||||
.max_rect(surface_rect.shrink2(vec2(14.0, 12.0))).layout(Layout::top_down(Align::Min)));
|
||||
content.set_clip_rect(surface_rect.shrink(2.0).intersect(ui.clip_rect()));
|
||||
let parent_ui = ui;
|
||||
let ui = &mut content;
|
||||
let references = self.composer_reference_list(app);
|
||||
self.panel_geometry["references"] = json!(references);
|
||||
let reference_height = reference_shelf_height(references.len(), ui.max_rect().width());
|
||||
if reference_height > 0.0 {
|
||||
let shelf = Rect::from_min_size(ui.max_rect().min, vec2(ui.max_rect().width(), reference_height - 6.0));
|
||||
let mut reference_ui = ui.new_child(egui::UiBuilder::new().id_salt("composer-references").max_rect(shelf));
|
||||
self.reference_shelf(app, &mut reference_ui, &references, shelf.height());
|
||||
}
|
||||
let header_rect = ui.max_rect().translate(vec2(0.0, reference_height));
|
||||
let mut header = ui.new_child(egui::UiBuilder::new().id_salt("composer-header").max_rect(header_rect));
|
||||
header.set_opacity(morph * morph);
|
||||
if morph < 0.95 { header.disable(); }
|
||||
if morph > 0.001 {
|
||||
self.composer_attachment_previews(app, &mut header);
|
||||
}
|
||||
let header_height = if header.min_rect().height() > 0.0 { header.min_rect().height() + 6.0 } else { 0.0 };
|
||||
let stop_space = if compact_stop { 36.0 } else { 0.0 };
|
||||
let mini_input = Rect::from_min_size(
|
||||
egui::pos2(surface_rect.left() + 54.0, surface_rect.top() + reference_height + 17.0),
|
||||
vec2((surface_rect.width() - 72.0 - stop_space).max(1.0), 24.0),
|
||||
);
|
||||
let full_input = Rect::from_min_max(
|
||||
egui::pos2(surface_rect.left() + 16.0, surface_rect.top() + 14.0 + reference_height + header_height),
|
||||
egui::pos2(surface_rect.right() - 16.0, surface_rect.bottom() - 60.0));
|
||||
let input_rect = Rect::from_min_max(mini_input.min.lerp(full_input.min, morph), mini_input.max.lerp(full_input.max, morph));
|
||||
let typing_owner=Id::unique((&self.origin,self.account["id"].as_str(),self.observed_doc,self.loaded_draft));
|
||||
let reduced=self.reduce_motion;
|
||||
let mut layouter = |ui: &Ui, text: &dyn egui::TextBuffer, wrap_width: f32| {
|
||||
let mut galley=composer_galley(ui,text.as_str(),wrap_width);
|
||||
super::typing_text::edit(ui,typing_owner,&mut galley,reduced);
|
||||
galley
|
||||
};
|
||||
let mut input_ui = ui.new_child(egui::UiBuilder::new().id_salt("composer-input-region").max_rect(input_rect));
|
||||
input_ui.set_clip_rect(input_rect.intersect(ui.clip_rect()));
|
||||
input_ui.spacing_mut().scroll.fade.strength=0.0;
|
||||
input_ui.visuals_mut().text_cursor.stroke=Stroke::new(1.5,t.text);
|
||||
let draft_ready = self.composer_draft_ready(app);
|
||||
if !draft_ready { input_ui.disable(); }
|
||||
let text_start=ui.ctx().graphics(|graphics|graphics.get(ui.layer_id()).map_or(0,|list|list.next_idx().0));
|
||||
let resized=ui.data_mut(|data|{let id=input_id.with("viewport-size");let previous=data.get_temp::<Vec2>(id);data.insert_temp(id,input_rect.size());previous!=Some(input_rect.size())});
|
||||
let editor = egui::ScrollArea::vertical().id_salt("agent-input-scroll").animated(false)
|
||||
.max_height(input_rect.height().max(24.0)).min_scrolled_height(input_rect.height().max(24.0))
|
||||
.content_margin(egui::Margin::ZERO).auto_shrink([false, false])
|
||||
.show(&mut input_ui, |ui| {
|
||||
let hint = if !draft_ready { "正在加载项目草稿…" }
|
||||
else if self.steering_available(app) { "继续补充要求,将在当前步骤后插话…" }
|
||||
else { "告诉小壹,你想怎么改…" };
|
||||
let editor=super::stitch_ui::text_input(&mut self.composer, hint, true)
|
||||
.layouter(&mut layouter).id(input_id).return_key(egui::KeyboardShortcut::new(egui::Modifiers::SHIFT, egui::Key::Enter))
|
||||
.font(FontId::proportional(14.0)).desired_rows(1).desired_width(f32::INFINITY)
|
||||
.min_size(vec2(0.0, input_rect.height().max(24.0))).margin(egui::Margin::ZERO).frame(Frame::NONE).show(ui);
|
||||
if resized&&editor.response.response.has_focus()&&let Some(range)=editor.cursor_range {
|
||||
let caret=editor.galley.pos_from_cursor(range.primary).translate(editor.galley_pos.to_vec2());
|
||||
if !ui.clip_rect().contains_rect(caret){ui.scroll_to_rect_animation(caret,None,egui::style::ScrollAnimation::none());}
|
||||
}
|
||||
editor
|
||||
});
|
||||
self.panel_geometry["inputScrollOffset"]=json!(editor.state.unclamped_offset().y);
|
||||
let editor=editor.inner;
|
||||
self.panel_geometry["inputContentHeight"]=json!(editor.galley.size().y);
|
||||
if let Some(row)=editor.galley.rows.first(){self.panel_geometry["inputFirstRow"]=rect_value(Rect::from_min_size(editor.galley_pos+vec2(0.0,row.pos.y),vec2(input_rect.width(),row.size.y)));}
|
||||
if let Some(range) = editor.cursor_range {
|
||||
self.panel_geometry["inputCaret"] = rect_value(editor.galley.pos_from_cursor(range.primary).translate(editor.galley_pos.to_vec2()));
|
||||
}
|
||||
self.panel_geometry["inputHitRect"] = rect_value(editor.response.rect);
|
||||
let response = editor.response.response.accessible_name("小壹消息输入");
|
||||
let text_end = ui.ctx().graphics(|graphics|graphics.get(ui.layer_id()).map_or(text_start, |list| list.next_idx().0));
|
||||
// 输入框的逐字柔光画在光涌玻璃上面、文字光标下面(见 `typing_text::paint_glow`)。
|
||||
super::typing_text::paint_glow(ui,typing_owner,editor.galley_pos);
|
||||
let input_focused = response.has_focus();
|
||||
self.panel_geometry["input"] = rect_value(input_rect);
|
||||
if self.focus_composer && draft_ready { response.request_focus(); self.focus_composer = false; }
|
||||
if response.changed() {
|
||||
self.canvas_workspace.composer_edited(); self.draft_changed = true; self.touched = Instant::now();
|
||||
}
|
||||
let typing = input_focused && !self.composer.trim().is_empty() && !self.pending();
|
||||
let orb_id = Id::unique("composer-identity");
|
||||
let orb_progress = super::stitch_ui::morph_value(ui.ctx(), orb_id.with("size"), typing, self.reduce_motion);
|
||||
let orb_center = egui::pos2(surface_rect.left() + 29.0, surface_rect.center().y + reference_height / 2.0)
|
||||
.lerp(egui::pos2(surface_rect.left() + 35.0, surface_rect.bottom() - 33.0), morph);
|
||||
let orb = Rect::from_center_size(orb_center, Vec2::splat(34.0 - 10.0 * morph + 16.0 * orb_progress));
|
||||
let typing_animation = typing && super::typing_text::is_animating(ui, typing_owner);
|
||||
let background_canvas = self.product_view_detached()
|
||||
|| self.owner_doc.is_some_and(|owner| app.session.active().is_none_or(|state| state.doc.id.0 != owner));
|
||||
let working = !background_canvas && !self.agent_effects_paused && !self.pi_ui_waiting()
|
||||
&& (self.pending() || self.batch_progress_visible() && !self.has_paused_production());
|
||||
let motion = super::siri_orb::Motion::composer(self.reduce_motion, typing_animation, working);
|
||||
let freeze = self.reduce_motion || background_canvas && !typing_animation;
|
||||
let animation = super::siri_orb::paint(ui, orb_id, orb, motion, freeze);
|
||||
self.panel_geometry["composerOrb"] = rect_value(orb);
|
||||
self.panel_geometry["composerOrbTyping"] = json!(typing);
|
||||
self.panel_geometry["composerOrbMotion"] = json!(if self.reduce_motion { "reduced" } else { motion.label() });
|
||||
self.panel_geometry["composerOrbPhase"] = animation.map_or(Value::Null, |a| json!(a.phase));
|
||||
self.panel_geometry["composerOrbSpeed"] = animation.map_or(Value::Null, |a| json!(a.speed));
|
||||
let toolbar_rect = Rect::from_min_max(egui::pos2(surface_rect.left() + 14.0, surface_rect.bottom() - 54.0),
|
||||
egui::pos2(surface_rect.right() - 14.0, surface_rect.bottom() - 12.0));
|
||||
let mut toolbar = ui.new_child(egui::UiBuilder::new().id_salt("composer-toolbar").max_rect(toolbar_rect));
|
||||
toolbar.set_opacity(((morph - 0.3) / 0.7).clamp(0.0, 1.0));
|
||||
if morph < 0.95 { toolbar.disable(); }
|
||||
let can = self.can_send_with(app, false);
|
||||
let connect = (self.needs_library_login() || self.library_blocked())
|
||||
&& draft_ready && self.busy.is_none() && !self.composer.trim().is_empty();
|
||||
let mut send_clicked = false;
|
||||
if morph > 0.3 {
|
||||
let ui = &mut toolbar;
|
||||
// One responsive toolbar. Narrow docks retain every action with
|
||||
// an accessible icon; only labels collapse, never controls.
|
||||
ui.horizontal(|ui| {
|
||||
let narrow = ui.available_width() < 260.0;
|
||||
let ultra = ui.available_width() < if can_stop { 175.0 } else { 145.0 };
|
||||
let action_size = if narrow { 24.0 } else { 28.0 };
|
||||
ui.spacing_mut().item_spacing.x = if narrow { 1.0 } else { 3.0 };
|
||||
ui.spacing_mut().button_padding.x = 4.0;
|
||||
let right_width = 30.0
|
||||
+ if can_stop { 30.0 + ui.spacing().item_spacing.x } else { 0.0 }
|
||||
+ if ultra { 0.0 } else { action_size + ui.spacing().item_spacing.x };
|
||||
let left_width = (ui.available_width() - right_width - ui.spacing().item_spacing.x).max(1.0);
|
||||
let mut compact_settings_anchor = None;
|
||||
ui.allocate_ui_with_layout(vec2(left_width, 42.0), Layout::left_to_right(Align::Center), |ui| {
|
||||
ui.allocate_exact_size(vec2(if ultra { 34.0 } else { 42.0 }, 42.0), Sense::hover());
|
||||
let add = super::stitch_ui::icon_button(ui, "plus", action_size, false, "添加");
|
||||
add.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "添加"));
|
||||
self.panel_geometry["composerMore"] = rect_value(add.rect);
|
||||
self.panel_geometry["referenceImage"] = Value::Null;
|
||||
self.panel_geometry["promptLibrary"] = Value::Null;
|
||||
prompt_anchor = Some(add.rect);
|
||||
if ultra { compact_settings_anchor = Some(add.clone()); }
|
||||
egui::Popup::menu(&add).id(Id::unique("jiansun-composer-more-popup")).style(super::stitch_ui::scoped_popup_style(ui))
|
||||
.frame(super::stitch_ui::command_menu_frame(ui.ctx())).show(|ui| {
|
||||
ui.set_width(180.0);
|
||||
let selected = self.canvas_subject(app)["kind"] != "project" && self.composer_draft_ready(app);
|
||||
let reference = super::stitch_ui::command_menu_item(ui, "layers", "引用选中画布对象", selected);
|
||||
self.panel_geometry["referenceAdd"] = rect_value(reference.rect);
|
||||
if reference.clicked() {
|
||||
match self.composer_reference_add(app) { Ok(()) => self.focus_composer = true, Err(error) => self.error = error }
|
||||
ui.close();
|
||||
}
|
||||
self.composer_attachment_menu_item(app, ui);
|
||||
if super::stitch_ui::command_menu_item(ui, "folder-open", "常用提示词", true).clicked() {
|
||||
self.close_model_settings();
|
||||
self.prompt_library.toggle(&self.account, &self.origin, &self.tx); ui.close();
|
||||
}
|
||||
if ultra {
|
||||
if super::stitch_ui::command_menu_item(ui, "sparkles", "生图", self.can_send_with(app, true)).clicked() { self.send_image_once(app); ui.close(); }
|
||||
if super::stitch_ui::command_menu_item(ui, "sliders-horizontal", "连接设置、通知与警告", true).clicked() {
|
||||
self.open_model_settings();
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
if !ultra {
|
||||
let image_action = super::stitch_ui::icon_action_button(ui, "sparkles", "生图", true, action_size, self.can_send_with(app, true))
|
||||
.on_hover_text("使用生图模型提交当前要求;普通发送仍是对话");
|
||||
self.panel_geometry["imageGenerate"] = rect_value(image_action.rect);
|
||||
if image_action.clicked() { self.send_image_once(app); }
|
||||
if left_width >= 120.0 {
|
||||
let usage = context_for_model(&self.pi_context_usage, &self.models, &self.model);
|
||||
if usage.as_ref().is_some_and(|value|value["contextWindow"].as_u64().is_some_and(|limit|limit>0)) {
|
||||
let meter = context_meter(ui, usage.as_ref(), self.reduce_motion, true);
|
||||
self.panel_geometry["contextIndicator"] = rect_value(meter.rect);
|
||||
self.panel_geometry["contextPercent"] = context_fraction(usage.as_ref()).map_or(Value::Null,|fraction|json!(fraction*100.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
let response = ui
|
||||
.add_enabled_ui(can || connect, |ui| super::stitch_ui::send_action_button(ui, Id::unique("composer-send"), self.reduce_motion))
|
||||
.inner
|
||||
.on_hover_text(if connect { "连接素材库后发送" }
|
||||
else if self.can_steer(app) { "Enter 插话 · Shift+Enter 换行" }
|
||||
else { "Enter 发送 · Shift+Enter 换行" })
|
||||
.on_disabled_hover_text(if self.unknown { "先核查原请求结果" }
|
||||
else if !self.composer_text_send_allowed_for(app) { "当前对话模型暂不支持图片,请先移除附件或使用生图" }
|
||||
else { "打开项目、连接模型并输入要求后发送" });
|
||||
self.panel_geometry["send"] = rect_value(response.rect);
|
||||
send_clicked = response.clicked();
|
||||
if compact_stop {
|
||||
ui.allocate_exact_size(vec2(30.0,30.0), Sense::hover());
|
||||
} else if can_stop {
|
||||
let stop = super::stitch_ui::icon_button(ui, "square", 30.0, false, "停止小壹,保留原请求");
|
||||
self.panel_geometry["stop"] = rect_value(stop.rect);
|
||||
if stop.clicked() { self.abort_chat_run(); }
|
||||
}
|
||||
if !ultra {
|
||||
let response = super::stitch_ui::icon_button(ui, "sliders-horizontal", action_size, self.model_settings, "连接设置、通知与警告");
|
||||
let unread=notification_id(&self.origin,&self.account,&self.project_context,self.owner_doc)
|
||||
.and_then(|id|ui.data(|data|data.get_temp::<AgentNotifications>(id))).is_some_and(|history|history.unread>0);
|
||||
if unread {
|
||||
let dot=Rect::from_center_size(response.rect.right_top()+vec2(-3.0,3.0),vec2(8.0,8.0));
|
||||
super::stitch_ui::paint_badge(ui,response.id.with("unread"),dot,super::stitch_ui::BadgeKind::Unread,"",self.reduce_motion);
|
||||
}
|
||||
self.panel_geometry["settings"] = rect_value(response.rect);
|
||||
if response.clicked() {
|
||||
if self.model_settings {
|
||||
self.close_model_settings();
|
||||
} else {
|
||||
self.open_model_settings();
|
||||
}
|
||||
}
|
||||
self.model_settings_popup(ui, &response);
|
||||
}
|
||||
});
|
||||
if let Some(anchor) = compact_settings_anchor { self.model_settings_popup(ui, &anchor); }
|
||||
});
|
||||
}
|
||||
if send_clicked || (shortcut && (can || connect)) {
|
||||
if connect { self.open_library_login(); }
|
||||
else { self.send_discussion(app); }
|
||||
}
|
||||
// 设置浮层里点的"检查更新"在这里派发:浮层本身拿不到 app。
|
||||
self.flush_client_update_request(app);
|
||||
let compact_stop_rect = Id::unique("jiansun-composer-compact-stop-rect");
|
||||
if compact_stop {
|
||||
let compact_center = egui::pos2(surface_rect.right() - 27.0, mini_input.center().y);
|
||||
let expanded_center = egui::pos2(toolbar_rect.right() - 48.0, toolbar_rect.center().y);
|
||||
let rect = Rect::from_center_size(compact_center.lerp(expanded_center,morph),vec2(30.0,30.0));
|
||||
let mut control = ui.new_child(egui::UiBuilder::new().id_salt("composer-compact-stop").max_rect(rect));
|
||||
let stop = super::stitch_ui::icon_button(&mut control, "square", 30.0, false, "停止小壹,保留原请求");
|
||||
self.panel_geometry["stop"] = rect_value(stop.rect);
|
||||
ui.data_mut(|data| data.insert_temp(compact_stop_rect, stop.rect));
|
||||
if stop.clicked() { self.abort_chat_run(); }
|
||||
} else {
|
||||
ui.data_mut(|data| data.remove::<Rect>(compact_stop_rect));
|
||||
}
|
||||
let ui = parent_ui;
|
||||
let frame = egui::InnerResponse { inner: light, response: surface_response };
|
||||
self.panel_geometry["composer"] = rect_value(frame.response.rect);
|
||||
ui.ctx().data_mut(|data| data.insert_temp(Id::unique("jiansun-composer-previous-rect"), frame.response.rect));
|
||||
self.panel_geometry["composerFocused"] = json!(input_focused);
|
||||
// Only a submission accepted by the native path can launch the pulse.
|
||||
// Loading history, repainting bubbles and failed preflight never do.
|
||||
let sent = matches!(self.busy.as_deref(), Some("agent" | "pi-agent" | "image" | "slot-append" | "slot-generate"))
|
||||
&& self.messages.get(messages_before_send..).is_some_and(|messages|
|
||||
messages.iter().any(|message| message["role"] == "user"));
|
||||
if sent {
|
||||
self.reveal_sent_user_text(ui,messages_before_send);
|
||||
self.flush_document_draft(ui.ctx(), self.observed_doc, false);
|
||||
}
|
||||
super::stitch_ui::sent_glow(ui, Id::unique("composer-sent-glow"), super::stitch_ui::SendSurface {rect:frame.response.rect,radius,background:Some(send_background),text_range:Some(text_start..text_end),flanks:morph}, sent, self.reduce_motion);
|
||||
|
||||
if self.prompt_library.show(ui, &self.account, &self.origin, &mut self.composer, &self.tx,
|
||||
prompt_library_ui::PromptPanelPlacement { can_insert:draft_ready, reduced:self.reduce_motion, anchor:prompt_anchor, composer:frame.response.rect }) {
|
||||
self.canvas_workspace.composer_edited();
|
||||
self.draft_changed = true;
|
||||
self.touched = Instant::now();
|
||||
if let Some(id) = toast_id(&self.origin, &self.account, &self.project_context, self.owner_doc) { post_draft_toast(ui, id); }
|
||||
}
|
||||
if let Some(id) = toast_id(&self.origin, &self.account, &self.project_context, self.owner_doc) {
|
||||
draw_draft_toast(ui, id, frame.response.rect, self.reduce_motion);
|
||||
}
|
||||
self.panel_geometry["composerLightMode"] = json!(super::stitch_ui::composer_glow_mode(ui,self.reduce_motion));
|
||||
if !self.needs_library_login() && !self.library_blocked() && !self.key_saved && super::stitch_ui::action_button(ui, "连接个人模型", super::stitch_ui::ButtonRole::Quiet, true).clicked() {
|
||||
self.open_model_settings();
|
||||
self.key_settings = true;
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn error_notice_ui(&mut self,ui:&mut Ui) {
|
||||
self.panel_geometry["errorNotice"]=Value::Null;
|
||||
if self.error.is_empty() || self.error==self.library_message {return;}
|
||||
if self.result_needs_check() && (self.error.contains("素材库请求失败(HTTP 503)")
|
||||
|| self.error.contains("结果未知;不会重发") || self.error.contains("原请求结果待核查")) { return; }
|
||||
let error=self.error.clone();
|
||||
let details=super::operation_error::inline(ui,&error);
|
||||
self.panel_geometry["errorNotice"]=json!({"title":super::operation_error::public_title(&error),"details":rect_value(details.rect)});
|
||||
if details.clicked()
|
||||
&& let Some(id)=notification_id(&self.origin,&self.account,&self.project_context,self.owner_doc) {
|
||||
ui.ctx().data_mut(|data| {
|
||||
let history=data.get_temp_mut_or_default::<AgentNotifications>(id);
|
||||
history.add(&error);history.open=true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn status_row(&mut self, ui: &mut Ui, name: &str, text: &str, tint: Color32, action: impl FnOnce(&mut Self, &mut Ui)) {
|
||||
let frame=super::stitch_ui::surface_frame(ui.ctx(),super::stitch_ui::SurfaceRole::Task).stroke(Stroke::NONE).inner_margin(8);
|
||||
super::stitch_ui::material_frame(ui,frame, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
icon(ui, name, tint);
|
||||
ui.label(RichText::new(text).size(12.0).color(tint));
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| action(self, ui));
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,67 @@
|
||||
use super::super::{PhotocraftApp, Request, Value, Workspace, json};
|
||||
use super::artifact_preview_ui::{candidate_matches_message, image_location};
|
||||
use super::turns::turns;
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn trace_canvas_candidate(&mut self, app: &PhotocraftApp, target: Value) {
|
||||
self.pending_candidate_trace = None;
|
||||
let Some((doc, revision)) = app.session.active().map(|state| (state.doc.id.0, state.revision)) else { return };
|
||||
let matching: Vec<_> = turns(&self.messages).into_iter().filter(|turn|
|
||||
turn.images().any(|image| candidate_matches_message(&target, image)))
|
||||
.map(|turn| turn.user_index).collect();
|
||||
if matching.len() != 1 { return; }
|
||||
self.pending_candidate_trace = Some(json!({
|
||||
"scope":[self.origin,self.account["id"],self.project_context["localId"],doc,self.loaded_draft,revision],
|
||||
"turn":matching.first().copied().flatten(),"target":target
|
||||
}));
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn track_worker_image(&mut self, value: &Value) {
|
||||
let Some(op) = self.workflow.worker_image_progress(value) else { return; };
|
||||
let Some(task) = op["candidateId"].as_str().filter(|_| op["imageFrame"].is_object()) else { return; };
|
||||
if let Some(message) = self.messages.iter_mut().rev().find(|message| message["taskId"] == task
|
||||
&& matches!(message["kind"].as_str(), Some("image-job" | "image")))
|
||||
{
|
||||
if message["kind"] == "image-job" {
|
||||
message["step"] = op["imageStep"].clone();
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.messages.push(json!({
|
||||
"role":"assistant", "kind":"image-job", "taskId":task, "run":op["run"], "workerNumber":op["workerNumber"],
|
||||
"width":op["imageFrame"]["width"], "height":op["imageFrame"]["height"],
|
||||
"slotLabel":op["slotLabel"], "step":op["imageStep"],
|
||||
"target":{"slotId":op["slotId"],"outputId":op["outputId"],"productVariantId":op["productVariantId"],"candidateId":task}
|
||||
}));
|
||||
self.draft_changed = true;
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn register_image(&mut self, task: Value) {
|
||||
let Some(id) = task["taskId"].as_str() else {
|
||||
return;
|
||||
};
|
||||
if !self.messages.iter().any(|m| m["kind"] == "image" && m["taskId"] == id) {
|
||||
let mut message = json!({"role":"assistant","kind":"image","taskId":id,"target":image_location(&task, id)});
|
||||
for key in ["slotId", "outputId"] {
|
||||
if task[key].is_string() {
|
||||
message[key] = task[key].clone();
|
||||
}
|
||||
}
|
||||
if task["variantId"].is_string() {
|
||||
message["productVariantId"] = task["variantId"].clone();
|
||||
}
|
||||
if let Some(job) = self.messages.iter_mut().rev().find(|item| item["kind"] == "image-job" && item["taskId"] == id) {
|
||||
for key in ["width", "height", "workerNumber", "slotLabel"] {
|
||||
message[key] = job[key].clone();
|
||||
}
|
||||
*job = message;
|
||||
} else {
|
||||
self.messages.push(message);
|
||||
}
|
||||
self.draft_changed = true;
|
||||
}
|
||||
if self.requested_previews.insert(id.to_owned()) {
|
||||
let _ = self.tx.send(Request::Action("agent-image-preview".into(), json!({"doc":task["doc"],"taskId":id})));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,211 @@
|
||||
use super::super::stitch_timeline as timeline;
|
||||
use super::artifact_preview_ui::image_location;
|
||||
use super::turn_ui::paint_image_caption;
|
||||
use egui::{FontId, Layout, Rect};
|
||||
use super::super::{Tokens, Ui, Value, Workspace, agent_motion};
|
||||
use super::artifact_preview_ui::{image_preview_button, image_reference_target};
|
||||
use super::turn_ui::{frame_image_ratio, image_card_size, image_result_labels};
|
||||
use egui::{Align2, Color32, Id, Response, Sense, Stroke, vec2};
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn timeline_images(&self, ui: &mut Ui, id: Id, images: &[&Value], flow: &mut super::agent_stream::Flow, doc: Option<&super::Document>) -> Option<Value> {
|
||||
let heading = if images.iter().any(|image| image["kind"] == "template-image") { "图片来源" } else { "生成图片" };
|
||||
let count = images.len().to_string();
|
||||
ui.add_space(2.0);
|
||||
let (row, results) = timeline::image_set(ui, id, timeline::ImageSet::conversation(heading, Some(&count), images.len()),
|
||||
self.reduce_motion, |ui, index, width| self.image_result(ui, images[index], width, doc));
|
||||
flow.connect(ui, row.rect);
|
||||
flow.break_run();
|
||||
results.into_iter().flatten().last()
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn image_result(&self, ui: &mut Ui, value: &Value, cell_width: f32, doc: Option<&super::Document>) -> Option<Value> {
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let id = value["taskId"].as_str().or_else(|| value["id"].as_str()).filter(|id| !id.is_empty())?;
|
||||
let now = ui.input(|input| input.time);
|
||||
let enter = self.canvas_workspace.preview_arrival(id).map_or(1.0, |started| agent_motion::image_enter(now - started, 1.0, self.reduce_motion).0);
|
||||
let mut locate = None;
|
||||
let target = image_location(value, id);
|
||||
let original = value["kind"] == "template-image" || value["original"] == true;
|
||||
let (page_label, short_label, label) = if original {
|
||||
let field = self.template_workflow["outputs"].as_array().into_iter().flatten()
|
||||
.filter(|output| value["outputId"].is_null() || output["outputId"] == value["outputId"])
|
||||
.flat_map(|output| output["fields"].as_array().into_iter().flatten())
|
||||
.find(|field| field["kind"] == "image" && field["fieldId"] == value["fieldId"])
|
||||
.and_then(|field| field["label"].as_str())
|
||||
.or_else(|| value["fieldId"].as_str()).unwrap_or("");
|
||||
let label = if field.is_empty() { "模板原图".into() } else { format!("{field} · 模板原图") };
|
||||
(String::new(), "模板原图".into(), label)
|
||||
} else if value["slotId"].is_null() && value["candidateId"].is_null()
|
||||
&& let Some(label) = value["label"].as_str().filter(|label| !label.is_empty())
|
||||
{
|
||||
(String::new(), label.to_owned(), label.to_owned())
|
||||
} else {
|
||||
image_result_labels(&target, &self.template_workflow, &self.creation_brief)
|
||||
};
|
||||
let ratio_id = ui.scope_id().with(("result-image-ratio", id));
|
||||
let ratio = ui.data_mut(|data| {
|
||||
if let Some(texture) = self.agent_images.peek(id) {
|
||||
let size = texture.size_vec2();
|
||||
data.insert_temp(ratio_id, size.x / size.y.max(1.0));
|
||||
}
|
||||
data.get_temp::<f32>(ratio_id).or_else(|| frame_image_ratio(value)).unwrap_or(1.0)
|
||||
});
|
||||
let size = image_card_size(cell_width, ratio);
|
||||
if value["kind"] == "image-job" {
|
||||
let active = !self.agent_effects_paused && value["finished"].is_null()
|
||||
&& (value["projected"] == true || self.pi_run.as_deref().is_some_and(|run| value["run"] == run));
|
||||
let text = value["slotLabel"].as_str().unwrap_or("").to_owned();
|
||||
if !active {
|
||||
// A queued slot keeps its cell and its place in order; it grows
|
||||
// into the image card only once its own generation starts.
|
||||
super::agent_stream::queued_job(ui, cell_width, &text, value["finished"].as_str().unwrap_or("等待结果"));
|
||||
return None;
|
||||
}
|
||||
let step = value["step"].as_str().unwrap_or("正在生成图片…");
|
||||
let (rect, response) = ui.allocate_ui_with_layout(
|
||||
vec2(cell_width, size.y), Layout::centered_and_justified(egui::Direction::TopDown),
|
||||
|ui| ui.allocate_exact_size(size, Sense::empty()),
|
||||
).inner;
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{text} · {step}")));
|
||||
if ui.is_rect_visible(rect) {
|
||||
let id = ui.scope_id().with(("timeline-image-job", id));
|
||||
let painter = ui.painter_at(rect);
|
||||
painter.rect_filled(rect, t.radius_sm, t.canvas);
|
||||
painter.rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside);
|
||||
let background = ui.painter().add(egui::Shape::Noop);
|
||||
super::glow_pill::background(ui, id, rect, t.radius_sm, 0.56, background);
|
||||
painter.text(rect.center(), Align2::CENTER_CENTER, step, FontId::proportional(super::agent_stream::TEXT_TITLE), t.text);
|
||||
paint_image_caption(&painter, rect, &text);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
let slot = self.template_workflow["slots"].as_array().into_iter().flatten().find(|slot|
|
||||
target["slotId"].is_string() && slot["id"] == target["slotId"] && slot["outputId"] == target["outputId"]
|
||||
&& slot["variantId"] == target["productVariantId"]);
|
||||
let candidate = slot.and_then(|slot| slot["candidates"].as_array()?.iter()
|
||||
.find(|candidate| candidate["id"] == target["candidateId"]));
|
||||
let live = doc.zip(target["slotId"].as_str().zip(target["productVariantId"].as_str()))
|
||||
.filter(|(doc, _)| target["documentId"].as_u64().is_none_or(|id| doc.id.0 == id)
|
||||
&& self.canvas_workspace.output == target["outputId"] && self.canvas_workspace.variant == target["productVariantId"]);
|
||||
let adopted = live.and_then(|(doc, (slot, variant))| super::canvas_workspace::adopted(doc, slot, variant));
|
||||
let manual = live.is_some_and(|(doc, (slot, variant))| super::canvas_workspace::manual_image(doc, slot, variant).is_some());
|
||||
let is_adopted = adopted.is_some() && adopted == target["candidateId"].as_str();
|
||||
let show_adopt = live.is_some() && !is_adopted && candidate.is_some_and(|candidate| candidate["status"] == "complete")
|
||||
&& self.can_start_turn() && self.saving.is_none();
|
||||
ui.push_id(id, |ui| ui.vertical(|ui| {
|
||||
ui.set_width(cell_width);
|
||||
ui.allocate_ui_with_layout(vec2(cell_width, size.y), Layout::centered_and_justified(egui::Direction::TopDown), |ui| {
|
||||
if let Some(texture) = self.agent_images.peek(id) {
|
||||
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
|
||||
// Blur and fade in place: geometry, the rounded mask, the hit
|
||||
// target and selection outline all remain at the final crop.
|
||||
// The parent UI clip still bounds the image when scrolling.
|
||||
if ui.is_rect_visible(rect) {
|
||||
self.agent_images.mark_visible_existing(id);
|
||||
let _ = self.agent_images.get(id);
|
||||
if enter < 1.0 {
|
||||
ui.painter().add(agent_motion::rounded_image_entry_blur(texture.id(), rect, enter, t.radius_sm));
|
||||
} else {
|
||||
egui::Image::new(texture).fit_to_exact_size(rect.size()).corner_radius(t.radius_sm).paint_at(ui, rect);
|
||||
}
|
||||
}
|
||||
agent_motion::message_repaint(ui, rect, enter);
|
||||
let selected = !original && self.canvas_workspace.context.as_ref().is_some_and(|current| current["candidateId"] == target["candidateId"]);
|
||||
if selected {
|
||||
agent_motion::role_light(ui, agent_motion::Surface::new(response.id.with("selection-light"), rect.expand(1.0), t.radius_sm), self.reduce_motion, agent_motion::LightRole::CanvasTarget);
|
||||
} else if response.hovered() {
|
||||
ui.painter().rect_stroke(rect.expand(1.0), t.radius_sm, Stroke::new(1.0, t.text_dim), egui::StrokeKind::Outside);
|
||||
}
|
||||
let slot_label = slot.and_then(|slot| slot["label"].as_str()).or_else(|| value["slotLabel"].as_str()).unwrap_or("");
|
||||
let caption = [slot_label, page_label.as_str(), short_label.as_str()].into_iter()
|
||||
.filter(|part| !part.is_empty()).collect::<Vec<_>>().join(" · ");
|
||||
paint_image_caption(&ui.painter_at(rect), rect, &caption);
|
||||
let review = &self.workflow.production_progress()["candidateReviews"][id];
|
||||
let decision = candidate.and_then(|candidate| candidate["reviewDecision"].as_str())
|
||||
.or_else(|| value["reviewDecision"].as_str()).or_else(|| review["status"].as_str());
|
||||
let badge = if is_adopted { Some(("已采纳", t.agent_semantic().success)) }
|
||||
else if manual { Some(("图位已手动编辑", t.text_faint)) }
|
||||
else { match decision {
|
||||
Some("passed" | "pass") => Some(("验图通过", t.agent_semantic().success)),
|
||||
Some("not_selected") => Some(("未选用", t.text_faint)),
|
||||
Some("rejected" | "revise" | "missing") => Some(("已退回", t.danger)),
|
||||
Some("pending") => Some(("待核查", t.warning)),
|
||||
_ if !original && target["slotId"].is_string() => Some(("待采纳", t.warning)),
|
||||
_ => None,
|
||||
}};
|
||||
if let Some((status, color)) = badge && rect.width() >= 112.0 && rect.height() >= 52.0 {
|
||||
let painter = ui.painter_at(rect);
|
||||
let font = crate::theme::agent_scale::Type::Meta.font_id();
|
||||
let text = painter.layout_no_wrap(status.to_owned(), font, Color32::WHITE);
|
||||
let tag = Rect::from_min_size(rect.left_top() + vec2(8.0, 8.0), vec2(text.size().x + 21.0, 22.0));
|
||||
painter.rect_filled(tag, 6.0, Color32::from_black_alpha(188));
|
||||
painter.circle_filled(egui::pos2(tag.left() + 8.0, tag.center().y), 3.0, color);
|
||||
painter.galley(egui::pos2(tag.left() + 15.0, tag.center().y - text.size().y * 0.5), text, Color32::WHITE);
|
||||
}
|
||||
let expand = (rect.width() >= 42.0 && rect.height() >= 42.0).then(|| image_preview_button(ui, rect, id));
|
||||
let response = response.on_hover_text(format!("{label} · 右键引用到小壹或查看大图"));
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("定位 {label}")));
|
||||
if response.clicked() && !expand.is_some_and(|button| button.clicked()) {
|
||||
if original {
|
||||
ui.data_mut(|data| data.insert_temp(Id::unique("jiansun-image-expanded"), id.to_owned()));
|
||||
} else {
|
||||
locate = Some(image_location(value, id));
|
||||
}
|
||||
}
|
||||
self.image_reference_menu(ui, &response, value, id, &label, original, show_adopt);
|
||||
} else {
|
||||
let placeholder = if original { "模板原图加载中" } else { "定位图片" };
|
||||
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
|
||||
let response = response.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
.on_hover_text(format!("{label} · 右键引用到小壹或查看大图"));
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, placeholder));
|
||||
if ui.is_rect_visible(rect) {
|
||||
ui.painter().rect_filled(rect, t.radius_sm, if response.hovered() { t.hover } else { t.field });
|
||||
let icon_size = rect.width().min(rect.height()).min(16.0);
|
||||
crate::icons::paint(ui, Rect::from_center_size(rect.center(), vec2(icon_size, icon_size)), "image", icon_size, t.text_dim);
|
||||
if response.has_focus() {
|
||||
ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.text_dim), egui::StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
if ui.is_rect_visible(response.rect) && matches!(value["status"].as_str(), None | Some("complete")) {
|
||||
self.agent_images.mark_visible(id);
|
||||
}
|
||||
self.image_reference_menu(ui, &response, value, id, &label, original, show_adopt);
|
||||
if response.clicked() && !original {
|
||||
locate = Some(image_location(value, id));
|
||||
}
|
||||
}
|
||||
});
|
||||
}));
|
||||
locate
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn image_reference_menu(&self, ui: &mut Ui, response: &Response, value: &Value, id: &str, label: &str, original: bool, show_adopt: bool) {
|
||||
egui::Popup::context_menu(response).frame(super::stitch_ui::menu_frame(ui.ctx())).show(|ui| {
|
||||
super::stitch_ui::scope_with_motion(ui, self.reduce_motion, |ui| {
|
||||
// menu_item fills its available width; constrain the
|
||||
// popup rather than letting it inherit the whole canvas.
|
||||
let width = 176.0_f32.min((ui.ctx().content_rect().width() - 32.0).max(1.0));
|
||||
ui.set_min_width(width);
|
||||
ui.set_max_width(width);
|
||||
ui.spacing_mut().item_spacing.y = 2.0;
|
||||
if show_adopt && super::stitch_ui::menu_item(ui, "采纳", true).clicked() {
|
||||
ui.data_mut(|data| data.insert_temp(Id::unique("xiaoyi-adopt-candidate"), image_location(value, id)));
|
||||
ui.close();
|
||||
}
|
||||
if super::stitch_ui::menu_item(ui, "引用到小壹", true).clicked() {
|
||||
let target = image_reference_target(value, id, label, original);
|
||||
ui.data_mut(|data| data.insert_temp(Id::unique("xiaoyi-image-reference"), target));
|
||||
ui.close();
|
||||
}
|
||||
let preview = super::stitch_ui::menu_item(ui, "查看大图", true);
|
||||
if preview.clicked() {
|
||||
ui.data_mut(|d| d.insert_temp(Id::unique("jiansun-image-expanded"), id.to_owned()));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,555 @@
|
||||
use super::super::{Request, RichText, Value};
|
||||
use super::models::{CONTEXT_PENDING, CONTEXT_UNAVAILABLE, context_fraction, context_label};
|
||||
use super::notifications::{AgentNotifications, notification_id};
|
||||
use super::super::agent_panel::storage_settings_ui;
|
||||
use egui::{FontId, Frame, Rect, Sense, Vec2};
|
||||
use super::super::{PhotocraftApp, Tokens, Ui, Workspace, json};
|
||||
use super::rect_value;
|
||||
use super::models::{ModelRole, is_hidden_model, model_display_name};
|
||||
use super::turn_ui::icon;
|
||||
use egui::{Align, Color32, Id, Layout, Response, vec2};
|
||||
|
||||
pub(in crate::jiansun) fn context_meter(ui:&mut Ui,usage:Option<&Value>,reduced:bool,compact:bool)->Response{
|
||||
let t=Tokens::get(ui.ctx()).agent();let fraction=context_fraction(usage);let label=context_label(usage);
|
||||
// The ring itself stays a dash; what it explains to a person is that the
|
||||
// number is not known yet, which a bare dash cannot say.
|
||||
let accessible=if label==CONTEXT_UNAVAILABLE {CONTEXT_PENDING.to_owned()}else{label.clone()};
|
||||
let response=ui.horizontal(|ui|{
|
||||
let response=super::stitch_ui::context_capacity(ui,fraction,&accessible).interact(Sense::click());
|
||||
if !compact {ui.label(RichText::new(&label).size(12.0).color(t.text));}response
|
||||
}).inner;
|
||||
response.widget_info(||egui::WidgetInfo::labeled(egui::Role::Button,true,accessible.as_str()));
|
||||
super::stitch_ui::select_popup(ui,&response,260.0,reduced,|ui|{
|
||||
ui.label(RichText::new("当前上下文").strong().color(t.text));
|
||||
if let Some(fraction)=fraction {
|
||||
super::stitch_ui::progress(ui,response.id.with("capacity"),&accessible,Some(fraction),reduced);
|
||||
} else {ui.label(RichText::new(&accessible).size(12.0).color(t.text_dim));}
|
||||
});response
|
||||
}
|
||||
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn model_picker(&mut self, ui: &mut Ui, role: ModelRole, width: f32, compact: bool) -> Response {
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let current = match role {ModelRole::Chat=>&self.model,ModelRole::Copy=>&self.copy_model,ModelRole::Image=>&self.image_model};
|
||||
let models = match role {ModelRole::Chat=>&self.models,ModelRole::Copy=>&self.copy_models,ModelRole::Image=>&self.image_models};
|
||||
let label = models.iter().find(|m| m["key"] == *current).and_then(|m| m["id"].as_str()).map(model_display_name).unwrap_or_else(|| "选择模型".to_owned());
|
||||
let display = label.clone();
|
||||
let mut selected = current.clone();
|
||||
let enabled = self.busy.is_none() && !self.account.is_null();
|
||||
let old_selection = selected.clone();
|
||||
let mut show_all_models = self.show_all_models;
|
||||
let mut menu_rect = None;
|
||||
// A native ComboBox owns its popup lifetime and keyboard semantics.
|
||||
// Bind that popup to the current workspace identity and close the old
|
||||
// one before switching scope or disabling selection.
|
||||
let model_scope = json!([self.origin, self.account["id"], self.project_context["localId"], self.owner_doc]).to_string();
|
||||
let response = ui
|
||||
.add_enabled_ui(enabled, |ui| {
|
||||
super::stitch_ui::scope_with_motion(ui, self.reduce_motion, |ui| {
|
||||
let response = ui.push_id(("agent-model", role, compact, &model_scope), |ui| {
|
||||
super::stitch_ui::select_trigger(ui, &display, width, enabled)
|
||||
}).inner;
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, enabled, &display));
|
||||
let popup_id = response.id.with("popup");
|
||||
let last_id = Id::unique(("agent-model-last-popup", role, compact));
|
||||
if let Some(previous) = ui.data(|d| d.get_temp::<Id>(last_id))
|
||||
&& (previous != popup_id || !enabled) {
|
||||
egui::Popup::close_id(ui.ctx(), previous);
|
||||
}
|
||||
if !enabled { egui::Popup::close_id(ui.ctx(), popup_id); }
|
||||
ui.data_mut(|d| d.insert_temp(last_id, popup_id));
|
||||
let show_toggle = models.iter().any(|model| is_hidden_model(role, model));
|
||||
let showing_all = show_all_models;
|
||||
let visible = models.iter().filter(|model| {
|
||||
showing_all || model["key"] == old_selection || !is_hidden_model(role, model)
|
||||
});
|
||||
let longest = visible.clone().filter_map(|model| model["id"].as_str()).map(|name| {
|
||||
ui.painter().layout_no_wrap(model_display_name(name), FontId::proportional(13.0), t.text).size().x + 76.0
|
||||
}).fold(width, f32::max);
|
||||
let limit = (ui.ctx().content_rect().width() * 0.52).clamp(240.0, 560.0).min((ui.ctx().content_rect().width() - 32.0).max(160.0));
|
||||
let popup_width = longest.min(limit).max(width.min(limit));
|
||||
let shown = super::stitch_ui::select_popup_with_behavior(ui, &response, popup_width, self.reduce_motion, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| {
|
||||
ui.set_width((popup_width - 16.0).max(128.0));
|
||||
ui.set_max_width((popup_width - 16.0).max(128.0));
|
||||
ui.spacing_mut().item_spacing.y = 2.0;
|
||||
ui.label(RichText::new(match role {ModelRole::Chat=>"对话模型",ModelRole::Copy=>"文案模型",ModelRole::Image=>"生图模型"}).size(12.0).strong().color(t.text_dim));
|
||||
ui.add_space(4.0);
|
||||
egui::ScrollArea::vertical().id_salt(("agent-model-list", role, compact)).max_height(280.0).show(ui, |ui| {
|
||||
let mut option = |ui: &mut Ui, key: &str, name: &str, allowed: bool| {
|
||||
let is_selected = selected == key;
|
||||
let label = if allowed { name.to_owned() } else { format!("{name} · Key未开放") };
|
||||
let item = super::stitch_ui::select_option(ui, &label, is_selected, allowed);
|
||||
if item.clicked() { selected = key.to_owned(); ui.close(); }
|
||||
};
|
||||
option(ui, "", "未选择", true);
|
||||
for model in visible {
|
||||
if let (Some(key), Some(id)) = (model["key"].as_str(), model["id"].as_str()) {
|
||||
let name = model_display_name(id);
|
||||
let label = match (role, model["productionReady"].as_bool(), model["imageInputStatus"].as_str()) {
|
||||
(ModelRole::Chat, Some(true), _) if model["productionVerified"] != true => format!("{name} · 制作待实测"),
|
||||
(ModelRole::Chat, Some(true), _) => format!("{name} · 可制作"),
|
||||
(ModelRole::Chat, _, Some("disabled")) => format!("{name} · 仅文本"),
|
||||
(ModelRole::Chat, Some(false), _) => format!("{name} · 制作待核验"),
|
||||
_ => name,
|
||||
};
|
||||
option(ui, key, &label, self.available(id));
|
||||
}
|
||||
}
|
||||
});
|
||||
if show_toggle {
|
||||
super::stitch_ui::divider(ui);
|
||||
super::stitch_ui::switch(ui, ui.scope_id().with("show-all-models"), &mut show_all_models,
|
||||
"显示历史/全部模型", enabled, self.reduce_motion);
|
||||
}
|
||||
});
|
||||
if let Some(shown) = shown {
|
||||
let rect = ui.ctx().layer_transform_to_global(shown.response.layer_id).map_or(shown.response.rect, |transform| transform * shown.response.rect);
|
||||
menu_rect = Some(rect);
|
||||
}
|
||||
response
|
||||
})
|
||||
.inner
|
||||
})
|
||||
.inner;
|
||||
self.show_all_models = show_all_models;
|
||||
if let Some(rect) = menu_rect {
|
||||
self.panel_geometry[role.menu()] = rect_value(rect);
|
||||
}
|
||||
if compact {
|
||||
let rect = ui.ctx().layer_transform_to_global(response.layer_id).map_or(response.rect, |transform| transform * response.rect);
|
||||
self.panel_geometry["model"] = rect_value(rect);
|
||||
self.panel_geometry[role.geometry()] = rect_value(rect);
|
||||
}
|
||||
if selected != old_selection {
|
||||
self.choose_model(role, selected);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn onboarding_model_options(&mut self, ui: &mut Ui) {
|
||||
use crate::theme::agent_scale::Type;
|
||||
let roles = [(ModelRole::Chat, "对话模型", !self.models.is_empty()),
|
||||
(ModelRole::Copy, "文案模型", !self.copy_models.is_empty()),
|
||||
(ModelRole::Image, "生图模型", !self.image_models.is_empty())];
|
||||
let available = roles.into_iter().filter(|(_, _, available)| *available);
|
||||
let count = available.clone().count();
|
||||
if count == 0 {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
super::stitch_ui::status_label(ui, "模型目录未加载", super::stitch_ui::StatusTone::Warning);
|
||||
if super::stitch_ui::action_button(ui, "重试", super::stitch_ui::ButtonRole::Quiet, self.busy.is_none()).clicked() {
|
||||
self.send("restore", json!({}));
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
ui.label(RichText::new("至少选择一个模型").font(Type::Meta.font_id()).color(Tokens::get(ui.ctx()).agent().text_dim));
|
||||
ui.horizontal_top(|ui| {
|
||||
let width = (ui.available_width() - (count - 1) as f32 * ui.spacing().item_spacing.x) / count as f32;
|
||||
for (role, label, _) in available {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(width);
|
||||
ui.label(label);
|
||||
self.model_picker(ui, role, width, true);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn model_key_editor(&mut self, ui: &mut Ui, scope: &str, open: bool, focus: bool) {
|
||||
let enabled = open && self.busy.is_none() && !self.account.is_null();
|
||||
ui.add_enabled_ui(enabled, |ui| {
|
||||
let key_id = ui.make_persistent_id((scope, "personal-key", &self.origin, self.account["id"].as_str().unwrap_or_default()));
|
||||
let input = super::stitch_ui::halo_field(ui, key_id.with("field"), None, self.reduce_motion, |ui| ui.add(
|
||||
super::stitch_ui::text_input(
|
||||
&mut self.api_key,
|
||||
if self.key_saved { "输入新的个人 Key" } else { "输入个人 Key" },
|
||||
false,
|
||||
)
|
||||
.id(key_id).password(true).desired_width(f32::INFINITY).frame(Frame::NONE),
|
||||
).accessible_name("模型 API Key"));
|
||||
if focus && enabled { input.request_focus(); }
|
||||
input.on_hover_text("只保存在本机系统凭据库");
|
||||
if super::stitch_ui::action_button(ui, "保存连接", super::stitch_ui::ButtonRole::Primary,
|
||||
!self.api_key.trim().is_empty() && (!self.model.is_empty() || !self.copy_model.is_empty() || !self.image_model.is_empty()))
|
||||
.clicked()
|
||||
{
|
||||
self.model_ready = false;
|
||||
self.image_ready = false;
|
||||
self.copy_ready = false;
|
||||
self.send("configure", json!({"key":self.api_key,"model":self.model,"copyModel":self.copy_model,"imageModel":self.image_model}));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn thinking_picker(&mut self, ui: &mut Ui) {
|
||||
let Some(model) = self.models.iter().find(|model| model["key"] == self.model && model["reasoning"] == true) else {
|
||||
return;
|
||||
};
|
||||
let label = |level: &str| match level {
|
||||
"off" => "关闭",
|
||||
"minimal" => "最少",
|
||||
"low" => "低",
|
||||
"medium" => "中",
|
||||
"high" => "高",
|
||||
"xhigh" => "很高",
|
||||
"max" => "最高",
|
||||
_ => "自动",
|
||||
};
|
||||
let current = self.thinking_by_model.get(self.model.as_str()).and_then(Value::as_str).unwrap_or("");
|
||||
let mut selected = current;
|
||||
let levels = model["reasoningEfforts"].as_array().into_iter().flatten().filter_map(Value::as_str);
|
||||
let width = ui.available_width();
|
||||
let tokens = Tokens::get(ui.ctx()).agent();
|
||||
ui.push_id("xiaoyi-thinking-effort", |ui| {
|
||||
ui.label(RichText::new("思考档位").size(12.0).color(tokens.text_dim));
|
||||
let trigger = super::stitch_ui::select_trigger(ui, label(current), width, self.model_ready && self.busy.is_none());
|
||||
self.panel_geometry["thinkingLevel"] = rect_value(trigger.rect);
|
||||
super::stitch_ui::select_popup(ui, &trigger, width, self.reduce_motion, |ui| {
|
||||
for level in ["", "off"].into_iter().chain(levels) {
|
||||
if super::stitch_ui::select_option(ui, label(level), current == level, true).clicked() {
|
||||
selected = level;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if selected != current {
|
||||
self.send("select-model", json!({"field":"thinkingLevel","selection":selected,"model":self.model,
|
||||
"accountId":self.account["id"],"origin":self.origin}));
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn xiaoyi_key_input(&mut self, ui: &mut Ui) {
|
||||
use super::stitch_ui::{self, ButtonRole};
|
||||
let id = ui.make_persistent_id("xiaoyi-knowledge-key");
|
||||
let hint = if self.xiaoyi_key_saved { "输入新的制作 Key" } else { "输入制作 Key" };
|
||||
stitch_ui::halo_field(ui, id.with("field"), None, self.reduce_motion, |ui| ui.add(
|
||||
stitch_ui::text_input(&mut self.xiaoyi_key, hint, false)
|
||||
.id(id).password(true).desired_width(f32::INFINITY).frame(Frame::NONE),
|
||||
));
|
||||
if stitch_ui::action_button(ui, "校验并保存", ButtonRole::Secondary, !self.xiaoyi_key.trim().is_empty()).clicked() {
|
||||
let key = std::mem::take(&mut self.xiaoyi_key);
|
||||
self.send("configure-xiaoyi-knowledge", json!({"key":key}));
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn knowledge_settings(&mut self, ui: &mut Ui) {
|
||||
use super::stitch_ui::{self, ButtonRole, StatusTone, status_label};
|
||||
use crate::theme::agent_scale::Type;
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
ui.label(RichText::new("小壹知识库").size(Type::Title.size()).color(t.text));
|
||||
let checking = self.busy.as_deref() == Some("configure-xiaoyi-knowledge");
|
||||
if self.xiaoyi_knowledge_mode == "manual" {
|
||||
knowledge_connection_status(ui, self.xiaoyi_key_saved, self.xiaoyi_key_check.as_ref(), checking);
|
||||
} else {
|
||||
let (status, tone) = match (checking, self.xiaoyi_key_check.as_ref(), self.xiaoyi_knowledge_mode.as_str()) {
|
||||
(true, _, _) => ("正在连接", StatusTone::Neutral),
|
||||
(false, Some(Err(_)), _) => ("连接失败", StatusTone::Error),
|
||||
(false, _, "automatic") => ("素材库自动连接", StatusTone::Neutral),
|
||||
_ if self.account.is_null() => ("登录后自动连接", StatusTone::Neutral),
|
||||
_ => ("未连接", StatusTone::Neutral),
|
||||
};
|
||||
status_label(ui, status, tone);
|
||||
if let Some(Err(error)) = self.xiaoyi_key_check.as_ref().filter(|_| !checking) {
|
||||
status_label(ui, error, StatusTone::Error);
|
||||
}
|
||||
}
|
||||
ui.add_enabled_ui(self.busy.is_none(), |ui| {
|
||||
if self.xiaoyi_knowledge_mode == "manual" && !self.xiaoyi_key_saved {
|
||||
self.xiaoyi_key_input(ui);
|
||||
} else {
|
||||
if stitch_ui::action_button(ui, "检测连接", ButtonRole::Secondary, true).clicked() {
|
||||
self.send("configure-xiaoyi-knowledge", json!({"key":""}));
|
||||
}
|
||||
if self.xiaoyi_knowledge_mode == "manual" {
|
||||
let id = ui.make_persistent_id("replace-xiaoyi-knowledge-key");
|
||||
stitch_ui::disclosure(ui, id, "更换制作 Key", false, self.reduce_motion, |ui| {
|
||||
self.xiaoyi_key_input(ui);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn workspace_settings_ui(&mut self, app: &PhotocraftApp, ui: &mut Ui, corner: egui::Pos2) {
|
||||
// The brief's buttons disappear when the models are ready. Anchor the
|
||||
// popup and its exit animation to the workspace instead.
|
||||
let inset = crate::theme::agent_scale::space::MD;
|
||||
let anchor = ui.interact(
|
||||
Rect::from_min_size(corner + vec2(inset, -inset), Vec2::ZERO),
|
||||
ui.make_persistent_id("workspace-settings-anchor"),
|
||||
Sense::hover(),
|
||||
);
|
||||
if self.notifications_ui(ui) {
|
||||
self.show_center(super::CenterView::Canvas, app.session.active().is_some());
|
||||
}
|
||||
self.model_settings_popup(ui, &anchor);
|
||||
self.flush_client_update_request(app);
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn model_settings_popup(&mut self, ui: &mut Ui, anchor: &Response) {
|
||||
let retained = ui.ctx().read_response(egui::Popup::default_response_id(anchor)).is_some();
|
||||
if self.model_settings || self.key_settings || retained {
|
||||
self.settings_popup(ui, anchor);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn settings_popup(&mut self, ui: &mut Ui, anchor: &Response) {
|
||||
// The dock layout can change mid-pass. A mounted popup claims the pass
|
||||
// so another host cannot draw a second copy during the handoff.
|
||||
let host = Id::unique(("jiansun-settings-host", ui.ctx().viewport_id()));
|
||||
let pass = ui.ctx().cumulative_pass_nr();
|
||||
if ui.data(|data| data.get_temp::<u64>(host)) == Some(pass) {
|
||||
return;
|
||||
}
|
||||
let open = self.model_settings || self.key_settings;
|
||||
let open_id = host.with("open");
|
||||
let was_open = ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::<bool>(open_id), open));
|
||||
if was_open && !open {
|
||||
self.clear_settings_key_draft();
|
||||
self.xiaoyi_key.clear();
|
||||
}
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let (visual, transform) = super::stitch_ui::floating_panel_motion(ui.ctx(), anchor.id.with("popup"), anchor, open, self.reduce_motion);
|
||||
self.panel_geometry["settingsMotion"] = json!({"opacity":visual.opacity,"scale":transform.scaling,"interactive":visual.interactive});
|
||||
ui.ctx().data_mut(|data| data.insert_temp(Id::unique("jiansun-settings-retained"), visual.render));
|
||||
if !visual.render {
|
||||
return;
|
||||
}
|
||||
ui.data_mut(|data| data.insert_temp(host, pass));
|
||||
let frame = super::stitch_ui::overlay_frame(ui.ctx(), super::stitch_ui::SurfaceRole::Dialog, visual.opacity).inner_margin(18);
|
||||
let global_anchor = ui.ctx().layer_transform_to_global(anchor.layer_id).map_or(anchor.rect, |transform| transform * anchor.rect);
|
||||
let body_height = super::stitch_ui::floating_body_height(ui.ctx().content_rect(), global_anchor);
|
||||
let glass = settings_glass_supported(ui.ctx());
|
||||
self.panel_geometry["settingsGlass"] = json!(glass);
|
||||
// A model menu can extend beyond this surface. Its click or Escape
|
||||
// belongs to that child menu, not to the settings dismissal handler.
|
||||
let nested_open = [ModelRole::Chat,ModelRole::Copy,ModelRole::Image].into_iter().any(|role| {
|
||||
ui.data(|data| data.get_temp::<Id>(Id::unique(("agent-model-last-popup", role, true))))
|
||||
.is_some_and(|id| egui::Popup::is_id_open(ui.ctx(), id))
|
||||
});
|
||||
let mut popup_visible = true;
|
||||
egui::Popup::from_response(anchor)
|
||||
.frame(egui::Frame::NONE)
|
||||
.open_bool(&mut popup_visible)
|
||||
.close_behavior(if visual.interactive && !nested_open { egui::PopupCloseBehavior::CloseOnClickOutside } else { egui::PopupCloseBehavior::IgnoreClicks })
|
||||
.show(|ui| {
|
||||
let contents = |ui: &mut Ui| super::stitch_ui::overlay_contents(ui, visual, |ui| super::stitch_ui::scope_with_motion(ui, self.reduce_motion, |ui| {
|
||||
ui.set_width(360.0_f32.min((ui.ctx().content_rect().width() - 32.0).max(180.0)));
|
||||
ui.spacing_mut().item_spacing = vec2(8.0, 10.0);
|
||||
ui.spacing_mut().scroll.floating = false;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new("小壹设置").size(14.0).strong().color(t.text));
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
if super::stitch_ui::icon_button(ui, "x", 26.0, false, "关闭模型设置").clicked() {
|
||||
self.close_model_settings();
|
||||
}
|
||||
});
|
||||
});
|
||||
let body = egui::ScrollArea::vertical().id_salt("xiaoyi-settings-body").max_height(body_height).show(ui, |ui| {
|
||||
for (role, label) in [(ModelRole::Chat,"对话模型"),(ModelRole::Copy,"文案模型"),(ModelRole::Image,"生图模型")] {
|
||||
ui.label(RichText::new(label).size(12.0).color(t.text_dim));
|
||||
self.model_picker(ui, role, ui.available_width(), true);
|
||||
if role == ModelRole::Chat { self.thinking_picker(ui); }
|
||||
}
|
||||
if !self.copy_catalog_error.is_empty() {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label("文案目录未加载").on_hover_text(&self.copy_catalog_error);
|
||||
if super::stitch_ui::action_button(ui,"重试",super::stitch_ui::ButtonRole::Quiet,true).clicked(){self.send("restore",json!({}));}
|
||||
});
|
||||
}
|
||||
if !self.image_catalog_error.is_empty() {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label("生图目录未加载").on_hover_text(&self.image_catalog_error);
|
||||
if super::stitch_ui::action_button(ui, "重试", super::stitch_ui::ButtonRole::Quiet, true).clicked() {
|
||||
self.send("restore", json!({}));
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
icon(ui, "lock", t.text_dim);
|
||||
ui.label(RichText::new(if self.key_saved { "个人 Key 已连接" } else { "个人 Key 未连接" }).size(13.0).color(t.text));
|
||||
if self.busy.as_deref() == Some("configure") {
|
||||
super::stitch_ui::ai_loader(ui, ui.scope_id().with("configure-loading"), true, self.reduce_motion);
|
||||
ui.label("正在校验…");
|
||||
} else if super::stitch_ui::action_button(ui, if self.key_settings {
|
||||
"收起"
|
||||
} else if self.key_saved {
|
||||
"更换"
|
||||
} else {
|
||||
"设置"
|
||||
}, super::stitch_ui::ButtonRole::Quiet, self.busy.is_none() && !self.account.is_null())
|
||||
.clicked()
|
||||
{
|
||||
self.key_settings = !self.key_settings;
|
||||
if !self.key_settings {
|
||||
self.clear_settings_key_draft();
|
||||
}
|
||||
}
|
||||
});
|
||||
super::stitch_ui::morph_surface(ui, ui.scope_id().with("key-reveal"), self.key_settings, self.reduce_motion, |ui| {
|
||||
if !self.onboarding.is_open() {
|
||||
self.model_key_editor(ui, "settings", self.key_settings, false);
|
||||
}
|
||||
});
|
||||
super::stitch_ui::divider(ui);
|
||||
self.knowledge_settings(ui);
|
||||
super::stitch_ui::divider(ui);
|
||||
|
||||
if let Some(id) = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc) {
|
||||
let notifications = super::stitch_ui::action_button(ui, "通知与警告", super::stitch_ui::ButtonRole::Quiet, true);
|
||||
let count=ui.data(|data|data.get_temp::<AgentNotifications>(id)).map_or(0,|history|history.unread);
|
||||
if count>0 {
|
||||
// On the label's centre line, a badge's own half-width to the right of the control.
|
||||
let rect=Rect::from_center_size(notifications.rect.right_center()+vec2(15.0,0.0),vec2(24.0,20.0));
|
||||
super::stitch_ui::paint_badge(ui,id.with("unread-count"),rect,super::stitch_ui::BadgeKind::Count,&count.to_string(),self.reduce_motion);
|
||||
}
|
||||
self.panel_geometry["notificationsButton"] = rect_value(notifications.rect);
|
||||
if notifications.clicked() {
|
||||
ui.ctx().data_mut(|data| data.get_temp_mut_or_default::<AgentNotifications>(id).open = true);
|
||||
self.close_model_settings();
|
||||
}
|
||||
}
|
||||
// 有"通知与警告"时补一条分隔线;没有时上面已经是分隔线。
|
||||
let after_notifications = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc).is_some();
|
||||
self.client_version_settings(ui, after_notifications);
|
||||
let after_version = after_notifications || self.client_update.version["version"].is_string();
|
||||
self.storage_settings_section(ui, after_version);
|
||||
});
|
||||
// egui reports the pre-auto-shrink inner rect. Match the
|
||||
// actual vertical viewport used by ScrollArea::end, rather
|
||||
// than incorrectly counting its unused space as content.
|
||||
let mut body_rect = body.inner_rect;
|
||||
body_rect.set_height(body_rect.height().min(body.content_size.y));
|
||||
self.panel_geometry["settingsBody"] = rect_value(body_rect);
|
||||
self.panel_geometry["settingsContentHeight"] = json!(body.content_size.y);
|
||||
ui.add_space(4.0);
|
||||
}));
|
||||
if glass {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
show_settings_glass(ui, frame, t.card, visual.opacity, transform.scaling, contents);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
contents(ui);
|
||||
} else {
|
||||
super::stitch_ui::material_frame(ui, frame, contents);
|
||||
}
|
||||
});
|
||||
if open && !popup_visible && !nested_open {
|
||||
self.close_model_settings();
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn storage_settings_section(&mut self, ui: &mut Ui, show_divider: bool) {
|
||||
let reduced = self.reduce_motion;
|
||||
let ctx = ui.ctx().clone();
|
||||
let (action, modal_opened) = storage_settings_ui::with_machine_state(&ctx, |state| {
|
||||
let was_open = state.migrate_modal_open || state.cleanup_modal_open;
|
||||
let action = storage_settings_ui::storage_settings_card(ui, state, reduced, show_divider);
|
||||
let now_open = state.migrate_modal_open || state.cleanup_modal_open;
|
||||
(action, !was_open && now_open)
|
||||
});
|
||||
if modal_opened {
|
||||
self.close_model_settings();
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
if let Some(action) = action {
|
||||
let (method, payload) = action.to_request();
|
||||
let _ = self.tx.send(Request::Action(method.into(), payload));
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn storage_modals_ui(&mut self, ctx: &egui::Context) {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
let pass_id = Id::unique("xiaoyi-storage-modals-pass");
|
||||
let already_rendered = ctx.data(|data| data.get_temp::<u64>(pass_id) == Some(pass));
|
||||
if already_rendered {
|
||||
return;
|
||||
}
|
||||
ctx.data_mut(|data| data.insert_temp(pass_id, pass));
|
||||
let reduced = self.reduce_motion;
|
||||
let action = storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
storage_settings_ui::show_storage_modals(ctx, state, reduced)
|
||||
});
|
||||
if let Some(action) = action {
|
||||
let (method, payload) = action.to_request();
|
||||
let _ = self.tx.send(Request::Action(method.into(), payload));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// Experimental, local-acceptance-only opt-in. Until device-loss, resource
|
||||
/// failure, performance and real-window verification are complete, a normal
|
||||
/// launch uses the existing opaque popup and unchanged native renderer path.
|
||||
pub(in crate::jiansun) fn knowledge_connection_status(ui: &mut Ui, saved: bool, check: Option<&Result<(), String>>, checking: bool) {
|
||||
use super::stitch_ui::{StatusTone, status_label};
|
||||
let stored = if saved { "已保存到本机" } else { "本机未保存" };
|
||||
let (status, tone) = match (checking, check) {
|
||||
(true, _) => ("正在校验", StatusTone::Neutral),
|
||||
(false, Some(Ok(()))) => ("上次校验通过", StatusTone::Neutral),
|
||||
(false, Some(Err(_))) => ("上次校验失败", StatusTone::Error),
|
||||
(false, None) if saved => ("本次尚未校验", StatusTone::Neutral),
|
||||
(false, None) => ("等待配置", StatusTone::Neutral),
|
||||
};
|
||||
status_label(ui, &format!("{stored} · {status}"), tone);
|
||||
if let Some(Err(error)) = check.filter(|_| !checking) {
|
||||
status_label(ui, error, StatusTone::Error);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(in crate::jiansun) fn settings_glass_supported(ctx: &egui::Context) -> bool {
|
||||
let initialized = Id::unique("jiansun-settings-glass-opt-in-initialized");
|
||||
let should_initialize = ctx.data_mut(|data| {
|
||||
if data.get_temp::<bool>(initialized).unwrap_or(false) {
|
||||
false
|
||||
} else {
|
||||
data.insert_temp(initialized, true);
|
||||
true
|
||||
}
|
||||
});
|
||||
if should_initialize && std::env::var_os("PHOTOCRAFT_EXPERIMENTAL_STITCH_GLASS").as_deref() == Some(std::ffi::OsStr::new("1")) {
|
||||
eframe::egui_wgpu::stitch_backdrop_set_experiment_enabled(ctx, true);
|
||||
}
|
||||
eframe::egui_wgpu::stitch_backdrop_supported(ctx)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(in crate::jiansun) fn settings_glass_supported(_ctx: &egui::Context) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The paired callbacks bracket an opaque emergency underlay. The validated
|
||||
/// split renderer omits it; the normal renderer keeps it if a capability or
|
||||
/// planner check fails, including the current frame. This does not guarantee
|
||||
/// presentation after GPU device loss and is intentionally opt-in only.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(in crate::jiansun) fn show_settings_glass<R>(ui: &mut Ui, mut frame: egui::Frame, base: Color32, opacity: f32, scale: f32, contents: impl FnOnce(&mut Ui) -> R) {
|
||||
use eframe::egui_wgpu::BackdropMarker;
|
||||
|
||||
let begin = ui.painter().add(egui::Shape::Noop);
|
||||
let fallback = ui.painter().add(egui::Shape::Noop);
|
||||
let end = ui.painter().add(egui::Shape::Noop);
|
||||
frame.fill = frame.fill.gamma_multiply(0.58);
|
||||
let shown = super::stitch_ui::material_frame(ui, frame, contents);
|
||||
let rect = shown.response.rect - egui::epaint::MarginF32::from(frame.outer_margin);
|
||||
let radius = f32::from(frame.corner_radius.nw) * scale;
|
||||
let start_marker = BackdropMarker { blur_radius_points: 5.0 * scale, corner_radius_points: radius, opacity };
|
||||
let end_marker = BackdropMarker { blur_radius_points: 0.0, corner_radius_points: radius, opacity };
|
||||
ui.painter().set(begin, egui::Shape::Callback(start_marker.new_paint_callback(rect)));
|
||||
// Ignore Area's measurement fade, but retain the explicit panel transition
|
||||
// when a shrinking backdrop falls back to ordinary painting.
|
||||
let mut opaque_painter = ui.painter().clone();
|
||||
opaque_painter.set_opacity(opacity.clamp(0.0, 1.0));
|
||||
opaque_painter.set(fallback, egui::Shape::rect_filled(rect, frame.corner_radius, Color32::from_rgb(base.r(), base.g(), base.b())));
|
||||
ui.painter().set(end, egui::Shape::Callback(end_marker.new_paint_callback(rect)));
|
||||
}
|
||||
|
||||
@ -0,0 +1,75 @@
|
||||
use super::super::json;
|
||||
use super::super::{Value, Workspace};
|
||||
use super::models::ModelRole;
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn receive_chat_context_usage(&mut self,usage:&Value) {
|
||||
if usage["version"]==1&&self.models.iter().any(|model|model["key"]==self.model&&model["id"]==usage["model"])&&usage["modelKey"].as_str().is_none_or(|key|key==self.model){self.pi_context_usage=usage.clone();}
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn choose_model(&mut self, role: ModelRole, selected: String) {
|
||||
if self.key_saved && self.api_key.is_empty() {
|
||||
self.send("select-model", json!({"field":role.setting(),"selection":selected,
|
||||
"accountId":self.account["id"],"origin":self.origin}));
|
||||
} else {
|
||||
match role {
|
||||
ModelRole::Chat => self.model = selected,
|
||||
ModelRole::Copy => self.copy_model = selected,
|
||||
ModelRole::Image => self.image_model = selected,
|
||||
}
|
||||
self.model_ready = false;
|
||||
self.copy_ready = false;
|
||||
self.image_ready = false;
|
||||
if !self.onboarding.is_open() {
|
||||
self.open_model_settings();
|
||||
self.key_settings = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn receive_model_preference(&mut self, value: &Value) {
|
||||
if value["field"] == "thinkingLevel" {
|
||||
self.thinking_by_model = value["thinkingByModel"].clone();
|
||||
return;
|
||||
}
|
||||
let (selected, models, ready) = match value["field"].as_str() {
|
||||
Some("model") => (&mut self.model, &self.models, &mut self.model_ready),
|
||||
Some("copyModel") => (&mut self.copy_model, &self.copy_models, &mut self.copy_ready),
|
||||
Some("imageModel") => (&mut self.image_model, &self.image_models, &mut self.image_ready),
|
||||
_ => return,
|
||||
};
|
||||
let Some(choice) = value["selection"].as_str() else { return; };
|
||||
*selected = choice.into();
|
||||
*ready = self.key_saved && self.available_models.as_ref().is_some_and(|available| {
|
||||
models.iter().find(|model| model["key"] == choice).and_then(|model| model["id"].as_str())
|
||||
.is_some_and(|id| available.iter().any(|entry| entry == id))
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn open_model_settings(&mut self) {
|
||||
if !self.model_settings {
|
||||
self.model_settings = true;
|
||||
self.prompt_library.close();
|
||||
self.maybe_check_update_on_settings_open();
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn clear_settings_key_draft(&mut self) {
|
||||
if !self.onboarding.is_open() {
|
||||
self.api_key.clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn close_model_settings(&mut self) {
|
||||
if self.model_settings || self.key_settings {
|
||||
self.model_settings = false;
|
||||
self.key_settings = false;
|
||||
self.clear_settings_key_draft();
|
||||
self.xiaoyi_key.clear();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,85 @@
|
||||
use super::super::json;
|
||||
use super::super::Value;
|
||||
|
||||
/// Model ids are catalog keys written for machines. Known words become a
|
||||
/// readable name; one unknown word leaves the whole id untouched, rather
|
||||
/// than a half-translated label that matches no receipt.
|
||||
pub(in crate::jiansun) fn model_display_name(id: &str) -> String {
|
||||
let word = |word: &str| -> Option<String> {
|
||||
match word {
|
||||
"gpt" => Some("GPT".to_owned()),
|
||||
"vip" | "cl" | "2k" | "4k" => Some(word.to_ascii_uppercase()),
|
||||
"image" | "nano" | "banana" | "flare" | "burst" | "sunburst" | "lite" | "fast" | "pro" => {
|
||||
Some(format!("{}{}", word[..1].to_ascii_uppercase(), &word[1..]))
|
||||
}
|
||||
_ if !word.is_empty() && word.bytes().all(|byte| byte.is_ascii_digit() || byte == b'.') => Some(word.to_owned()),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let mut words = Vec::new();
|
||||
for part in id.split('-') {
|
||||
let Some(part) = word(part) else { return id.to_owned() };
|
||||
words.push(part);
|
||||
}
|
||||
if words.len() > 1 { words.join(" ") } else { id.to_owned() }
|
||||
}
|
||||
|
||||
/// Only the timestamp emitted by the active tool can start a live timer.
|
||||
|
||||
|
||||
#[derive(Clone,Copy,Debug,Hash,PartialEq,Eq)]
|
||||
pub(in crate::jiansun) enum ModelRole {Chat,Copy,Image}
|
||||
impl ModelRole {
|
||||
pub(in crate::jiansun) fn setting(self) -> &'static str {
|
||||
match self { Self::Chat => "model", Self::Copy => "copyModel", Self::Image => "imageModel" }
|
||||
}
|
||||
pub(in crate::jiansun) fn geometry(self)->&'static str {match self {Self::Chat=>"chatModel",Self::Copy=>"copyModel",Self::Image=>"imageModel"}}
|
||||
pub(in crate::jiansun) fn menu(self)->&'static str {match self {Self::Chat=>"chatModelMenu",Self::Copy=>"copyModelMenu",Self::Image=>"imageModelMenu"}}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn is_hidden_model(role: ModelRole, model: &Value) -> bool {
|
||||
if role == ModelRole::Chat && model["productionReady"] == false {
|
||||
return true;
|
||||
}
|
||||
let Some(id) = model["id"].as_str() else { return false };
|
||||
let id = id.to_ascii_lowercase();
|
||||
matches!(id.as_str(),
|
||||
"gpt-6.2-astra" | "claude-sonnet-4-6" | "gemini-4-argon" | "gemini-4-carbon"
|
||||
| "grok-4.5" | "grok-4.6" | "world-generation" | "deepseek-ocr"
|
||||
) || [
|
||||
"gpt-5.6-", "gpt-6-", "gpt-6.1-", "glm-5.3", "claude-fable-", "claude-opus-",
|
||||
"claude-haiku-4-5", "gemini-3-", "gemini-3.",
|
||||
].iter().any(|prefix| id.starts_with(prefix))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) const CONTEXT_UNAVAILABLE:&str="—";
|
||||
pub(in crate::jiansun) const CONTEXT_PENDING:&str="开始对话后显示使用情况";
|
||||
pub(in crate::jiansun) fn usage_count(value:&Value)->Option<u64>{value.as_u64().filter(|n|*n<=9_007_199_254_740_991)}
|
||||
pub(in crate::jiansun) fn context_for_model(usage:&Value,models:&[Value],selected:&str)->Option<Value>{
|
||||
let model=models.iter().find(|model|model["key"]==selected)?;
|
||||
let same=usage["version"]==1&&usage["model"]==model["id"]&&usage["modelKey"].as_str().is_none_or(|key|key==selected);
|
||||
let mut current=if same {usage.clone()} else {json!({"version":1,"model":model["id"],"modelKey":selected})};
|
||||
let has_capacity=current["contextWindow"].as_u64().is_some_and(|limit|limit>0)&¤t["capacitySource"].as_str().is_some_and(|source|!source.is_empty());
|
||||
if !has_capacity&&model["contextWindow"].as_u64().is_some_and(|limit|limit>0)&&model["contextWindowSource"].as_str().is_some_and(|source|!source.is_empty()) {
|
||||
current["contextWindow"]=model["contextWindow"].clone();current["capacitySource"]=model["contextWindowSource"].clone();
|
||||
}
|
||||
(same||current["contextWindow"].as_u64().is_some_and(|limit|limit>0)).then_some(current)
|
||||
}
|
||||
pub(in crate::jiansun) fn context_tokens(value:&Value)->Option<u64>{matches!(value["contextSource"].as_str(),Some("pi-session"|"pi-last-response")).then(||usage_count(&value["contextTokens"])).flatten()}
|
||||
pub(in crate::jiansun) fn context_fraction(usage:Option<&Value>)->Option<f32>{
|
||||
let value=usage?;
|
||||
let limit=usage_count(&value["contextWindow"])?;
|
||||
if limit==0||value["capacitySource"].as_str().is_none_or(str::is_empty){return None;}
|
||||
let used=context_tokens(value)?;
|
||||
if value["contextSource"]=="pi-last-response" {return Some((used as f64/limit as f64).clamp(0.0,1.0) as f32);}
|
||||
let native=&value["piContextUsage"];let percent=native["percent"].as_f64()?;
|
||||
(value["contextSource"]=="pi-session"&&usage_count(&native["tokens"])==Some(used)&&usage_count(&native["contextWindow"])==Some(limit)&&percent.is_finite()&&(0.0..=100.0).contains(&percent)).then_some((percent/100.0) as f32)
|
||||
}
|
||||
pub(in crate::jiansun) fn context_number(tokens:u64)->String {if tokens>=1_000_000 {format!("{:.0}M",tokens as f64/1_000_000.0)} else if tokens>=1_000 {format!("{:.0}K",tokens as f64/1_000.0)} else {tokens.to_string()}}
|
||||
pub(in crate::jiansun) fn context_label(usage:Option<&Value>)->String{
|
||||
let Some(value)=usage else {return CONTEXT_UNAVAILABLE.into()};
|
||||
let Some(limit)=usage_count(&value["contextWindow"]).filter(|limit|*limit>0) else {return CONTEXT_UNAVAILABLE.into()};
|
||||
if value["capacitySource"].as_str().is_none_or(str::is_empty){return CONTEXT_UNAVAILABLE.into();}
|
||||
let used=context_tokens(value).map_or_else(||"—".into(),context_number);
|
||||
format!("{used}/{}",context_number(limit))
|
||||
}
|
||||
@ -0,0 +1,129 @@
|
||||
use super::super::agent_panel::multi_project_ui;
|
||||
use super::super::stitch_timeline as timeline;
|
||||
use super::super::{PhotocraftApp, Workspace};
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn multi_project_view_model(
|
||||
&self,
|
||||
app: &PhotocraftApp,
|
||||
ctx: &egui::Context,
|
||||
) -> multi_project_ui::MultiProjectViewModel {
|
||||
if let Some(injected) = multi_project_ui::snapshot(ctx) {
|
||||
return injected;
|
||||
}
|
||||
let snap = self.multi_project_ui_snapshot(app);
|
||||
let active_section = match snap.active_section {
|
||||
super::multi_project_state::WorkspaceSectionKind::Projects => multi_project_ui::WorkspaceSection::Projects,
|
||||
super::multi_project_state::WorkspaceSectionKind::Brief => multi_project_ui::WorkspaceSection::Brief,
|
||||
super::multi_project_state::WorkspaceSectionKind::Canvas => multi_project_ui::WorkspaceSection::Canvas,
|
||||
};
|
||||
let map_status = |status: &super::multi_project_state::ProjectRunVisualStatus| match status {
|
||||
super::multi_project_state::ProjectRunVisualStatus::Running => multi_project_ui::MultiRunStatus::Running,
|
||||
super::multi_project_state::ProjectRunVisualStatus::Queued => multi_project_ui::MultiRunStatus::Queued,
|
||||
super::multi_project_state::ProjectRunVisualStatus::Paused => multi_project_ui::MultiRunStatus::Paused,
|
||||
super::multi_project_state::ProjectRunVisualStatus::PartialDelivered => multi_project_ui::MultiRunStatus::PartialDelivered,
|
||||
super::multi_project_state::ProjectRunVisualStatus::Completed => multi_project_ui::MultiRunStatus::Completed,
|
||||
super::multi_project_state::ProjectRunVisualStatus::Failed => multi_project_ui::MultiRunStatus::Failed,
|
||||
};
|
||||
let global_runs = snap
|
||||
.global_runs
|
||||
.into_iter()
|
||||
.map(|run| {
|
||||
let output_id = run.producing_output_id.unwrap_or_default();
|
||||
let output_label = if run.producing_output_label.is_empty() && !output_id.is_empty() {
|
||||
multi_project_ui::output_display_label(&output_id).to_owned()
|
||||
} else {
|
||||
run.producing_output_label
|
||||
};
|
||||
multi_project_ui::GlobalRunEntry {
|
||||
project_id: run.project_id,
|
||||
project_title: run.project_title,
|
||||
status: map_status(&run.status),
|
||||
producing_output_id: output_id,
|
||||
producing_output_label: output_label,
|
||||
progress_label: run.progress_label,
|
||||
elapsed_secs: run.elapsed_secs,
|
||||
active_slots: run.active_slots,
|
||||
has_attention: run.has_attention,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let active_project_title = (!snap.active_project_title.is_empty()).then_some(snap.active_project_title);
|
||||
let viewing_output_label = snap.viewing_output_id.as_deref().map(|id| {
|
||||
if snap.viewing_output_label.is_empty() {
|
||||
multi_project_ui::output_display_label(id).to_owned()
|
||||
} else {
|
||||
snap.viewing_output_label.clone()
|
||||
}
|
||||
});
|
||||
let producing_output_label = snap.producing_output_id.as_deref().map(|id| {
|
||||
if snap.producing_output_label.is_empty() {
|
||||
multi_project_ui::output_display_label(id).to_owned()
|
||||
} else {
|
||||
snap.producing_output_label.clone()
|
||||
}
|
||||
});
|
||||
multi_project_ui::MultiProjectViewModel {
|
||||
global_runs,
|
||||
max_concurrent: snap.max_concurrent,
|
||||
active_project_id: snap.active_project_id,
|
||||
active_project_title,
|
||||
active_section,
|
||||
viewing_output_id: snap.viewing_output_id,
|
||||
viewing_output_label,
|
||||
producing_output_id: snap.producing_output_id,
|
||||
producing_output_label,
|
||||
viewing_differs_from_producing: snap.viewing_differs_from_producing,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn handle_multi_project_action(
|
||||
&mut self,
|
||||
app: &mut PhotocraftApp,
|
||||
ctx: &egui::Context,
|
||||
action: multi_project_ui::MultiProjectAction,
|
||||
) {
|
||||
match &action {
|
||||
multi_project_ui::MultiProjectAction::SwitchToProject(project_id) => {
|
||||
if self.open_project_index(app, project_id).is_some() {
|
||||
self.focus_project_by_id(app, project_id);
|
||||
} else if let Some(item) = self
|
||||
.projects
|
||||
.iter()
|
||||
.find(|p| p["localId"].as_str() == Some(project_id.as_str()) || p["id"].as_str() == Some(project_id.as_str()))
|
||||
.cloned()
|
||||
{
|
||||
if let Err(error) = self.request_project_open(app, item) {
|
||||
self.error = error;
|
||||
}
|
||||
}
|
||||
}
|
||||
multi_project_ui::MultiProjectAction::PauseProject(project_id) => {
|
||||
if self.open_project_index(app, project_id).is_some() {
|
||||
self.pause_project_run(app, project_id);
|
||||
} else {
|
||||
super::production_controls::queue_action(
|
||||
ctx,
|
||||
"production-stop",
|
||||
super::production_controls::stop_input(timeline::StopMode::Pause),
|
||||
);
|
||||
}
|
||||
}
|
||||
multi_project_ui::MultiProjectAction::ResumeProject(project_id) => {
|
||||
if self.open_project_index(app, project_id).is_some() {
|
||||
self.resume_project_run(app, project_id);
|
||||
} else {
|
||||
self.resume_product_production(app);
|
||||
}
|
||||
}
|
||||
multi_project_ui::MultiProjectAction::JumpToProducingOutput { project_id, .. } => {
|
||||
if self.open_project_index(app, project_id).is_some() {
|
||||
self.focus_project_by_id(app, project_id);
|
||||
}
|
||||
self.jump_to_producing_output(app);
|
||||
}
|
||||
}
|
||||
multi_project_ui::push_action(ctx, action);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,66 @@
|
||||
use super::super::{Value, Workspace};
|
||||
use egui::Id;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(in crate::jiansun) struct AgentToast { pub(in crate::jiansun) shown_at: f64 }
|
||||
|
||||
pub(in crate::jiansun) fn toast_active(toast: &AgentToast, now: f64) -> bool {
|
||||
now.is_finite() && toast.shown_at.is_finite() && now >= toast.shown_at && now - toast.shown_at < 2.4
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn toast_id(origin: &str, account: &Value, project: &Value, doc: Option<u64>) -> Option<Id> {
|
||||
let account = account["id"].as_str().filter(|id| !id.is_empty())?;
|
||||
if origin.is_empty() { return None; }
|
||||
Some(Id::unique("jiansun-draft-toast").with((origin, account, project["localId"].as_str(), doc)))
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(in crate::jiansun) struct AgentNotifications {
|
||||
pub(in crate::jiansun) entries: Vec<String>,
|
||||
pub(in crate::jiansun) unread: usize,
|
||||
pub(in crate::jiansun) last_error: String,
|
||||
pub(in crate::jiansun) last_unknown: bool,
|
||||
pub(in crate::jiansun) open: bool,
|
||||
}
|
||||
|
||||
impl AgentNotifications {
|
||||
pub(in crate::jiansun) fn add(&mut self, value: &str) {
|
||||
if value.trim().is_empty() { return; }
|
||||
let mut chars = value.chars();
|
||||
let mut visible = chars.by_ref().take(4000).collect::<String>();
|
||||
if chars.next().is_some() { visible.push_str("…(内容已截断)"); }
|
||||
if self.entries.iter().any(|item| item == &visible) { return; }
|
||||
self.entries.push(visible);
|
||||
if self.entries.len() > 40 { self.entries.remove(0); }
|
||||
self.unread=(self.unread+1).min(self.entries.len());
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn observe(&mut self, error: &str, unknown: bool, warning: Option<&str>, receipts: &[Value]) {
|
||||
if !error.is_empty() && error != self.last_error { self.add(error); }
|
||||
self.last_error = error.to_owned();
|
||||
if unknown && !self.last_unknown && error.is_empty() { self.add("原请求结果待核查,未重复发送。"); }
|
||||
self.last_unknown = unknown;
|
||||
if let Some(warning) = warning { self.add(warning); }
|
||||
for message in receipts {
|
||||
if let Some(text) = message["text"].as_str().filter(|text| {
|
||||
text.starts_with("保存副本时有导出提示:") || text.starts_with("PSD副本已导出,导出提示:")
|
||||
}) { self.add(text); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn notification_id(origin: &str, account: &Value, project: &Value, doc: Option<u64>) -> Option<Id> {
|
||||
toast_id(origin, account, project, doc).map(|id| id.with("notifications"))
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn recent_notification_entries(&self, ctx: &egui::Context) -> Vec<String> {
|
||||
let Some(id) = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc) else {
|
||||
return Vec::new();
|
||||
};
|
||||
ctx.data(|data| data.get_temp::<AgentNotifications>(id))
|
||||
.map(|history| history.entries.into_iter().rev().take(12).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,112 @@
|
||||
use super::super::{RichText, Value};
|
||||
use super::super::{Tokens, Ui, Workspace, json};
|
||||
use super::rect_value;
|
||||
use super::notifications::{AgentNotifications, AgentToast, notification_id, toast_active};
|
||||
use egui::{Id, Rect};
|
||||
|
||||
/// Only called after an actual library item was inserted into the draft.
|
||||
pub(in crate::jiansun) fn post_draft_toast(ui: &Ui, id: Id) {
|
||||
let now = ui.input(|input| input.time);
|
||||
ui.ctx().data_mut(|data| data.insert_temp(id, AgentToast { shown_at: now }));
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn draw_draft_toast(ui: &Ui, id: Id, anchor: Rect, reduced: bool) {
|
||||
let Some(toast) = ui.ctx().data(|data| data.get_temp::<AgentToast>(id)) else { return };
|
||||
if !ui.is_rect_visible(anchor) { return; }
|
||||
let now = ui.input(|input| input.time);
|
||||
let active = toast_active(&toast, now);
|
||||
let visual = super::stitch_ui::overlay_transition(ui.ctx(), id.with("transition"), active, reduced);
|
||||
if visual.render {
|
||||
let position = egui::pos2(anchor.left() + 8.0, (anchor.top() - 36.0).max(ui.clip_rect().top()));
|
||||
egui::Area::new(id.with("surface")).order(egui::Order::Foreground).fixed_pos(position).interactable(false).show(ui.ctx(), |ui| {
|
||||
super::stitch_ui::overlay_frame(ui.ctx(), super::stitch_ui::SurfaceRole::Menu, visual.opacity).show(ui, |ui| {
|
||||
super::stitch_ui::overlay_contents(ui, visual, |ui| {
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
ui.label(RichText::new("已添加到草稿").size(12.0).color(t.text));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
if active {
|
||||
let remaining = (2.4 - (now - toast.shown_at)).max(0.01);
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(remaining));
|
||||
} else if !visual.render {
|
||||
ui.ctx().data_mut(|data| data.remove::<AgentToast>(id));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn notifications_ui(&mut self, ui: &mut Ui)->bool {
|
||||
self.panel_geometry["notificationCandidates"]=Value::Null;
|
||||
let marker = Id::unique("jiansun-notification-last-scope");
|
||||
let current = notification_id(&self.origin, &self.account, &self.project_context, self.owner_doc);
|
||||
let scope = current.unwrap_or_else(|| Id::unique("jiansun-notification-no-account"));
|
||||
let previous = ui.ctx().data(|data| data.get_temp::<Id>(marker));
|
||||
let switched = previous.is_some_and(|old| old != scope);
|
||||
if switched {
|
||||
ui.ctx().data_mut(|data| {
|
||||
if let Some(old) = previous { data.get_temp_mut_or_default::<AgentNotifications>(old).open = false; }
|
||||
if current.is_some() { data.get_temp_mut_or_default::<AgentNotifications>(scope).open = false; }
|
||||
});
|
||||
}
|
||||
ui.ctx().data_mut(|data| data.insert_temp(marker, scope));
|
||||
let Some(id) = current else { return false };
|
||||
let mut history = ui.ctx().data(|data| data.get_temp::<AgentNotifications>(id)).unwrap_or_default();
|
||||
let unknown = self.result_needs_check();
|
||||
if switched {
|
||||
// Do not attribute an old in-memory error to the newly selected account.
|
||||
history.last_error = self.error.clone(); history.last_unknown = unknown;
|
||||
}
|
||||
let identity_prefix = self.local_identity("");
|
||||
let project_id = self.owner_doc.filter(|doc| self.loaded_draft == Some(*doc))
|
||||
.and_then(|doc| self.open_projects.get(&doc))
|
||||
.and_then(|identity| identity.strip_prefix(&identity_prefix))
|
||||
.filter(|project| !project.is_empty());
|
||||
let receipts = if project_id.is_some() { self.messages.as_slice() } else { &[] };
|
||||
let diagnostics = super::operation_error::DiagnosticContext {
|
||||
version: &self.client_update.version,
|
||||
project_id,
|
||||
messages: receipts,
|
||||
};
|
||||
let warning = self.prompt_library.warning();
|
||||
history.observe(&self.error, unknown, warning.as_deref(), receipts);
|
||||
let visual = super::stitch_ui::overlay_transition(ui.ctx(), id.with("transition"), history.open, self.reduce_motion);
|
||||
if visual.interactive {history.unread=0;}
|
||||
let mut view_candidates=false;
|
||||
if visual.render {
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let screen = ui.ctx().content_rect();
|
||||
let width = (screen.width() - 64.0).clamp(1.0, 360.0);
|
||||
let list_height = (screen.height() - 200.0).clamp(1.0, 260.0);
|
||||
let mut bounds = Rect::NOTHING;
|
||||
let closed = super::stitch_ui::dialog(ui, id.with("window"), "通知与警告", history.open, self.reduce_motion, width, |ui| {
|
||||
ui.label(RichText::new("本次会话的通知;导出提示也保留在项目对话中。").size(12.0).color(t.text_dim));
|
||||
if history.entries.is_empty() { ui.label("暂无通知"); }
|
||||
egui::ScrollArea::vertical().id_salt(id.with("entries")).max_height(list_height).show(ui, |ui| {
|
||||
for (index,entry) in history.entries.iter().enumerate().rev() {
|
||||
super::stitch_ui::divider(ui);
|
||||
let active=!self.error.is_empty() && entry==&self.error;
|
||||
ui.label(RichText::new(if active {"当前问题"} else {"历史通知"}).size(super::agent_stream::TEXT_META).color(t.text_dim));
|
||||
let has_candidates=self.template_workflow["slots"].as_array().into_iter().flatten()
|
||||
.any(|slot|slot["candidates"].as_array().into_iter().flatten().any(|candidate|candidate["status"]=="complete"));
|
||||
if active && super::operation_error::message(entry).image_read && has_candidates {
|
||||
let button=super::stitch_ui::action_button(ui,"查看已有候选",super::stitch_ui::ButtonRole::Secondary,true);
|
||||
self.panel_geometry["notificationCandidates"]=rect_value(button.rect);
|
||||
if button.clicked() {view_candidates=true;}
|
||||
}
|
||||
super::operation_error::details(ui,id.with(("error-details",index)),entry,self.reduce_motion,Some(&diagnostics));
|
||||
}
|
||||
});
|
||||
bounds = ui.min_rect();
|
||||
});
|
||||
if bounds.is_positive() { self.panel_geometry["notifications"] = rect_value(bounds); }
|
||||
if closed || view_candidates { history.open = false; ui.ctx().request_repaint(); }
|
||||
}
|
||||
self.panel_geometry["notificationsOpen"] = json!(history.open);
|
||||
ui.ctx().data_mut(|data| data.insert_temp(id, history));
|
||||
view_candidates
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,544 @@
|
||||
use super::super::{CenterView, Duration, Instant, Request, stitch_timeline as timeline, workflow_bridge};
|
||||
use super::production_reply_ui::{read_delivery_manifest, recover_delivery_manifest};
|
||||
use super::turn_ui::{active_tool_elapsed, frame_image_ratio, image_card_size};
|
||||
use egui::{Align, Layout};
|
||||
use super::super::{PhotocraftApp, RichText, Tokens, Ui, Value, Workspace, agent_motion, json};
|
||||
use super::rect_value;
|
||||
use super::turn_ui::subject_label;
|
||||
use egui::{Id, vec2};
|
||||
|
||||
pub(in crate::jiansun) fn workflow_scope(proposal: &Value, workflow: &Value) -> String {
|
||||
if matches!(proposal["intent"].as_str(), Some("export" | "export_psd")) {
|
||||
return "当前画布".into();
|
||||
}
|
||||
if !matches!(proposal["intent"].as_str(), Some("fill_output" | "review_candidates" | "generate_candidate")) {
|
||||
return String::new();
|
||||
}
|
||||
let output = match proposal["outputId"].as_str() {
|
||||
Some("main_images") => "主图",
|
||||
Some("sku_images") => "SKU",
|
||||
_ => "详情",
|
||||
};
|
||||
let target = if let Some(slot_id) = proposal["slotId"].as_str() {
|
||||
workflow["slots"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|slot| slot["id"] == slot_id)
|
||||
.and_then(|slot| if proposal["intent"] == "generate_candidate" { slot["fieldId"].as_str() } else { slot["documentId"].as_str() })
|
||||
.unwrap_or("图位已变化")
|
||||
} else {
|
||||
"全组"
|
||||
};
|
||||
if proposal["intent"] == "generate_candidate" {
|
||||
format!("{output} · {target} · {}", proposal["variant"].as_str().unwrap_or("候选已变化"))
|
||||
} else {
|
||||
format!("{output} · {target}")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl Workspace {
|
||||
/// Only render request-owned snapshots; the currently selected canvas
|
||||
/// object is not a reliable target once an asynchronous request is sent.
|
||||
pub(in crate::jiansun) fn processing_target(&self, app: &PhotocraftApp) -> Option<Value> {
|
||||
let doc = app.session.active().map(|state| state.doc.id.0)?;
|
||||
match self.busy.as_deref() {
|
||||
Some("slot-append" | "slot-generate") => self.running_workflow_generation(doc)
|
||||
.map(|op| {
|
||||
let label = self.template_workflow["slots"].as_array().into_iter().flatten()
|
||||
.find(|slot| slot["id"] == op["slotId"] && slot["outputId"] == op["outputId"])
|
||||
.map(|slot| &slot["label"]);
|
||||
let kind = if op["candidateId"].is_string() { "candidate" } else { "slot" };
|
||||
json!({"kind":kind,"slotId":op["slotId"],"outputId":op["outputId"],"label":label,
|
||||
"productVariantId":op["productVariantId"],"candidateId":op["candidateId"]})
|
||||
})
|
||||
.or_else(|| self.canvas_workspace.submitted_generation_target(&self.account["id"], &self.origin, Some(doc)).cloned()),
|
||||
Some("agent" | "pi-agent")
|
||||
if self.owner_doc == Some(doc)
|
||||
&& self.pi_request_scope["project"]["documentId"].as_u64() == Some(doc)
|
||||
&& self.pi_request_scope["account"]["id"] == self.account["id"]
|
||||
&& self.pi_request_scope["account"]["origin"] == self.origin
|
||||
&& self.pi_request_scope["project"]["localId"]
|
||||
.as_str()
|
||||
.is_none_or(|local| self.open_projects.get(&doc).is_some_and(|current| current == local)) =>
|
||||
{
|
||||
self.pi_request_scope.get("subject").filter(|target| target.is_object()).cloned()
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn processing_card_ui(&mut self, app: &PhotocraftApp, ui: &mut Ui) {
|
||||
super::glow_pill::bind(ui, app.gpu_render_state.as_ref());
|
||||
if self.batch_progress_visible() { return; }
|
||||
let reduced = self.reduce_motion || agent_motion::hidden(ui, ui.available_rect_before_wrap().intersect(ui.clip_rect()))
|
||||
|| self.owner_doc.is_some_and(|owner| app.session.active().is_none_or(|state| state.doc.id.0 != owner));
|
||||
let pending = self.pending();
|
||||
let running = self.canvas_workspace.adoption_preparing() || (pending && !self.agent_effects_paused);
|
||||
let processing_id = Id::unique("jiansun-processing-card");
|
||||
let image_task = matches!(self.busy.as_deref(), Some("image" | "slot-generate" | "slot-append" | "image-recover" | "slot-recover"))
|
||||
|| self.pending_image.is_some();
|
||||
// Conversation status uses AI Loader, never the image-generation
|
||||
// surface. Reset a preceding image remnant before another task starts.
|
||||
if pending && (!image_task || self.canvas_workspace.adoption_preparing()) {
|
||||
let _ = agent_motion::task_visibility(ui, processing_id, false, true);
|
||||
self.agent_status_ui(ui, running);
|
||||
return;
|
||||
}
|
||||
let visibility = agent_motion::task_visibility(ui, processing_id, pending && image_task, reduced);
|
||||
if visibility <= 0.0 {
|
||||
ui.data_mut(|data|data.remove::<(Id,f64,f64)>(Id::unique("glow-pill-image-clock")));
|
||||
return;
|
||||
}
|
||||
let mut card_ui = ui.new_child(egui::UiBuilder::new().id_salt("task-card-content").max_rect(ui.available_rect_before_wrap()));
|
||||
card_ui.set_opacity(visibility);
|
||||
let parent_ui = ui;
|
||||
let ui = &mut card_ui;
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let waiting_for_image = pending && matches!(self.busy.as_deref(), Some("image" | "slot-generate" | "slot-append"))
|
||||
&& self.pending_image.is_none()
|
||||
&& !self.agent_effects_paused;
|
||||
// Keep the neutral placeholder only long enough to fade out. Its
|
||||
// visual lifetime does not change the underlying task state or title.
|
||||
// The submitted user message stays at the same index while tool and
|
||||
// result records append. Selection, hover and viewport coordinates do
|
||||
// not define the identity or restart the waiting mark.
|
||||
let waiting_id = Id::unique(("jiansun-result-waiting", &self.origin, self.account["id"].as_str(),
|
||||
self.owner_doc, self.messages.iter().rposition(|message| message["role"] == "user")));
|
||||
let waiting_visibility = ui.ctx().animate_bool_with_time(
|
||||
waiting_id.with("visibility"),
|
||||
waiting_for_image,
|
||||
if reduced { 0.0 } else { 0.16 },
|
||||
);
|
||||
let active = running;
|
||||
let title = if !pending {
|
||||
"处理已结束"
|
||||
} else if !active {
|
||||
"已停止本地操作 · 原请求保留"
|
||||
} else if waiting_for_image {
|
||||
if self.image_progress.is_empty() { "正在生成图片…" } else { super::stitch_ui::processing_label(&self.image_progress) }
|
||||
} else if matches!(self.busy.as_deref(), Some("recover" | "image-recover" | "slot-recover")) {
|
||||
"正在核查原结果…"
|
||||
} else if !self.queue.is_empty() || self.pending_image.is_some() {
|
||||
"正在更新画布…"
|
||||
} else if self.busy.as_deref() == Some("slot-copy") {
|
||||
"正在生成图位文案…"
|
||||
} else {
|
||||
self.workflow_waiting.as_ref().and_then(|value| value["label"].as_str()).unwrap_or("正在回复…")
|
||||
};
|
||||
let title = title.to_owned();
|
||||
let target = self.processing_target(app).filter(|target| target["kind"].as_str().is_some_and(|kind| !kind.is_empty() && kind != "project"));
|
||||
// The conversation frame has its own margins. Size the task surface
|
||||
// from the actual dock/clip rather than compounding those margins.
|
||||
let dock_width = self.panel_geometry["panel"][2].as_f64().map(|width| width as f32).unwrap_or(ui.clip_rect().width());
|
||||
let desired_card_width = (dock_width - 32.0).max(0.0).min((ui.clip_rect().right() - ui.cursor().left()).max(0.0));
|
||||
let ratio = (waiting_visibility > 0.0).then(|| {
|
||||
let slot = target.as_ref()?;
|
||||
self.template_workflow["slots"].as_array()?.iter()
|
||||
.find(|value| value["id"] == slot["slotId"]
|
||||
&& (slot["outputId"].is_null() || slot["outputId"] == value["outputId"])
|
||||
&& (slot["productVariantId"].is_null() || value["variantId"].is_null() || slot["productVariantId"] == value["variantId"]))
|
||||
.and_then(|value| frame_image_ratio(&value["frame"]))
|
||||
}).flatten().unwrap_or(16.0 / 9.0);
|
||||
let image_size = image_card_size(desired_card_width, ratio);
|
||||
let elapsed_ms = if active {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()
|
||||
.and_then(|now| u64::try_from(now.as_millis()).ok())
|
||||
.and_then(|now| active_tool_elapsed(&self.messages, self.pi_run.as_deref(), now))
|
||||
} else { None };
|
||||
ui.add_space(10.0);
|
||||
let card = super::stitch_ui::surface(ui, super::stitch_ui::SurfaceRole::Task, |ui| {
|
||||
let waiting_background = agent_motion::reserve_background(ui);
|
||||
let content_width = ((if waiting_visibility > 0.0 { image_size.x } else { desired_card_width }) - 26.0).max(0.0);
|
||||
ui.set_width(content_width);
|
||||
if waiting_visibility > 0.0 {
|
||||
ui.set_min_height((image_size.y - 26.0).max(0.0));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
if waiting_visibility > 0.0 {
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(26.0, 26.0), egui::Sense::hover());
|
||||
let motion=if waiting_for_image {super::siri_orb::Motion::Thinking} else {super::siri_orb::Motion::Still};
|
||||
if let Some(orb) = super::siri_orb::paint(ui,waiting_id.with("identity"),rect,motion,reduced) {
|
||||
self.panel_geometry["processingBlob"] = rect_value(rect);
|
||||
self.panel_geometry["processingBlobPhase"] = json!(orb.phase);
|
||||
self.panel_geometry["processingBlobMoving"] = json!(!reduced && waiting_for_image);
|
||||
self.panel_geometry["processingIdentity"] = json!("siri-orb");
|
||||
}
|
||||
} else {
|
||||
super::stitch_ui::ai_loader(ui, processing_id.with("loader"), active, reduced);
|
||||
}
|
||||
let reserve = if active { 26.0 + ui.spacing().item_spacing.x } else { 0.0 };
|
||||
let label_width = (ui.available_width() - reserve).max(0.0);
|
||||
let label = egui::Label::new(RichText::new(title).size(13.0).color(t.text)).truncate();
|
||||
if waiting_visibility > 0.0 {
|
||||
ui.allocate_ui_with_layout(vec2(label_width, 26.0), Layout::left_to_right(Align::Center), |ui| {
|
||||
ui.set_width(label_width);
|
||||
ui.add(label);
|
||||
});
|
||||
} else {
|
||||
ui.add_sized(vec2(label_width, 26.0), label);
|
||||
}
|
||||
if active {
|
||||
let stop = super::stitch_ui::icon_button(ui, "square", 26.0, false, "停止本地自动操作,保留原请求");
|
||||
self.panel_geometry["taskStop"] = rect_value(stop.rect);
|
||||
if stop.clicked() { self.abort_chat_run(); }
|
||||
}
|
||||
});
|
||||
if let Some(ms) = elapsed_ms {
|
||||
let seconds = ms / 1_000;
|
||||
let response = ui.label(RichText::new(format!("工具已运行 {}:{:02}", seconds / 60, seconds % 60)).size(super::agent_stream::TEXT_META).color(t.text_dim));
|
||||
if !agent_motion::hidden(ui, response.rect) { ui.ctx().request_repaint_after(Duration::from_millis(1_000 - ms % 1_000)); }
|
||||
}
|
||||
if let Some(target) = &target {
|
||||
ui.add_space(5.0);
|
||||
let label = subject_label(target, &self.template_workflow);
|
||||
ui.add(egui::Label::new(RichText::new(label).size(12.0).color(t.text_dim)).wrap());
|
||||
}
|
||||
waiting_background
|
||||
});
|
||||
self.panel_geometry["processing"] = rect_value(card.response.rect);
|
||||
if waiting_visibility > 0.0 {
|
||||
self.panel_geometry["processingPlaceholder"] = rect_value(card.response.rect);
|
||||
}
|
||||
let now=ui.input(|input|input.time);
|
||||
let elapsed=ui.data_mut(|data|{
|
||||
let id=Id::unique("glow-pill-image-clock");
|
||||
let mut clock=data.get_temp::<(Id,f64,f64)>(id).filter(|clock|clock.0==waiting_id).unwrap_or((waiting_id,now,0.0));
|
||||
if active && !reduced {clock.2=(now-clock.1)*0.55;}
|
||||
data.insert_temp(id,clock);clock.2
|
||||
});
|
||||
let activity=ui.ctx().animate_bool_with_time(processing_id.with("working"),active,if reduced || agent_motion::hidden(ui, card.response.rect) {0.0} else {0.16});
|
||||
let mut pulse=if reduced {super::glow_pill::Pulse::default()} else {super::glow_pill::waiting(elapsed)};
|
||||
pulse.surge*=activity;
|
||||
pulse.warp*=activity;
|
||||
super::glow_pill::paint(ui,super::glow_pill::Surface {id:processing_id,rect:card.response.rect,radius:t.radius,
|
||||
time:if reduced {2.4} else {elapsed},pulse,opacity:visibility,background:Some(card.inner),text_range:None,flanks:0.0});
|
||||
if active && !reduced { agent_motion::schedule(ui, card.response.rect, agent_motion::Pace::Idle); }
|
||||
self.panel_geometry["processingLightMode"] = json!(if active {"glow-pill"} else {"paused"});
|
||||
self.panel_geometry["processingOpacity"] = json!(visibility);
|
||||
parent_ui.advance_cursor_after_rect(ui.min_rect());
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn agent_status_ui(&mut self, ui: &mut Ui, running: bool) {
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let id = Id::unique(("jiansun-agent-status", &self.origin, self.account["id"].as_str(), self.owner_doc,
|
||||
self.messages.iter().rposition(|message| message["role"] == "user")));
|
||||
let preparing = self.canvas_workspace.adoption_preparing();
|
||||
let title = if preparing { "准备采纳…" }
|
||||
else if self.pi_ui_waiting() { "等待你的回复…" }
|
||||
else if !running { "已停止本地操作 · 原请求保留" }
|
||||
else if self.busy.as_deref() == Some("recover") { "正在核查原结果…" }
|
||||
else if !self.queue.is_empty() { "正在更新画布…" }
|
||||
else { self.workflow_waiting.as_ref().and_then(|value| value["label"].as_str()).unwrap_or("正在处理…") }.to_owned();
|
||||
// A stable, unframed row remains throughout the turn, including the
|
||||
// genuine network waits between tools. No glow, panel or target repeat.
|
||||
let shown = ui.allocate_ui_with_layout(vec2(ui.available_width(), 26.0), Layout::right_to_left(Align::Center), |ui| {
|
||||
ui.set_min_height(26.0);
|
||||
// Reserve the stop target first. Generic shared field rows use a
|
||||
// 32pt interaction height; this status has its own compact 26pt
|
||||
// geometry and cannot inherit that minimum through horizontal().
|
||||
if running && !preparing {
|
||||
let stop = super::stitch_ui::icon_button(ui, "square", 26.0, false, "停止本地自动操作,保留原请求");
|
||||
self.panel_geometry["taskStop"] = rect_value(stop.rect);
|
||||
if stop.clicked() { self.abort_chat_run(); }
|
||||
}
|
||||
ui.allocate_ui_with_layout(vec2(ui.available_width(), 26.0), Layout::left_to_right(Align::Center), |ui| {
|
||||
super::stitch_ui::ai_loader(ui, id.with("loader"), running, true);
|
||||
ui.add(egui::Label::new(RichText::new(title).size(12.0).color(t.text_dim)).truncate());
|
||||
});
|
||||
});
|
||||
self.panel_geometry["agentStatus"] = rect_value(shown.response.rect);
|
||||
self.panel_geometry["processingLightMode"] = json!("inactive");
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_outcome_ui(&mut self, ui: &mut Ui, production: bool, app: &PhotocraftApp) {
|
||||
use timeline::RunOutcome;
|
||||
self.finish_delivery_hint(app, ui);
|
||||
if production {
|
||||
return;
|
||||
}
|
||||
let receipt = self.messages.iter().rev().take_while(|row| row["role"] != "user")
|
||||
.find(|row| row["productionSummary"].is_object());
|
||||
let checkpoint = &self.product_checkpoint;
|
||||
let delivery = receipt.map_or(&checkpoint["productionDelivery"], |row| &row["productionDelivery"]);
|
||||
let path = delivery["path"].as_str();
|
||||
let saved = path.and_then(|path| read_delivery_manifest(ui, path).map(|manifest| (path.to_owned(), manifest)))
|
||||
.or_else(|| (path.is_none() && !delivery["error"].is_string())
|
||||
.then(|| recover_delivery_manifest(ui, checkpoint)).flatten());
|
||||
if let Some((path, manifest)) = saved {
|
||||
if self.delivery_completion {
|
||||
self.sync_confirm = false;
|
||||
self.delivery_completion = false;
|
||||
}
|
||||
let label = if manifest["allOutputsCompleted"] == true {
|
||||
"本地已落盘"
|
||||
} else {
|
||||
"部分成品已落盘"
|
||||
};
|
||||
let count = manifest["completedOutputs"].as_u64().zip(manifest["totalOutputs"].as_u64())
|
||||
.map_or_else(|| label.to_owned(), |(done, total)| format!("{label} · {done}/{total} 份"));
|
||||
let outcome = if manifest["allOutputsCompleted"] == true {
|
||||
RunOutcome::Completed { summary: &count, path: &path }
|
||||
} else {
|
||||
RunOutcome::PartialDelivery { summary: &count, path: &path }
|
||||
};
|
||||
let mut open = false;
|
||||
timeline::run_outcome_card(ui, outcome, None, |_| open = true, |ui| {
|
||||
self.delivery_receipts_ui(app, ui, &manifest);
|
||||
});
|
||||
if open && app.services.open_folder.as_ref()
|
||||
.is_none_or(|open| open(std::path::Path::new(&path)).is_err())
|
||||
{
|
||||
self.error = "无法打开文件夹,请检查目录是否仍可访问".into();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let producing = self.pi_product_production;
|
||||
let outcome = if producing && self.agent_effects_paused {
|
||||
Some(RunOutcome::Stopped { request_kept: self.pending() || self.unknown })
|
||||
} else if producing && self.result_needs_check() {
|
||||
Some(RunOutcome::NeedsCheck)
|
||||
} else if self.pending() {
|
||||
None
|
||||
} else if let Some(error) = delivery["error"].as_str() {
|
||||
Some(RunOutcome::Failed { category: super::stitch_state::ErrorCategory::classify(error) })
|
||||
} else if path.is_some() || receipt.is_some() {
|
||||
Some(RunOutcome::Waiting { reason: "成品交付尚未确认" })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(outcome) = outcome {
|
||||
timeline::run_outcome_card(ui, outcome, None, |_| {}, |_| {});
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn delivery_receipts_ui(&mut self, app: &PhotocraftApp, ui: &mut Ui, manifest: &Value) {
|
||||
use super::stitch_ui::{self as kit, ButtonRole::Quiet, StatusTone::{Error, Neutral}};
|
||||
let doc = app.session.active().map(|doc| doc.doc.id.0);
|
||||
let receipt = &self.project_context["materialDelivery"];
|
||||
let same_delivery = receipt["deliveryId"].as_str().map_or(
|
||||
self.project_context["status"] == "completed", |id| manifest["deliveryId"] == id);
|
||||
let material = receipt["materialId"].as_str().filter(|_| same_delivery);
|
||||
let listing = &receipt["listingStatus"];
|
||||
let withdrawn = material.is_some() && receipt["state"] == "removed";
|
||||
let pending = self.busy.as_deref() == Some("project-sync")
|
||||
|| (same_delivery && matches!(receipt["state"].as_str(), Some("pending" | "uploading")));
|
||||
let upload_error = same_delivery.then(|| receipt["error"].as_str()).flatten()
|
||||
.or_else(|| self.error.strip_prefix("素材库提交失败:"));
|
||||
let (library_label, library_tone) = if withdrawn {
|
||||
("已撤回", Neutral)
|
||||
} else if material.is_some() {
|
||||
("已建档", Neutral)
|
||||
} else if upload_error.is_some() {
|
||||
("提交失败", Error)
|
||||
} else if pending {
|
||||
("正在提交", Neutral)
|
||||
} else if manifest["allOutputsCompleted"] == true {
|
||||
("待入库", Neutral)
|
||||
} else {
|
||||
("待补齐成品", Neutral)
|
||||
};
|
||||
let (listing_label, listing_tone) = match (material.is_some() && !withdrawn, listing["state"].as_str()) {
|
||||
(false, _) => ("未触发", Neutral),
|
||||
(true, Some("pending")) => ("等待上架", Neutral),
|
||||
(true, Some("listing")) => ("上架中", Neutral),
|
||||
(true, Some("listed")) => ("已上架", Neutral),
|
||||
(true, Some("failed")) => ("上架失败", Error),
|
||||
(true, _) => ("待查询", Neutral),
|
||||
};
|
||||
let now = Instant::now();
|
||||
let mut refresh = material.is_some() && !withdrawn && doc.is_some_and(|doc|
|
||||
self.listing_read_at.is_none_or(|(last_doc, next)| last_doc != doc || now >= next));
|
||||
let mut submit = false;
|
||||
let mut open_listing = false;
|
||||
let mut jump = None;
|
||||
kit::status_label(ui, &format!("素材库 · {library_label}"), library_tone);
|
||||
kit::status_label(ui, &format!("外部自动上架 · {listing_label}"), listing_tone);
|
||||
if upload_error.is_some() || listing_tone == Error || self.listing_read_error.is_some() || self.finished_web_error.is_some() {
|
||||
kit::disclosure(ui, ui.scope_id().with("delivery-details"), "查看提交与上架详情", false, self.reduce_motion, |ui| {
|
||||
for error in [upload_error, self.listing_read_error.as_deref(), self.finished_web_error.as_deref(),
|
||||
(listing_tone == Error).then(|| listing["message"].as_str()).flatten()].into_iter().flatten() {
|
||||
super::operation_error::details(ui, ui.next_auto_id(), error, self.reduce_motion, None);
|
||||
}
|
||||
if self.listing_read_error.is_some() && kit::action_button(ui, "重新查询", Quiet, doc.is_some()).clicked() {
|
||||
refresh = true;
|
||||
}
|
||||
if listing_tone == Error && kit::action_button(ui, "打开上架工作台", Quiet, !self.finished_web_pending).clicked() {
|
||||
open_listing = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
if material.is_none() && manifest["allOutputsCompleted"] == true && !pending {
|
||||
let ready = doc.is_some() && self.busy.is_none() && self.saving.is_none()
|
||||
&& !self.project_operation_pending() && !self.creation_dirty && !self.unknown;
|
||||
let label = if upload_error.is_some() { "重试入库" } else { "提交素材库" };
|
||||
submit = kit::action_button(ui, label, Quiet, ready).clicked();
|
||||
}
|
||||
|
||||
if let Some(hints) = manifest["reviewHints"].as_array().filter(|hints| !hints.is_empty()) {
|
||||
kit::disclosure(ui, ui.scope_id().with("delivery-review"), &format!("人工核对({})", hints.len()), false, self.reduce_motion, |ui| {
|
||||
for hint in hints {
|
||||
let Some(message) = hint.as_str().or_else(|| hint["message"].as_str()) else { continue };
|
||||
ui.label(crate::client_brand::user_error(message, "有一项成品需要人工核对"));
|
||||
let output = hint["outputId"].as_str().or_else(|| {
|
||||
[("详情页:", "detail"), ("主图:", "main_images"), ("SKU 图:", "sku_images"), ("SKU:", "sku_images")]
|
||||
.into_iter().find_map(|(prefix, output)| message.starts_with(prefix).then_some(output))
|
||||
});
|
||||
let Some(output) = output else { continue };
|
||||
let exact = hint["slotId"].is_string() || !hint["layerId"].is_null() || hint["nativeLayerId"].is_u64()
|
||||
|| !hint["screenId"].is_null() || !hint["pageId"].is_null() || hint["screenIndex"].is_u64();
|
||||
let label = if exact { "定位到画布" } else { "查看成品" };
|
||||
if kit::action_button(ui, label, Quiet, doc.is_some()).clicked() {
|
||||
jump = Some((output.to_owned(), hint.clone()));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if refresh && let Some(doc) = doc {
|
||||
self.listing_read_at = Some((doc, now + Duration::from_secs(15)));
|
||||
if self.tx.send(Request::Action("delivery-status".into(), json!({"doc":doc}))).is_err() {
|
||||
self.listing_read_error = Some("本机服务已停止,请重启后查看".into());
|
||||
}
|
||||
}
|
||||
if material.is_some() && !withdrawn {
|
||||
ui.ctx().request_repaint_after(Duration::from_secs(15));
|
||||
}
|
||||
if open_listing && let Some((doc, material)) = doc.zip(material) {
|
||||
self.finished_web_error = None;
|
||||
self.finished_web_pending = self.tx.send(Request::Action("finished-web-open".into(),
|
||||
json!({"doc":doc,"materialId":material}))).is_ok();
|
||||
if !self.finished_web_pending {
|
||||
self.finished_web_error = Some("本机服务已停止,请重启后重试".into());
|
||||
}
|
||||
}
|
||||
if submit {
|
||||
self.sync_action(app, "project-sync", json!({"status":"completed","deliveryId":manifest["deliveryId"]}));
|
||||
}
|
||||
if let Some((output, hint)) = jump {
|
||||
self.locate_delivery_hint(app, ui, &output, hint);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn locate_delivery_hint(&mut self, app: &PhotocraftApp, ui: &Ui, output: &str, hint: Value) {
|
||||
let target = json!({"outputId":output,"variantId":hint["variantId"]});
|
||||
if let Err(error) = self.slot_action(app, "slot-skeleton", target) {
|
||||
self.error = error;
|
||||
return;
|
||||
}
|
||||
ui.data_mut(|data| data.insert_temp(self.delivery_hint_id(), (output.to_owned(), hint)));
|
||||
self.show_center(CenterView::Canvas, app.session.active().is_some());
|
||||
self.creation_open = false;
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn delivery_hint_id(&self) -> Id {
|
||||
Id::unique(("delivery-review-locate", &self.origin, self.account["id"].as_str(), self.owner_doc))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn finish_delivery_hint(&mut self, app: &PhotocraftApp, ui: &Ui) {
|
||||
if self.product_view_pending() || self.busy.as_deref() == Some("slot-skeleton") {
|
||||
return;
|
||||
}
|
||||
let Some((output, hint)) = ui.data_mut(|data| data.remove_temp::<(String, Value)>(self.delivery_hint_id())) else { return };
|
||||
let workflow = &self.template_workflow;
|
||||
if workflow["outputId"] != output || hint["variantId"].is_string() && hint["variantId"] != workflow["variantId"] {
|
||||
self.error = "未能打开这条提示对应的成品".into();
|
||||
return;
|
||||
}
|
||||
let variant = workflow["variantId"].as_str();
|
||||
let native_id = hint["nativeLayerId"].as_u64().or(hint["layerId"].as_u64())
|
||||
.or_else(|| hint["layerId"].as_str().and_then(|id| id.strip_prefix('L').unwrap_or(id).parse().ok()))
|
||||
.filter(|&id| app.session.active().is_some_and(|state| state.doc.layer(photocraft_doc::LayerId(id)).is_some()));
|
||||
let pages = || workflow["outputs"].as_array().into_iter().flatten().filter(|page| page["outputId"] == output);
|
||||
let page = hint["pageId"].as_str().or(hint["screenId"].as_str())
|
||||
.or_else(|| hint["screenIndex"].as_u64().and_then(|index| pages().nth(index as usize)?["documentId"].as_str()));
|
||||
let slot = workflow["slots"].as_array().into_iter().flatten()
|
||||
.filter(|slot| slot["outputId"] == output && (slot["variantId"].is_null() || slot["variantId"].as_str() == variant))
|
||||
.find(|slot| match hint["slotId"].as_str() {
|
||||
Some(id) => slot["id"] == id,
|
||||
None => page.is_some_and(|page| slot["documentId"] == page),
|
||||
})
|
||||
.and_then(|slot| slot["id"].as_str());
|
||||
if native_id.is_some() || slot.is_some() {
|
||||
self.canvas_locate(json!({"kind":"selection","outputId":output,"productVariantId":variant,
|
||||
"targets":[{"nativeLayerId":native_id,"slotId":slot,"locateImageSlot":page.is_none() && native_id.is_none()}]}));
|
||||
ui.ctx().request_repaint();
|
||||
} else if ["slotId", "layerId", "nativeLayerId", "pageId", "screenId", "screenIndex"]
|
||||
.iter().any(|key| !hint[*key].is_null())
|
||||
{
|
||||
self.error = "当前成品中已找不到该核对位置".into();
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn workflow_card_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
let receipt_id = Id::unique(("workflow-approved", &self.origin, self.account["id"].as_str(), self.project_context["localId"].as_str(), self.owner_doc));
|
||||
let receipt = ui.data(|data| data.get_temp::<(Value, usize)>(receipt_id));
|
||||
let proposal = match self.workflow.proposal().cloned() { Some(proposal) => proposal, None => match &receipt { Some((proposal, _)) => proposal.clone(), None => return } };
|
||||
let resolved = receipt.as_ref().filter(|(previous, _)| previous == &proposal).map(|(_, chosen)| *chosen);
|
||||
let intent = proposal["intent"].as_str().unwrap_or("");
|
||||
let label = match intent {
|
||||
"analyze" => "开始分析",
|
||||
"selling_points" => "生成一批",
|
||||
"plan" => "生成方案",
|
||||
"review_plan" => "查看方案",
|
||||
"install_template" => "载入模板",
|
||||
"slot_copy" => "生成文案",
|
||||
"apply_copy" => "回填文案",
|
||||
"generate_candidate" => "生成此候选",
|
||||
"review_candidates" => "查看候选",
|
||||
"fill_output" => "回填画布",
|
||||
"export" => "导出…",
|
||||
"export_psd" => "导出 PSD…",
|
||||
_ => return,
|
||||
};
|
||||
let running = self.busy.is_some() || self.pi_run.is_some() || self.saving.is_some() || !self.queue.is_empty() || self.pending_image.is_some();
|
||||
let current = workflow_bridge::proposal_current(self, app);
|
||||
let unknown =
|
||||
self.unknown && matches!(intent, "analyze" | "selling_points" | "plan" | "install_template" | "slot_copy" | "apply_copy" | "generate_candidate");
|
||||
let ready = !running && current && !unknown;
|
||||
self.panel_geometry["workflowReady"] = json!(ready);
|
||||
let scope = workflow_scope(&proposal, &self.template_workflow);
|
||||
ui.add_space(10.0);
|
||||
let state = if let Some(choice) = resolved { timeline::ApprovalState::Decided(choice) }
|
||||
else if unknown { timeline::ApprovalState::Blocked("结果待核查") }
|
||||
else if !current { timeline::ApprovalState::Blocked("内容已更新") }
|
||||
else { timeline::ApprovalState::Awaiting };
|
||||
let card = timeline::approval_card(ui, receipt_id.with(proposal.to_string()), timeline::ApprovalCard {
|
||||
title: proposal["title"].as_str().unwrap_or(label), scope: (!scope.is_empty()).then_some(scope.as_str()),
|
||||
instruction: proposal["instruction"].as_str().filter(|s| !s.trim().is_empty()),
|
||||
action: label, opt_out: "暂不处理", state,
|
||||
}, ready, self.reduce_motion);
|
||||
if resolved.is_none() {
|
||||
if ready && ui.clip_rect().contains_rect(card.action.rect) {
|
||||
self.panel_geometry["workflowAccept"] = rect_value(card.action.rect);
|
||||
}
|
||||
if card.action.clicked() {
|
||||
match self.accept_workflow(app) {
|
||||
Ok(_) => { ui.data_mut(|data| data.insert_temp(receipt_id, (proposal.clone(), 0_usize))); }
|
||||
Err(error) => self.error = error,
|
||||
}
|
||||
}
|
||||
if let Some(response) = card.opt_out {
|
||||
if ui.clip_rect().contains_rect(response.rect) { self.panel_geometry["workflowDismiss"] = rect_value(response.rect); }
|
||||
if response.clicked() {
|
||||
self.workflow_dismiss();
|
||||
ui.data_mut(|data| data.insert_temp(receipt_id, (proposal, 1_usize)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if running {
|
||||
ui.horizontal(|ui| {
|
||||
super::stitch_ui::ai_loader(ui, ui.scope_id().with("workflow-saving"), true, self.reduce_motion);
|
||||
if self.saving.is_some() { ui.label("正在保存…"); }
|
||||
});
|
||||
}
|
||||
self.panel_geometry["workflowCard"] = rect_value(card.rect);
|
||||
if !running && self.workflow.take_card_reveal() {
|
||||
ui.scroll_to_rect_animation(card.rect, Some(Align::BOTTOM), egui::style::ScrollAnimation::none());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,192 @@
|
||||
use super::super::{Duration, PhotocraftApp, Ui, Value, Workspace, agent_motion, json, stitch_state::{RunState, WorkerStage}, stitch_timeline::{self as timeline, GoalProgressPanel}, template_preparation};
|
||||
use super::rect_value;
|
||||
use super::models::usage_count;
|
||||
use super::production_reply_ui::production_image_cells;
|
||||
use egui::{Align, Id, Layout, Rect, Response, vec2};
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn production_head_ui(&mut self, app: &PhotocraftApp, ui: &mut Ui) {
|
||||
use super::agent_stream::Cell;
|
||||
use timeline::{GoalBudget, GoalSlot, GoalStage, StagePhase, WorkerState};
|
||||
|
||||
let id = Id::unique(("jiansun-production-head", &self.origin, self.account["id"].as_str(), self.owner_doc));
|
||||
let run = self.product_production.as_ref();
|
||||
let preparing = self.product_start_queued.then(|| template_preparation::state(&self.template_progress));
|
||||
let waiting = run.is_some_and(|run| run.waiting_to_resume()) || self.template_progress["phase"] == "waiting" && preparing.is_some();
|
||||
let use_stream = preparing.is_none() && run.is_none_or(|run| run.showing_agent_progress());
|
||||
let progress = self.workflow.production_progress();
|
||||
let title = use_stream.then(|| progress["heading"].as_str().or_else(|| self.stream_reply.lines().next())).flatten()
|
||||
.filter(|line| !line.is_empty()).map(str::to_owned)
|
||||
.or_else(|| preparing.as_ref().map(|(label, _)| label.clone()))
|
||||
.or_else(|| run.and_then(|run| run.progress_label()))
|
||||
.unwrap_or_else(|| "正在准备详情页".into());
|
||||
let title = title.trim_start_matches("小壹").trim_start_matches([' ', '·']);
|
||||
let show_work = use_stream || run.is_some_and(|run| run.waiting_for_originals());
|
||||
let source = |key: &str| progress[key].as_array().filter(|_| show_work).map(Vec::as_slice).unwrap_or_default();
|
||||
let image_source = source("pictureCells");
|
||||
let copy_source = source("copyCells");
|
||||
let cells_of = |rows: &[Value]| rows.iter().map(|cell| match cell["state"].as_str() {
|
||||
Some("verified") => Cell::Verified,
|
||||
Some("filled") => Cell::Filled,
|
||||
Some("preview") => Cell::Preview,
|
||||
_ => Cell::Empty,
|
||||
}).collect::<Vec<_>>();
|
||||
let mut image_cells = cells_of(image_source);
|
||||
production_image_cells(app, self, progress, &mut image_cells);
|
||||
let copy_cells = cells_of(copy_source);
|
||||
let workers = if show_work { self.production_workers() } else { Vec::new() };
|
||||
let worker_states: Vec<_> = workers.iter().map(|worker| WorkerState {
|
||||
number: worker.number, stage: worker.stage, slot: &worker.slot, active: worker.active,
|
||||
}).collect();
|
||||
let filled = image_cells.iter().filter(|cell| cell.filled()).count();
|
||||
let current_counts = (if image_cells.is_empty() { progress["rendered"].as_u64().unwrap_or(0) as usize } else { filled },
|
||||
if image_cells.is_empty() { progress["total"].as_u64().unwrap_or(0) as usize } else { image_cells.len() });
|
||||
let fraction = preparing.as_ref().and_then(|(_, fraction)| *fraction).or_else(||
|
||||
(show_work && current_counts.1 > 0).then(|| current_counts.0 as f32 / current_counts.1 as f32));
|
||||
let working = run.and_then(|run| run.working_output());
|
||||
let current = working.as_ref().and_then(|row| row["outputId"].as_str())
|
||||
.or_else(|| show_work.then(|| progress["outputId"].as_str()).flatten())
|
||||
.or_else(|| (preparing.is_some() || self.pi_product_production && fraction.is_some()).then_some("detail"));
|
||||
let requested = run.map(|run| run.requested_outputs());
|
||||
let pending = run.map(|run| run.pending_outputs());
|
||||
let contains = |value: &Option<Value>, output: &str| value.as_ref().and_then(Value::as_array)
|
||||
.is_some_and(|rows| rows.iter().any(|row| row["outputId"] == output));
|
||||
let outputs = [("detail", "详情"), ("main_images", "主图"), ("sku_images", "SKU")];
|
||||
let pipeline: Vec<_> = outputs.iter().filter(|(output, _)| requested.is_none() || contains(&requested, output))
|
||||
.map(|(output, name)| (*name, if current == Some(*output) { StagePhase::Current(fraction.unwrap_or(0.0)) }
|
||||
else if contains(&requested, output) && !contains(&pending, output) { StagePhase::Done }
|
||||
else { StagePhase::Queued })).collect();
|
||||
let slots = || image_source.iter().zip(&image_cells).map(|(row, cell)| GoalSlot {
|
||||
label: row["label"].as_str().unwrap_or("图位"),
|
||||
state: match workers.iter().find(|worker| worker.active && worker.row["slotId"] == row["slotId"]).map(|worker| worker.stage) {
|
||||
Some(WorkerStage::Generating) => timeline::SlotState::Generating,
|
||||
Some(WorkerStage::Reviewing) => timeline::SlotState::Reviewing,
|
||||
_ if row["state"] == "failed" => timeline::SlotState::Failed,
|
||||
_ if cell.filled() => timeline::SlotState::Done,
|
||||
_ => timeline::SlotState::Queued,
|
||||
},
|
||||
}).collect();
|
||||
let stages: Vec<_> = outputs.iter().filter(|(_, name)| pipeline.iter().any(|(shown, _)| shown == name))
|
||||
.map(|(output, name)| {
|
||||
let selected = current == Some(*output);
|
||||
let (done, total, unit) = if selected && show_work { (current_counts.0, current_counts.1, "图位") }
|
||||
else { (usize::from(pipeline.contains(&(*name, StagePhase::Done))), 1, "份") };
|
||||
GoalStage { name, done, total, unit, elapsed: None, tokens: None,
|
||||
waiting_canvas: self.workflow.waiting_canvas(output),
|
||||
slots: if selected && show_work { slots() } else { Vec::new() } }
|
||||
}).collect();
|
||||
let head = super::production_controls::HeadControls::read(&self.production_control_state());
|
||||
let resume_ready = self.can_resume_product();
|
||||
let budget = if let Some(run) = run {
|
||||
GoalBudget::Time { elapsed: run.elapsed(), limit: None }
|
||||
} else if let Some(used) = usage_count(&progress["tokensUsed"]) {
|
||||
GoalBudget::Tokens { used, limit: usage_count(&progress["tokenBudget"]) }
|
||||
} else {
|
||||
GoalBudget::Unreported
|
||||
};
|
||||
let clock_paused = run.is_some_and(|run| run.clock_paused());
|
||||
let mut controls = head.view(resume_ready);
|
||||
if clock_paused && matches!(controls.stop, timeline::StopPhase::Idle | timeline::StopPhase::Delivered) {
|
||||
controls.stop = timeline::StopPhase::Paused;
|
||||
}
|
||||
let state = if clock_paused { RunState::WaitingResume }
|
||||
else if self.pi_ui_waiting() { RunState::WaitingUser }
|
||||
else if waiting { RunState::WaitingResume } else { RunState::Running };
|
||||
ui.add_space(10.0);
|
||||
let full = ui.available_rect_before_wrap();
|
||||
let inner = Rect::from_min_max(full.left_top() + vec2(16.0, 0.0), full.right_bottom() - vec2(16.0, 0.0));
|
||||
let mut column = ui.new_child(egui::UiBuilder::new().id_salt(id).max_rect(inner).layout(Layout::top_down(Align::Min)));
|
||||
column.spacing_mut().item_spacing.y = 4.0;
|
||||
let result = timeline::goal_progress_panel(&mut column, id, GoalProgressPanel {
|
||||
title, state, budget, pipeline: &pipeline, image_cells: &image_cells, copy_cells: ©_cells,
|
||||
workers: &worker_states, roadmap: Some(&stages), controls: run.is_some().then_some(controls),
|
||||
}, self.reduce_motion || self.product_view_detached(), |index| {
|
||||
let row = &image_source[index];
|
||||
let status = match image_cells[index] { Cell::Verified => "已核验", Cell::Filled => "已上画布", Cell::Preview => "有候选待采纳", Cell::Empty => "待填" };
|
||||
format!("图片 {} · {} · {status}", index + 1, row["label"].as_str().unwrap_or("图位"))
|
||||
});
|
||||
if let GoalBudget::Time { elapsed, .. } = budget
|
||||
&& !clock_paused
|
||||
&& !agent_motion::hidden(ui, result.rect)
|
||||
{
|
||||
// 首分钟显示秒,之后只在分钟数变化时刷新。
|
||||
let seconds = elapsed.as_secs();
|
||||
let next = if seconds < 60 { 1 } else { 60 - seconds % 60 };
|
||||
ui.ctx().request_repaint_after(Duration::from_secs(next));
|
||||
}
|
||||
let worker_geometry = result.workers.into_iter().map(|mut row| {
|
||||
if let Some(worker) = workers.iter().find(|worker| row["worker"] == worker.number) {
|
||||
row["step"] = json!(worker.step);
|
||||
row["review"] = json!(worker.review);
|
||||
}
|
||||
row
|
||||
}).collect::<Vec<_>>();
|
||||
let located = result.slot_clicked.and_then(|index| image_source.get(index)).filter(|row| row["slotId"].is_string())
|
||||
.map(|row| json!({"kind":"slot","slotId":row["slotId"],"outputId":progress["outputId"],"productVariantId":progress["variantId"]}));
|
||||
self.panel_geometry["productionProgressTag"] = rect_value(result.toggle.rect);
|
||||
self.panel_geometry["productionTitle"] = rect_value(result.title);
|
||||
self.panel_geometry["productionProgress"] = rect_value(result.rect);
|
||||
self.panel_geometry["productionShelf"] = rect_value(result.rect);
|
||||
self.panel_geometry["productionProgressRail"] = result.rail.map_or(Value::Null, rect_value);
|
||||
self.panel_geometry["productionImageCells"] = result.image_cells;
|
||||
self.panel_geometry["productionCopyCells"] = result.copy_cells;
|
||||
self.panel_geometry["productionWorkers"] = json!(worker_geometry);
|
||||
if let Some(target) = located { self.canvas_locate(target); }
|
||||
if let Some(stop) = result.stop {
|
||||
self.panel_geometry["taskStop"] = rect_value(stop.rect);
|
||||
if stop.clicked() { self.abort_chat_run(); }
|
||||
}
|
||||
if let Some(controls) = &result.controls {
|
||||
use timeline::StopMode;
|
||||
// "停止"沿用外部脚本已在读的 taskStop,点开是停止菜单;"只暂停"直接执行,另外两项先确认。
|
||||
let choice = |mode| controls.choices.iter().find(|(shown, _)| *shown == mode).map_or(Value::Null, |(_, rect)| rect_value(*rect));
|
||||
self.panel_geometry["taskStop"] = rect_value(controls.stop.rect);
|
||||
self.panel_geometry["productionResume"] = controls.resume.as_ref().map_or(Value::Null, |resume| rect_value(resume.rect));
|
||||
self.panel_geometry["productionStopPause"] = choice(StopMode::Pause);
|
||||
self.panel_geometry["productionStopEnd"] = choice(StopMode::End);
|
||||
self.panel_geometry["productionStopDeliver"] = choice(StopMode::Deliver);
|
||||
self.panel_geometry["productionStopStatus"] = controls.status.map_or(Value::Null, rect_value);
|
||||
self.panel_geometry["productionBudget"] = controls.budget.map_or(Value::Null, rect_value);
|
||||
if controls.resume.as_ref().is_some_and(Response::clicked) {
|
||||
self.resume_product_production(app);
|
||||
}
|
||||
match controls.chosen {
|
||||
Some(StopMode::Pause) => super::production_controls::queue_action(ui.ctx(), "production-stop",
|
||||
super::production_controls::stop_input(StopMode::Pause)),
|
||||
Some(mode) => super::production_controls::open_stop_confirm(ui.ctx(), mode),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
self.stop_confirm_ui(ui, head.phase().ready());
|
||||
ui.advance_cursor_after_rect(column.min_rect());
|
||||
ui.add_space(2.0);
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn production_assets_ui(&mut self, ui: &mut Ui, doc: u64) {
|
||||
if super::stitch_ui::action_button(ui, "打开本地文件夹", super::stitch_ui::ButtonRole::Quiet, true).clicked() {
|
||||
self.open_generated_folder(doc);
|
||||
}
|
||||
if let Some((id, message)) = &self.canvas_workspace.generated_folder_status
|
||||
&& *id == doc
|
||||
{
|
||||
super::stitch_ui::status_label(ui, message, super::stitch_ui::StatusTone::Neutral);
|
||||
}
|
||||
let mut locate = None;
|
||||
egui::ScrollArea::vertical().id_salt("returned-assets").show(ui, |ui| {
|
||||
let width = ui.available_width();
|
||||
let columns = ((width + 8.0) / 128.0).floor().max(1.0) as usize;
|
||||
let cell = ((width + 8.0) / columns as f32 - 8.0).min(144.0);
|
||||
egui::Grid::new("returned-assets-grid").num_columns(columns)
|
||||
.min_col_width(cell).max_col_width(cell).spacing(vec2(8.0, 8.0))
|
||||
.show(ui, |ui| {
|
||||
for (index, image) in self.production_assets().enumerate() {
|
||||
if let Some(target) = self.image_result(ui, image, cell, None) { locate = Some(target); }
|
||||
if (index + 1) % columns == 0 { ui.end_row(); }
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(target) = locate { self.canvas_locate(target); }
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,154 @@
|
||||
use super::super::{PhotocraftApp, Workspace};
|
||||
use super::super::{Arc, Ui, Value};
|
||||
|
||||
/// shared native label retains selectable text and its existing rich styling.
|
||||
pub(in crate::jiansun) fn production_turn(command: Option<&str>) -> bool {
|
||||
command.is_some_and(|command| {
|
||||
matches!(command, "制作详情、主图和 SKU" | "继续整套制作" | "一键制作整套详情页")
|
||||
|| ["制作详情页 ·", "制作主图 ·", "制作 SKU ·"].iter().any(|prefix| command.starts_with(prefix))
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_reply_text(text: &str, streaming: bool, workflow: &Value) -> String {
|
||||
let mut labels = std::collections::HashMap::new();
|
||||
let mut insert = |id, label| {
|
||||
labels.entry(id).and_modify(|current| {
|
||||
if *current != Some(label) {
|
||||
*current = None;
|
||||
}
|
||||
}).or_insert(Some(label));
|
||||
};
|
||||
for output in workflow["outputs"].as_array().into_iter().flatten() {
|
||||
if let (Some(id), Some(name)) = (output["documentId"].as_str(), output["name"].as_str()) {
|
||||
insert(id, name);
|
||||
}
|
||||
for field in output["fields"].as_array().into_iter().flatten() {
|
||||
if let (Some(id), Some(label)) = (field["fieldId"].as_str(), field["label"].as_str()) {
|
||||
insert(id, label);
|
||||
}
|
||||
}
|
||||
}
|
||||
let tool_tags = [("<tool_calls>", "</tool_calls>"), ("<tool_call>", "</tool_call>")];
|
||||
let mut visible = String::new();
|
||||
let mut remaining = text;
|
||||
while let Some((index, start, end)) = tool_tags.iter()
|
||||
.filter_map(|&(start, end)| remaining.find(start).map(|index| (index, start, end)))
|
||||
.min_by_key(|&(index, _, _)| index)
|
||||
{
|
||||
visible.push_str(&remaining[..index]);
|
||||
let body = &remaining[index + start.len()..];
|
||||
remaining = body.split_once(end).map_or("", |(_, tail)| tail);
|
||||
}
|
||||
if streaming && let Some(index) = remaining.rfind('<')
|
||||
&& tool_tags.iter().any(|(tag, _)| tag.starts_with(&remaining[index..]))
|
||||
{
|
||||
remaining = &remaining[..index];
|
||||
}
|
||||
visible.push_str(remaining);
|
||||
let text = visible.as_str();
|
||||
let mut value = String::with_capacity(text.len());
|
||||
let mut chars = text.char_indices().peekable();
|
||||
while let Some((start, c)) = chars.next() {
|
||||
let is_word = |c: char| c.is_ascii_alphanumeric() || matches!(c, '-' | '_');
|
||||
if !is_word(c) {
|
||||
value.push(c);
|
||||
continue;
|
||||
}
|
||||
while chars.next_if(|&(_, c)| is_word(c)).is_some() {}
|
||||
let end = chars.peek().map_or(text.len(), |&(end, _)| end);
|
||||
let token = &text[start..end];
|
||||
if token.len() >= 16 && token.bytes().all(|ch| ch.is_ascii_hexdigit()) && token.bytes().any(|ch| ch.is_ascii_alphabetic()) {
|
||||
value.push_str("内部编号");
|
||||
continue;
|
||||
}
|
||||
value.push_str(labels.get(token).copied().flatten().unwrap_or(match token {
|
||||
"sources" => "资料来源",
|
||||
"links" => "图文对应关系",
|
||||
_ => crate::client_brand::reply_word(token),
|
||||
}));
|
||||
}
|
||||
value.replace("分句编号", "句子对应关系").replace("分句索引", "句子对应关系")
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn read_delivery_manifest(ui: &Ui, path: &str) -> Option<Arc<Value>> {
|
||||
let folder = std::path::Path::new(path);
|
||||
if !folder.is_absolute() { return None; }
|
||||
let file = folder.join("交付清单.json");
|
||||
let metadata = file.metadata().ok()?;
|
||||
let stamp = (metadata.modified().ok()?, metadata.len());
|
||||
let id = ui.scope_id().with("saved-delivery-manifest");
|
||||
type Cache = (std::path::PathBuf, (std::time::SystemTime, u64), Arc<Value>);
|
||||
if let Some((_, _, manifest)) = ui.data(|data| data.get_temp::<Cache>(id))
|
||||
.filter(|(cached_file, cached_stamp, _)| cached_file == &file && *cached_stamp == stamp)
|
||||
{
|
||||
return Some(manifest);
|
||||
}
|
||||
let manifest: Value = serde_json::from_slice(&std::fs::read(&file).ok()?).ok()?;
|
||||
manifest["allOutputsCompleted"].as_bool()?;
|
||||
let manifest = Arc::new(manifest);
|
||||
ui.data_mut(|data| data.insert_temp(id, (file, stamp, Arc::clone(&manifest))));
|
||||
Some(manifest)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn recover_delivery_manifest(ui: &Ui, checkpoint: &Value) -> Option<(String, Arc<Value>)> {
|
||||
let root = checkpoint["deliveryDir"].as_str()?;
|
||||
if let Some(manifest) = read_delivery_manifest(ui, root)
|
||||
&& (checkpoint["deliveryId"].is_null() || manifest["deliveryId"] == checkpoint["deliveryId"])
|
||||
{
|
||||
return Some((root.to_owned(), manifest));
|
||||
}
|
||||
let delivery_id = checkpoint["deliveryId"].as_str()?;
|
||||
let dir = std::path::Path::new(root);
|
||||
if !dir.is_absolute() { return None; }
|
||||
let stamp = dir.metadata().ok()?.modified().ok()?;
|
||||
let id = ui.scope_id().with(("recover-delivery-path", root, delivery_id));
|
||||
type Cache = (std::time::SystemTime, Option<String>);
|
||||
let path = if let Some((_, path)) = ui.data(|data| data.get_temp::<Cache>(id)).filter(|(time, _)| *time == stamp) {
|
||||
path
|
||||
} else {
|
||||
let path = dir.read_dir().ok()?.flatten().filter_map(|entry| {
|
||||
entry.file_type().ok()?.is_dir().then(|| entry.path().into_os_string().into_string().ok()).flatten()
|
||||
}).find(|path| read_delivery_manifest(ui, path).is_some_and(|manifest| manifest["deliveryId"] == delivery_id));
|
||||
ui.data_mut(|data| data.insert_temp(id, (stamp, path.clone())));
|
||||
path
|
||||
}?;
|
||||
let manifest = read_delivery_manifest(ui, &path)?;
|
||||
(manifest["deliveryId"] == delivery_id).then_some((path, manifest))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_image_cells(
|
||||
app: &PhotocraftApp, workspace: &Workspace, progress: &Value, cells: &mut [super::agent_stream::Cell],
|
||||
) {
|
||||
use super::agent_stream::Cell;
|
||||
let Some((target, workflow)) = workspace.production_canvas(app) else { return };
|
||||
let Some(variant) = progress["variantId"].as_str() else { return };
|
||||
if workflow["canvasFirst"] != true || workflow["outputId"] != progress["outputId"] || workflow["variantId"] != variant {
|
||||
return;
|
||||
}
|
||||
let Some(slots) = workflow["slots"].as_array() else { return };
|
||||
for (row, state) in progress["pictureCells"].as_array().into_iter().flatten().zip(cells) {
|
||||
let Some(slot_id) = row["slotId"].as_str() else { continue };
|
||||
let Some(id) = slots.iter().find(|slot| slot["id"] == slot_id && slot["outputId"] == progress["outputId"]
|
||||
&& slot["variantId"] == variant).and_then(|slot| slot["nativeLayerId"].as_u64()) else { continue };
|
||||
let id = photocraft_doc::LayerId(id);
|
||||
let visible = target.doc.layer(id).is_some_and(|layer| layer.visible && match &layer.content {
|
||||
photocraft_doc::LayerContent::Smart(smart) => !matches!(&smart.source,
|
||||
photocraft_doc::SmartSource::Embedded { file_name, .. } if file_name == "template-empty.png"),
|
||||
photocraft_doc::LayerContent::Raster(_) => true,
|
||||
_ => false,
|
||||
});
|
||||
*state = if visible && *state == Cell::Verified
|
||||
&& super::canvas_workspace::adopted(&target.doc, slot_id, variant).is_some() {
|
||||
Cell::Verified
|
||||
} else if visible {
|
||||
Cell::Filled
|
||||
} else if app.has_slot_preview(&target.doc, id) || slots.iter().any(|slot|
|
||||
slot["id"] == slot_id && slot["variantId"] == variant && slot["candidates"].as_array().into_iter()
|
||||
.flatten().any(|candidate| candidate["status"] == "complete")) {
|
||||
Cell::Preview
|
||||
} else {
|
||||
Cell::Empty
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,95 @@
|
||||
use super::super::{PhotocraftApp, RichText, Ui, Value, Workspace, composer_references, json, reference_media};
|
||||
use super::rect_value;
|
||||
use super::artifact_preview_ui::activate_reference;
|
||||
use super::turn_ui::{paint_reference_thumbnail, subject_label};
|
||||
use egui::{Frame, Response, vec2};
|
||||
|
||||
pub(in crate::jiansun) const REFERENCE_WIDTH: f32 = 132.0;
|
||||
pub(in crate::jiansun) const REFERENCE_GAP: f32 = 4.0;
|
||||
|
||||
pub(in crate::jiansun) fn reference_columns(width: f32) -> usize {
|
||||
((width + REFERENCE_GAP) / (REFERENCE_WIDTH + REFERENCE_GAP)).floor().max(1.0) as usize
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn reference_shelf_height(count: usize, width: f32) -> f32 {
|
||||
if count == 0 { return 0.0; }
|
||||
let rows = count.div_ceil(reference_columns(width)).min(3);
|
||||
rows as f32 * (24.0 + REFERENCE_GAP) - REFERENCE_GAP + 6.0
|
||||
}
|
||||
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn reference_shelf(&mut self, app: &PhotocraftApp, ui: &mut Ui, references: &[Value], height: f32) {
|
||||
let mut detach = None;
|
||||
let mut target = None;
|
||||
let mut rects = Vec::new();
|
||||
let columns = reference_columns(ui.available_width());
|
||||
egui::ScrollArea::vertical().id_salt("composer-reference-scroll").max_height(height)
|
||||
.auto_shrink([false, true]).show(ui, |ui| {
|
||||
let width = REFERENCE_WIDTH.min(ui.available_width()).max(1.0);
|
||||
ui.spacing_mut().item_spacing = vec2(REFERENCE_GAP, REFERENCE_GAP);
|
||||
ui.spacing_mut().interact_size.y = 24.0;
|
||||
for (row, items) in references.chunks(columns).enumerate() {
|
||||
ui.horizontal(|ui| {
|
||||
for (column, reference) in items.iter().enumerate() {
|
||||
let index = row * columns + column;
|
||||
ui.push_id(index, |ui| {
|
||||
let label = subject_label(reference, &self.template_workflow);
|
||||
let glyph = if composer_references::image_reference(reference) { "image" }
|
||||
else if matches!(reference["component"].as_str(), Some("pixelMask" | "vectorMask")) { "layer-mask" }
|
||||
else if reference["layerKind"] == "Type" { "type" } else { "layers" };
|
||||
let task = reference["taskId"].as_str();
|
||||
let thumbnail = task.and_then(|id| self.agent_images.peek(id)).cloned();
|
||||
let (body, remove) = super::stitch_ui::reference_chip_with_preview(ui, glyph, &label, &label, 0.0, width, thumbnail.as_ref());
|
||||
let enter = |response: &Response| response.clicked() || response.has_focus()
|
||||
&& ui.input(|i| i.key_pressed(egui::Key::Enter) || i.key_pressed(egui::Key::Space));
|
||||
if enter(&remove) { detach = Some(index); }
|
||||
if enter(&body) { target = activate_reference(ui, reference, None); }
|
||||
if ui.is_rect_visible(body.rect) {
|
||||
if let Some(task) = task { self.agent_images.mark_visible(task); }
|
||||
let rect = body.rect.union(remove.rect);
|
||||
rects.push(rect_value(rect));
|
||||
if index == 0 {
|
||||
self.panel_geometry["subject"] = rect_value(rect);
|
||||
self.panel_geometry["referenceRemove"] = rect_value(remove.rect);
|
||||
}
|
||||
}
|
||||
if body.hovered() || body.has_focus() {
|
||||
let thumbnail = thumbnail.or_else(|| reference_media::hover_image(app, ui.ctx(), reference));
|
||||
let mut tooltip = egui::Tooltip::for_widget(&body);
|
||||
tooltip.popup = tooltip.popup.style(super::stitch_ui::scoped_popup_style(ui));
|
||||
if let Some(texture) = &thumbnail {
|
||||
tooltip.popup = tooltip.popup
|
||||
.align(egui::RectAlign::TOP_START)
|
||||
.gap(6.0)
|
||||
.width(148.0)
|
||||
.frame(Frame::NONE);
|
||||
tooltip.show(|ui| {
|
||||
let rect = paint_reference_thumbnail(ui, texture, vec2(148.0, 144.0));
|
||||
self.panel_geometry["subjectTooltip"] = rect_value(rect);
|
||||
});
|
||||
} else {
|
||||
tooltip.popup = tooltip.popup.frame(super::stitch_ui::surface_frame(ui.ctx(), super::stitch_ui::SurfaceRole::Menu).inner_margin(egui::Margin::same(8)));
|
||||
tooltip.show(|ui| {
|
||||
ui.set_max_width(148.0);
|
||||
ui.add(egui::Label::new(RichText::new(label).size(12.0)).wrap());
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
self.panel_geometry["referenceChips"] = json!(rects);
|
||||
if let Some(index) = detach {
|
||||
if let Err(error) = self.composer_reference_remove(app, index) { self.error = error; }
|
||||
self.focus_composer = true;
|
||||
} else if let Some(target) = target
|
||||
&& let Err(error) = self.locate_composer_reference(app, target)
|
||||
{
|
||||
self.error = error;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,178 @@
|
||||
use super::super::agent_panel::storage_settings_ui;
|
||||
use super::super::{Value, Workspace};
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn receive_storage_event(&mut self, ctx: &egui::Context, method: &str, result: Result<Value, String>) {
|
||||
let apply_migration_patch = |mig: &mut storage_settings_ui::MigrationStateView, patch: &Value| {
|
||||
if let Some(phase) = patch["phase"].as_str() {
|
||||
mig.phase = storage_settings_ui::MigrationPhase::parse(phase);
|
||||
}
|
||||
if let Some(target) = patch["targetRoot"].as_str().filter(|s| !s.is_empty()) {
|
||||
mig.target_root = target.to_owned();
|
||||
}
|
||||
if patch.get("targetFreeBytes").is_some() {
|
||||
mig.target_free_bytes = patch["targetFreeBytes"].as_u64();
|
||||
}
|
||||
if let Some(req) = patch["requiredBytes"].as_u64() {
|
||||
mig.required_bytes = req;
|
||||
}
|
||||
if let Some(copied) = patch["copiedBytes"].as_u64() {
|
||||
mig.copied_bytes = copied;
|
||||
}
|
||||
if let Some(total) = patch["totalBytes"].as_u64() {
|
||||
mig.total_bytes = total;
|
||||
}
|
||||
if patch.get("validationError").is_some() {
|
||||
mig.validation_error = patch["validationError"].as_str().filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
}
|
||||
if let Some(warnings) = patch["validationWarnings"].as_array() {
|
||||
mig.validation_warnings = warnings.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect();
|
||||
}
|
||||
if let Some(blocking) = patch["blockingProjects"].as_array() {
|
||||
mig.blocking_projects = blocking.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect();
|
||||
} else if !matches!(mig.phase, storage_settings_ui::MigrationPhase::ReadyToSwitch | storage_settings_ui::MigrationPhase::Idle) {
|
||||
mig.blocking_projects.clear();
|
||||
}
|
||||
if let Some(steps) = patch.get("switchSteps").or_else(|| patch.get("steps")).and_then(Value::as_array) {
|
||||
mig.switch_steps = steps
|
||||
.iter()
|
||||
.map(|row| storage_settings_ui::SwitchStep {
|
||||
id: row["id"].as_str().unwrap_or_default().to_owned(),
|
||||
label: row["label"].as_str().unwrap_or_default().to_owned(),
|
||||
state: storage_settings_ui::SwitchStepState::parse(
|
||||
row["state"].as_str().or_else(|| row["status"].as_str()).unwrap_or("pending"),
|
||||
),
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
if patch.get("error").is_some() {
|
||||
mig.error = patch["error"].as_str().filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
}
|
||||
if patch.get("rollbackNote").is_some() {
|
||||
mig.rollback_note = patch["rollbackNote"].as_str().filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
}
|
||||
};
|
||||
|
||||
match method {
|
||||
"storage-status" => match result {
|
||||
Ok(val) if val.get("mode").is_some() => {
|
||||
let view = storage_settings_ui::StorageStatusView::from_json(&val);
|
||||
storage_settings_ui::set_status(ctx, view);
|
||||
if val["autoOpenReleaseModal"] == true {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
state.migrate_modal_open = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) => {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
state.status.status_text = Some(error);
|
||||
state.status.status_is_error = true;
|
||||
});
|
||||
}
|
||||
},
|
||||
"storage-status-refresh" => {}
|
||||
"storage-scan" => match result {
|
||||
Ok(val) => storage_settings_ui::set_scan(ctx, storage_settings_ui::StorageScanView::from_json(&val)),
|
||||
Err(error) => {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
state.scan.scanning = false;
|
||||
state.scan.error = Some(error);
|
||||
});
|
||||
}
|
||||
},
|
||||
"storage-cleanup" => match result {
|
||||
Ok(val) => {
|
||||
let mut scan = storage_settings_ui::StorageScanView::from_json(&val);
|
||||
scan.scanning = false;
|
||||
scan.cleanup_running = false;
|
||||
storage_settings_ui::set_scan(ctx, scan);
|
||||
}
|
||||
Err(error) => {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
state.scan.cleanup_running = false;
|
||||
state.scan.cleanup_result = Some(storage_settings_ui::CleanupResultView {
|
||||
freed_bytes: 0,
|
||||
message: String::new(),
|
||||
error: Some(error),
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
"storage-migrate" => match result {
|
||||
Ok(val) => {
|
||||
if val["requiresExit"] == true {
|
||||
self.storage_switch_pending = true;
|
||||
self.storage_restart_requested = true;
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
apply_migration_patch(&mut state.status.migration, &val);
|
||||
state.status.migration.phase = storage_settings_ui::MigrationPhase::Switching;
|
||||
state.migrate_modal_open = true;
|
||||
});
|
||||
} else if let Some(picked) = val["pickedRoot"].as_str() {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
state.target_input = picked.to_owned();
|
||||
if val["migration"].is_object() {
|
||||
apply_migration_patch(&mut state.status.migration, &val["migration"]);
|
||||
}
|
||||
});
|
||||
} else if val["migration"].is_object() {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
apply_migration_patch(&mut state.status.migration, &val["migration"]);
|
||||
});
|
||||
} else if val["deferred"] == true {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
state.migrate_modal_open = false;
|
||||
});
|
||||
} else if val["cancelled"] == true {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
if state.status.migration.phase.is_non_closable() {
|
||||
state.status.migration.phase = storage_settings_ui::MigrationPhase::ReadyToSwitch;
|
||||
}
|
||||
});
|
||||
} else if val["phase"].is_string() {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
apply_migration_patch(&mut state.status.migration, &val);
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
if matches!(
|
||||
state.status.migration.phase,
|
||||
storage_settings_ui::MigrationPhase::Idle | storage_settings_ui::MigrationPhase::Validating
|
||||
) {
|
||||
state.status.migration.phase = storage_settings_ui::MigrationPhase::Idle;
|
||||
state.status.migration.validation_error = Some(error);
|
||||
} else {
|
||||
state.status.migration.phase = storage_settings_ui::MigrationPhase::Failed;
|
||||
state.status.migration.error = Some(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
"storage-migrate-progress" => match result {
|
||||
Ok(val) => {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
apply_migration_patch(&mut state.status.migration, &val);
|
||||
if state.target_input.is_empty() && !state.status.migration.target_root.is_empty() {
|
||||
state.target_input = state.status.migration.target_root.clone();
|
||||
}
|
||||
if state.status.migration.phase.is_non_closable() {
|
||||
state.migrate_modal_open = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(error) => {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
state.status.migration.phase = storage_settings_ui::MigrationPhase::Failed;
|
||||
state.status.migration.error = Some(error);
|
||||
});
|
||||
}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,533 @@
|
||||
use super::super::{
|
||||
RichText, Tokens, Ui, Value, Workspace, agent_motion,
|
||||
pi_bridge,
|
||||
stitch_state::{NoticeKind, ToolStatus},
|
||||
stitch_timeline as timeline,
|
||||
};
|
||||
use super::artifact_preview_ui::activate_reference;
|
||||
use super::composer_ui::copy_reply;
|
||||
use super::models::usage_count;
|
||||
use super::production_reply_ui::{production_reply_text, production_turn};
|
||||
use super::turns::{ReplyHandoff, StreamHandoffs, Turn, TurnItem, TurnItemContent, TurnItemLayout, TurnItemLayouts, activity_history_label, duration_text};
|
||||
use crate::icons;
|
||||
use egui::{Align, Color32, FontId, Id, Layout, Rect, Sense, Vec2, vec2};
|
||||
|
||||
pub(in crate::jiansun) fn thinking_ui(ui: &mut Ui, thinking: &Value, turn_running: bool, reduced: bool) -> egui::Response {
|
||||
let status = match (thinking["active"] == true, turn_running) {
|
||||
(true, true) => timeline::ThinkingStatus::Active,
|
||||
(true, false) => timeline::ThinkingStatus::Interrupted,
|
||||
(false, _) => timeline::ThinkingStatus::Done,
|
||||
};
|
||||
timeline::thinking_row(ui, ui.next_auto_id().with("thinking"), status, None, reduced)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn turn_reply_id(conversation_id: Id, user_index: Option<usize>) -> Id {
|
||||
conversation_id.with(("turn-reply", user_index))
|
||||
}
|
||||
|
||||
/// One caption for every image and waiting card: white 12pt on a scrim at the
|
||||
/// bottom-left, one line, never wider than the card.
|
||||
pub(in crate::jiansun) fn paint_image_caption(painter: &egui::Painter, rect: Rect, text: &str) {
|
||||
if !(rect.width() >= 64.0 && rect.height() >= 34.0) { return; }
|
||||
let mut job = egui::text::LayoutJob::simple_singleline(text.to_owned(), FontId::proportional(super::agent_stream::TEXT_META), Color32::WHITE);
|
||||
job.wrap.max_width = (rect.width() - 22.0).max(1.0);
|
||||
job.wrap.max_rows = 1;
|
||||
let caption = painter.layout_job(job);
|
||||
let pos = rect.left_bottom() + vec2(10.0, -8.0 - caption.size().y);
|
||||
painter.rect_filled(Rect::from_min_size(pos, caption.size()).expand2(vec2(5.0, 3.0)), 6.0, Color32::from_black_alpha(188));
|
||||
painter.galley(pos, caption, Color32::WHITE);
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn remember_visible_stream(ui: &Ui, id: Id, text: &str) {
|
||||
let mut end = text.len().min(65_000);
|
||||
while end > 0 && !text.is_char_boundary(end) { end -= 1; }
|
||||
let text = text.get(..end).unwrap_or_default();
|
||||
ui.data_mut(|data| {
|
||||
let cache = data.get_temp_mut_or_default::<StreamHandoffs>(Id::unique("jiansun-stream-handoffs"));
|
||||
if let Some((_, previous)) = cache.0.iter_mut().find(|(candidate, _)| *candidate == id) {
|
||||
if previous != text { text.clone_into(previous); }
|
||||
} else {
|
||||
// One public stream is at most the bridge's 65KB limit. Keep only
|
||||
// recent scoped turns, never an unbounded copy of the transcript.
|
||||
if cache.0.len() >= 16 { cache.0.remove(0); }
|
||||
cache.0.push((id, text.to_owned()));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn final_handoff(ui: &Ui, id: Id, text: &str) -> Option<ReplyHandoff> {
|
||||
if text.is_empty() { return None; }
|
||||
ui.data_mut(|data| {
|
||||
let cache = data.get_temp_mut_or_default::<StreamHandoffs>(Id::unique("jiansun-stream-handoffs"));
|
||||
cache.0.iter().find(|(candidate, _)| *candidate == id).and_then(|(_, stream)| {
|
||||
if stream.starts_with(text) || stream.ends_with(text) { Some(ReplyHandoff::Displayed) }
|
||||
else if !stream.is_empty() && text.starts_with(stream.as_str()) { Some(ReplyHandoff::Append) }
|
||||
else { None }
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// A UI mount time, a previous turn or a future/invalid clock is not evidence.
|
||||
pub(in crate::jiansun) fn active_tool_elapsed(messages: &[Value], run: Option<&str>, now_ms: u64) -> Option<u64> {
|
||||
let run = run.filter(|run| !run.is_empty())?;
|
||||
messages.iter().rev().find_map(|message| {
|
||||
let event = &message["event"];
|
||||
if event["version"] != 1 || event["type"] != "tool" || event["run"] != run || event["status"] != "started" {
|
||||
return None;
|
||||
}
|
||||
let started = event["timestampMs"].as_u64()?;
|
||||
now_ms.checked_sub(started)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
/// The bubble itself lives in the kit (`stitch_ui::user_bubble_with_reveal`), together with
|
||||
/// the per-character reveal and its glow. `reduced` is always passed through: reduced motion
|
||||
/// shows the whole message at once and never starts the reveal or its repaint loop.
|
||||
pub(in crate::jiansun) fn user_bubble_with_reveal(ui: &mut Ui, text: &str, started: Option<f64>, reduced: bool) -> Rect {
|
||||
timeline::user_message(ui, text, started, reduced)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn paint_reference_thumbnail(ui: &mut Ui, texture: &egui::TextureHandle, limit: Vec2) -> Rect {
|
||||
let source = texture.size_vec2();
|
||||
let size = source * (limit.x / source.x).min(limit.y / source.y);
|
||||
ui.add(egui::Image::new(texture).fit_to_exact_size(size).corner_radius(6.0)).rect
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn frame_image_ratio(frame: &Value) -> Option<f32> {
|
||||
let width = frame["width"].as_f64()?;
|
||||
let height = frame["height"].as_f64()?;
|
||||
(width > 0.0 && height > 0.0).then_some((width / height) as f32).filter(|ratio| ratio.is_finite() && *ratio > 0.0)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn image_card_size(width: f32, ratio: f32) -> egui::Vec2 {
|
||||
let width = width.min(340.0 * ratio);
|
||||
vec2(width, width / ratio)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn icon(ui: &mut Ui, name: &str, tint: Color32) {
|
||||
ui.add(icons::image(name, 14.0, tint));
|
||||
}
|
||||
|
||||
/// Candidate numbers are the actual canvas order, never the message order.
|
||||
/// If either identity is absent or ambiguous, show no invented ordinal.
|
||||
pub(in crate::jiansun) fn candidate_ordinal(subject: &Value, workflow: &Value) -> Option<usize> {
|
||||
let slot_id = subject["slotId"].as_str().filter(|id| !id.is_empty())?;
|
||||
let candidate_id = subject["candidateId"].as_str().filter(|id| !id.is_empty())?;
|
||||
let mut slots = workflow["slots"].as_array()?.iter().filter(|slot| slot["id"].as_str() == Some(slot_id));
|
||||
let slot = slots.next()?;
|
||||
if slots.next().is_some() { return None; }
|
||||
let mut matches = slot["candidates"].as_array()?.iter().enumerate()
|
||||
.filter(|(_, candidate)| candidate["id"].as_str() == Some(candidate_id));
|
||||
let (index, _) = matches.next()?;
|
||||
if matches.next().is_some() { return None; }
|
||||
Some(index + 1)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn subject_label(subject: &Value, workflow: &Value) -> String {
|
||||
if subject["kind"] == "selection" {
|
||||
let count = subject["selectedLayerIds"].as_array().map_or_else(|| subject["targets"].as_array().map_or(0, Vec::len), Vec::len);
|
||||
return format!("已选 {count} 个对象");
|
||||
}
|
||||
let mut parts = Vec::<String>::new();
|
||||
for field in ["pageId", "label", "variantLabel"] {
|
||||
if let Some(text) = subject[field].as_str().filter(|text| !text.trim().is_empty()) {
|
||||
let text = text.chars().take(160).collect::<String>();
|
||||
if !parts.iter().any(|part| part == &text || part.starts_with(&format!("{text} ·"))) {
|
||||
parts.push(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
if subject["kind"] == "candidate" {
|
||||
let ordinal = candidate_ordinal(subject, workflow);
|
||||
parts.push(
|
||||
subject["candidateLabel"]
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| ordinal.map_or_else(|| "候选".into(), |index| format!("候选 {index}"))),
|
||||
);
|
||||
}
|
||||
if parts.is_empty() { "当前项目".into() } else { parts.join(" · ") }
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn image_result_labels(target: &Value, workflow: &Value, brief: &Value) -> (String, String, String) {
|
||||
let short = candidate_ordinal(target, workflow).map_or_else(|| "候选图片".to_owned(), |ordinal| format!("候选 {ordinal}"));
|
||||
let slot = workflow["slots"].as_array().into_iter().flatten()
|
||||
.find(|slot| target["slotId"].as_str().is_some_and(|id| !id.is_empty() && slot["id"].as_str() == Some(id)));
|
||||
let page = slot.and_then(|slot| slot["documentId"].as_str()).unwrap_or("");
|
||||
let slot_label = slot.and_then(|slot| slot["label"].as_str()).unwrap_or("");
|
||||
let variant = brief["variants"].as_array().into_iter().flatten()
|
||||
.find(|variant| target["productVariantId"].as_str().is_some_and(|id| !id.is_empty() && variant["id"].as_str() == Some(id)))
|
||||
.and_then(|variant| variant["name"].as_str()).unwrap_or("");
|
||||
let title = subject_label(target, workflow);
|
||||
let full = [page, slot_label, variant, title.as_str()].into_iter().filter(|part| !part.is_empty()).collect::<Vec<_>>().join(" · ");
|
||||
(page.to_owned(), short, full)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn notice_kind(text: &str) -> NoticeKind {
|
||||
if text.contains("失败") { NoticeKind::Failed }
|
||||
else if text.contains("核查") || text.contains("无法确认") || text.contains("未执行") { NoticeKind::NeedsCheck }
|
||||
else if text.starts_with("正在") { NoticeKind::Waiting }
|
||||
else if text.starts_with("图片已生成") { NoticeKind::Produced }
|
||||
else if ["已完成", "已替换", "已置入", "已采用", "已回填", "已导出"]
|
||||
.iter().any(|prefix| text.starts_with(prefix)) { NoticeKind::Saved }
|
||||
else { NoticeKind::Info }
|
||||
}
|
||||
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn user_reveal_id(&self,index:Option<usize>)->Id {
|
||||
Id::unique(("user-text-arrival",&self.origin,self.account["id"].as_str(),self.project_context["localId"].as_str(),self.observed_doc,index))
|
||||
}
|
||||
pub(in crate::jiansun) fn reveal_sent_user_text(&self,ui:&Ui,after:usize) {
|
||||
if self.reduce_motion {return;}
|
||||
let now=ui.input(|input|input.time);
|
||||
for (index,_) in self.messages.iter().enumerate().skip(after).filter(|(_,message)|message["role"]=="user") {
|
||||
ui.data_mut(|data|data.insert_temp(self.user_reveal_id(Some(index)),now));
|
||||
}
|
||||
}
|
||||
pub(in crate::jiansun) fn sent_references(&self, ui: &mut Ui, message: &Value) -> Option<Value> {
|
||||
let references = message["requestScope"]["references"].as_array().filter(|items| !items.is_empty())?;
|
||||
let mut locate = None;
|
||||
let available = ui.available_width().max(1.0);
|
||||
let width = available.min(120.0);
|
||||
let spacing = ui.spacing().item_spacing.x;
|
||||
let columns = (((available + spacing) / (width + spacing)).floor() as usize).max(1);
|
||||
let caption_color = Tokens::get(ui.ctx()).agent().text_dim;
|
||||
for (row, items) in references.chunks(columns).enumerate() {
|
||||
ui.allocate_ui_with_layout(vec2(available, 1.0), Layout::right_to_left(Align::Min), |ui| {
|
||||
for (column, reference) in items.iter().enumerate().rev() {
|
||||
let index = row * columns + column;
|
||||
let detail = &message["referenceContent"][index];
|
||||
ui.allocate_ui_with_layout(vec2(width, 1.0), Layout::top_down(Align::Max), |ui| {
|
||||
ui.set_width(width);
|
||||
let label = reference["label"].as_str().filter(|label| !label.is_empty())
|
||||
.map(str::to_owned).unwrap_or_else(|| subject_label(reference, &self.template_workflow));
|
||||
let image_size = vec2(width, 110.0);
|
||||
let image_area = Rect::from_min_size(ui.max_rect().min, image_size);
|
||||
if let Some(id) = detail["imageId"].as_str().or_else(|| reference["taskId"].as_str()) {
|
||||
if ui.is_rect_visible(image_area) {
|
||||
self.agent_images.mark_visible(id);
|
||||
}
|
||||
// Keep the transcript height independent of the scroll clip.
|
||||
if let Some(image) = self.agent_images.peek(id) {
|
||||
let rect = paint_reference_thumbnail(ui, image, image_size);
|
||||
let preview = ui.interact(rect, ui.scope_id().with(("sent-reference-image", index)), Sense::click())
|
||||
.on_hover_text(label.as_str());
|
||||
if preview.clicked() { locate = activate_reference(ui, reference, Some(id)); }
|
||||
}
|
||||
}
|
||||
let caption = ui.add(egui::Label::new(RichText::new(label).size(12.0).color(caption_color))
|
||||
.truncate().sense(Sense::click()));
|
||||
if caption.clicked() { locate = activate_reference(ui, reference, detail["imageId"].as_str()); }
|
||||
if let Some(text) = detail["text"].as_str().filter(|text| !text.is_empty()) {
|
||||
ui.add(egui::Label::new(RichText::new(text.chars().take(96).collect::<String>()).size(12.0)).wrap());
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
locate
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn turn_ui(&self, ui: &mut Ui, turn: Turn<'_>, conversation_id: Id, count: usize, current_turn: bool, tracing: bool, doc: Option<&super::Document>) -> Option<Value> {
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let batch_progress = self.batch_progress_visible();
|
||||
let product = production_turn(turn.user)
|
||||
|| (current_turn && self.pi_product_production);
|
||||
let live_reply = if self.pi_product_production {
|
||||
self.stream_reply.as_str()
|
||||
} else if batch_progress && self.workflow.production_progress().is_object() {
|
||||
""
|
||||
} else if batch_progress {
|
||||
self.stream_reply.splitn(3, '\n').nth(2).unwrap_or("")
|
||||
} else {
|
||||
self.stream_reply.as_str()
|
||||
};
|
||||
let stream = current_turn.then_some(live_reply).filter(|text| !text.is_empty());
|
||||
let turn_running = current_turn && self.pending() && !self.agent_effects_paused
|
||||
&& (self.pi_run.is_some() || matches!(self.busy.as_deref(), Some("agent" | "pi-agent")));
|
||||
let projected = if current_turn && batch_progress { self.projected_worker_jobs() } else { Vec::new() };
|
||||
let merged_images = matches!(turn.items.last(), Some(TurnItem::Images(..)));
|
||||
let last_position = turn.items.len().saturating_sub(1);
|
||||
let mut locate = None;
|
||||
let mut flow = super::agent_stream::Flow::default();
|
||||
if let Some(text) = turn.user {
|
||||
let enter = agent_motion::message_enter(ui, conversation_id, turn.user_index.unwrap_or(usize::MAX), count, self.reduce_motion);
|
||||
let reveal_id = self.user_reveal_id(turn.user_index);
|
||||
let now = ui.input(|input| input.time);
|
||||
let started = if self.reduce_motion {ui.data_mut(|data|data.remove::<f64>(reveal_id));None} else {
|
||||
ui.data_mut(|data| {
|
||||
if enter < 1.0 { data.get_temp_mut_or_insert_with(reveal_id, || now); }
|
||||
data.get_temp::<f64>(reveal_id)
|
||||
})
|
||||
};
|
||||
let response = agent_motion::message_visual(ui, enter, |ui| {
|
||||
if let Some(index) = turn.user_index {
|
||||
if let Some(reference) = self.sent_references(ui, &self.messages[index]) {
|
||||
locate = Some(reference);
|
||||
}
|
||||
}
|
||||
user_bubble_with_reveal(ui, text, started, self.reduce_motion);
|
||||
if turn.user_index.is_some_and(|index| self.messages[index]["kind"] == "steer" && self.messages[index]["delivered"] == true) {
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
ui.label(RichText::new("已插话").size(11.0).color(t.text_dim));
|
||||
});
|
||||
}
|
||||
});
|
||||
agent_motion::message_repaint(ui, response.response.rect, enter);
|
||||
ui.add_space(18.0);
|
||||
}
|
||||
if !turn.items.is_empty() || stream.is_some() {
|
||||
if let Some(target) = turn.target.filter(|target| target["kind"] != "project") {
|
||||
let label = subject_label(target, &self.template_workflow);
|
||||
let row = timeline::target_row(ui, conversation_id.with(("turn-target", turn.user_index)), &label, self.reduce_motion);
|
||||
if row.clicked() { locate = Some(target.clone()); }
|
||||
}
|
||||
let reply_id = turn_reply_id(conversation_id, turn.user_index);
|
||||
let latest_reply = turn.items.iter().rev().find_map(|item| match item {
|
||||
TurnItem::Reply(_, index) => Some(*index),
|
||||
_ => None,
|
||||
});
|
||||
let tail_reply = match turn.items.last() {
|
||||
Some(TurnItem::Reply(text, index)) => Some((*text, *index)),
|
||||
_ => None,
|
||||
};
|
||||
let stream_is_persisted = stream.is_some_and(|stream| tail_reply.is_some_and(|(text, _)|
|
||||
text == stream || text.starts_with(stream) || (!turn_running && final_handoff(ui, reply_id, text).is_some())));
|
||||
let stream_extends_receipt = !stream_is_persisted && stream.is_some_and(|stream|
|
||||
tail_reply.is_some_and(|(text, _)| !text.is_empty() && stream.starts_with(text)));
|
||||
let paint_stream = |ui: &mut Ui, text: &str| {
|
||||
remember_visible_stream(ui, reply_id, text);
|
||||
ui.push_id(reply_id, |ui| {
|
||||
let display = product.then(|| production_reply_text(text, turn_running, &self.template_workflow));
|
||||
timeline::reply(ui, reply_id, timeline::Reply { text: display.as_deref().unwrap_or(text), streaming: turn_running, animate_final: false }, self.reduce_motion);
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
};
|
||||
let layouts_id = reply_id.with("turn-item-layouts");
|
||||
let virtualized = current_turn && turn.items.len() >= 32;
|
||||
#[cfg(test)]
|
||||
let virtualized = virtualized && !ui.data(|data|
|
||||
data.get_temp::<bool>(Id::unique("benchmark-full-transcript")).unwrap_or(false));
|
||||
let mut layouts = TurnItemLayouts::default();
|
||||
let now = ui.input(|input| input.time);
|
||||
if virtualized {
|
||||
layouts = ui.data_mut(|data| data.remove_temp(layouts_id)).unwrap_or_default();
|
||||
#[cfg(test)]
|
||||
{
|
||||
let reset_on_append = ui.data(|data|
|
||||
data.get_temp::<bool>(Id::unique("benchmark-reset-on-append")).unwrap_or(false));
|
||||
if reset_on_append && layouts.benchmark_count != count {
|
||||
layouts.items.clear();
|
||||
}
|
||||
layouts.benchmark_count = count;
|
||||
}
|
||||
let key = Some((ui.available_width().to_bits(), ui.pixels_per_point().to_bits(),
|
||||
Tokens::get(ui.ctx()).kind, self.reduce_motion, turn_running));
|
||||
if layouts.key.is_some_and(|(_, _, _, _, running)| running) && !turn_running {
|
||||
layouts.disclose_until = now + super::stitch_ui::TOOL_DISCLOSURE_SETTLE_SECONDS;
|
||||
}
|
||||
if layouts.key != key {
|
||||
layouts.key = key;
|
||||
layouts.items.clear();
|
||||
}
|
||||
layouts.items.resize(count, None);
|
||||
}
|
||||
let viewport = ui.clip_rect().expand2(vec2(0.0, 240.0));
|
||||
let focused_rect = virtualized.then(|| {
|
||||
ui.memory(|memory| memory.focused()).and_then(|id| ui.ctx().read_response(id)).map(|r| r.rect)
|
||||
}).flatten();
|
||||
|
||||
for (position, item) in turn.items.into_iter().enumerate() {
|
||||
let use_layout = virtualized && position != last_position;
|
||||
let item_index = item.message_index();
|
||||
let mut cached = if use_layout { layouts.items[item_index].take() } else { None };
|
||||
let origin = ui.next_widget_position().to_vec2();
|
||||
let mut texture_sizes = Vec::new();
|
||||
if use_layout {
|
||||
let live = match &item {
|
||||
TurnItem::Thinking(value, _) => turn_running && value["active"] == true,
|
||||
TurnItem::Tools(rows) => now < layouts.disclose_until || turn_running && rows.iter().any(|(event, _)|
|
||||
ToolStatus::parse(event["status"].as_str().unwrap_or("")).running()),
|
||||
TurnItem::Images(_, images) => {
|
||||
let mut live = false;
|
||||
for image in images {
|
||||
let id = image["taskId"].as_str().or_else(|| image["id"].as_str()).unwrap_or("");
|
||||
texture_sizes.push(self.agent_images.peek(id).map(egui::TextureHandle::size));
|
||||
live |= turn_running && image["kind"] == "image-job" && image["finished"].is_null()
|
||||
&& self.pi_run.as_deref().is_some_and(|run| image["run"] == run);
|
||||
live |= self.canvas_workspace.preview_arrival(id).is_some_and(|started|
|
||||
agent_motion::image_enter(now - started, 1.0, self.reduce_motion).0 < 1.0);
|
||||
}
|
||||
live
|
||||
}
|
||||
TurnItem::Reply(_, index) => latest_reply == Some(*index) && stream.is_some()
|
||||
|| agent_motion::message_enter(ui, conversation_id, *index, count, self.reduce_motion) < 1.0,
|
||||
_ => false,
|
||||
};
|
||||
cached = cached.filter(|layout|
|
||||
layout.texture_sizes == texture_sizes && layout.content.matches(&item, &self.messages));
|
||||
if !live && !tracing
|
||||
&& let Some(layout) = &cached
|
||||
&& layout.settled_at <= now
|
||||
{
|
||||
let bounds = layout.bounds.translate(origin);
|
||||
if !bounds.intersects(viewport) && !ui.rect_contains_pointer(bounds)
|
||||
&& focused_rect.is_none_or(|focus| !bounds.intersects(focus))
|
||||
{
|
||||
ui.expand_to_include_rect(bounds);
|
||||
ui.add_space(layout.advance);
|
||||
ui.skip_ahead_auto_ids(1);
|
||||
flow.restore_anchor(layout.rail.map(|rail| rail.translate(origin)));
|
||||
layouts.items[item_index] = cached;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Each cached item owns stable widget IDs even when earlier
|
||||
// items are replaced by their layout.
|
||||
let content = use_layout.then(|| {
|
||||
let previous = cached.take();
|
||||
let settled = previous.as_ref().map(|layout| (layout.advance, layout.settled_at));
|
||||
let content = previous.map_or_else(|| TurnItemContent::capture(&item, &self.messages), |layout| layout.content);
|
||||
(content, settled)
|
||||
});
|
||||
let mut item_ui = use_layout.then(|| ui.new_child(egui::UiBuilder::new().id_salt(("turn-item", item_index))));
|
||||
{
|
||||
let ui = item_ui.as_mut().unwrap_or(&mut *ui);
|
||||
match item {
|
||||
TurnItem::Thinking(thinking, _) => {
|
||||
let row = thinking_ui(ui, thinking, turn_running, self.reduce_motion);
|
||||
flow.connect(ui, row.rect);
|
||||
}
|
||||
TurnItem::Notice(text, _) => {
|
||||
let text = activity_history_label(text);
|
||||
let display = crate::client_brand::user_error(
|
||||
&production_reply_text(text, false, &self.template_workflow), "本轮操作有一条更新");
|
||||
let row = timeline::notice_row(ui, ui.next_auto_id().with("notice"), timeline::Notice {
|
||||
kind: notice_kind(text), text: &display, hint: None,
|
||||
}, self.reduce_motion);
|
||||
flow.connect(ui, row.rect);
|
||||
}
|
||||
TurnItem::Tools(tasks) => {
|
||||
let Some((_, first)) = tasks.first() else { continue };
|
||||
let id = conversation_id.with(("public-reasoning", first));
|
||||
let elapsed: Vec<_> = tasks.iter().map(|(event, _)| {
|
||||
let status = ToolStatus::parse(event["status"].as_str().unwrap_or(""));
|
||||
status.timed().then(|| usage_count(&event["durationMs"]).map(duration_text)).flatten()
|
||||
}).collect();
|
||||
let rows: Vec<_> = tasks.iter().zip(&elapsed).map(|((event, _), elapsed)| {
|
||||
let tool = event["toolName"].as_str().unwrap_or("");
|
||||
let status = ToolStatus::parse(event["status"].as_str().unwrap_or(""));
|
||||
timeline::ToolRow { tool, name: super::stitch_state::tool_label(tool),
|
||||
status: if status == ToolStatus::Started && !turn_running { ToolStatus::Unknown } else { status },
|
||||
elapsed: elapsed.as_deref(), summary:event["summary"].as_str(),
|
||||
failure_category:event["failureCategory"].as_str(),
|
||||
failure_detail:event["failureDetail"]["message"].as_str(),
|
||||
copy_updates: pi_bridge::copy_updates(event) }
|
||||
}).collect();
|
||||
let row = timeline::tool_group(ui, id, timeline::ToolGroupHead {
|
||||
total: rows.len(),
|
||||
completed: rows.iter().filter(|row| row.status == ToolStatus::Completed).count(),
|
||||
failed: rows.iter().filter(|row| row.status == ToolStatus::Failed).count(),
|
||||
active: turn_running && rows.iter().any(|row| row.status.running()),
|
||||
turn_running,
|
||||
}, &rows, self.reduce_motion);
|
||||
flow.connect(ui, row.rect);
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
TurnItem::Reply(text, index) => {
|
||||
flow.break_run();
|
||||
let is_last_reply = tail_reply.is_some_and(|(_, last)| index == last);
|
||||
if is_last_reply && stream_extends_receipt && let Some(text) = stream {
|
||||
paint_stream(ui, text);
|
||||
continue;
|
||||
}
|
||||
let handoff = (current_turn && latest_reply == Some(index))
|
||||
.then(|| final_handoff(ui, reply_id, text)).flatten();
|
||||
let arrival = agent_motion::message_enter(ui, conversation_id, index, count, self.reduce_motion);
|
||||
let anchor = reply_id.with(index);
|
||||
let clean = production_reply_text(text, false, &self.template_workflow);
|
||||
let text = clean.as_str();
|
||||
let copy_id = anchor.with("copy");
|
||||
// The copy action keeps its row but shows only while the
|
||||
// reply is pointed at or the button itself holds focus.
|
||||
let previous = ui.data(|data| data.get_temp::<bool>(copy_id.with("shown")));
|
||||
let (reply_rect, copy_focused) = ui.data(|data| (
|
||||
data.get_temp::<Rect>(copy_id.with("reply-rect")),
|
||||
data.get_temp::<bool>(copy_id.with("focus")).unwrap_or(false),
|
||||
));
|
||||
let shown = copy_focused || reply_rect.is_some_and(|rect| ui.rect_contains_pointer(rect));
|
||||
if previous != Some(shown) {
|
||||
ui.ctx().request_repaint();
|
||||
ui.data_mut(|data| data.insert_temp(copy_id.with("shown"), shown));
|
||||
}
|
||||
let response = ui.push_id(anchor, |ui| {
|
||||
if let Some(handoff) = handoff
|
||||
&& super::stitch_ui::move_response_arrival(ui, reply_id, anchor)
|
||||
&& handoff == ReplyHandoff::Displayed
|
||||
{
|
||||
super::stitch_ui::prepare_final_handoff(ui, anchor, text);
|
||||
}
|
||||
timeline::reply(ui, anchor, timeline::Reply { text, streaming: false, animate_final: arrival < 1.0 }, self.reduce_motion);
|
||||
ui.allocate_ui_with_layout(vec2(ui.available_width(), 24.0), Layout::right_to_left(Align::Center), |ui| {
|
||||
ui.set_opacity(if shown { 1.0 } else { 0.0 });
|
||||
let focused = copy_reply(ui, text).has_focus();
|
||||
ui.data_mut(|data| data.insert_temp(copy_id.with("focus"), focused));
|
||||
});
|
||||
});
|
||||
ui.data_mut(|data| data.insert_temp(copy_id.with("reply-rect"), response.response.rect));
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
TurnItem::Images(first, images) => {
|
||||
let images = images.into_iter().chain(projected.iter().filter(|_| position == last_position)).collect::<Vec<_>>();
|
||||
if let Some(target) = self.timeline_images(ui, conversation_id.with(("image-results", first)), &images, &mut flow, doc) {
|
||||
locate = Some(target);
|
||||
}
|
||||
}
|
||||
TurnItem::Choice(index) => {
|
||||
flow.break_run();
|
||||
let action = match self.messages.get(index).and_then(|message| message["kind"].as_str()) {
|
||||
Some("pi-ui-request") => self.pi_ui_render(ui, index),
|
||||
kind => timeline::interaction_card(ui, timeline::InteractionCard { title: None, note: None }, |ui| {
|
||||
if kind == Some("copywriting-fields") { self.copy_fields_ui(ui, index) }
|
||||
else { self.copy_options_ui(ui, index) }
|
||||
}).inner,
|
||||
};
|
||||
if let Some(action) = action { locate = Some(action); }
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let (Some(child), Some((content, previous))) = (item_ui, content) {
|
||||
let bounds = child.min_rect().translate(-origin);
|
||||
let advance = child.next_widget_position().y - origin.y;
|
||||
let rail = flow.anchor().map(|anchor| anchor.translate(-origin));
|
||||
let settled_at = previous.filter(|(height, _)| *height == advance)
|
||||
.map_or(now + 0.25, |(_, settled_at)| settled_at);
|
||||
ui.expand_to_include_rect(child.min_rect());
|
||||
ui.add_space(advance);
|
||||
layouts.items[item_index] = Some(TurnItemLayout { content, bounds, advance, rail, settled_at, texture_sizes });
|
||||
}
|
||||
}
|
||||
if virtualized {
|
||||
ui.data_mut(|data| data.insert_temp(layouts_id, layouts));
|
||||
}
|
||||
if let Some(text) = stream.filter(|_| !stream_is_persisted && !stream_extends_receipt) {
|
||||
flow.break_run();
|
||||
paint_stream(ui, text);
|
||||
}
|
||||
if stream.is_some() && self.unknown && !batch_progress {
|
||||
ui.label(RichText::new("输出未完成").small().color(t.warning));
|
||||
}
|
||||
}
|
||||
if !projected.is_empty() && !merged_images {
|
||||
let images: Vec<_> = projected.iter().collect();
|
||||
self.timeline_images(ui, conversation_id.with(("worker-jobs", turn.user_index)), &images, &mut flow, doc);
|
||||
}
|
||||
locate
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,248 @@
|
||||
use egui::{Id, Rect};
|
||||
use super::super::{Value, Workspace, stitch_state::WorkerStage};
|
||||
|
||||
pub(in crate::jiansun) struct ProductionWorker<'a> {
|
||||
pub(in crate::jiansun) row: &'a Value,
|
||||
pub(in crate::jiansun) number: u64,
|
||||
pub(in crate::jiansun) active: bool,
|
||||
pub(in crate::jiansun) stage: WorkerStage,
|
||||
pub(in crate::jiansun) step: String,
|
||||
pub(in crate::jiansun) review: bool,
|
||||
pub(in crate::jiansun) slot: String,
|
||||
pub(in crate::jiansun) frame: Value,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(in crate::jiansun) struct Turn<'a> {
|
||||
pub(in crate::jiansun) user: Option<&'a str>,
|
||||
pub(in crate::jiansun) user_index: Option<usize>,
|
||||
pub(in crate::jiansun) target: Option<&'a Value>,
|
||||
pub(in crate::jiansun) items: Vec<TurnItem<'a>>,
|
||||
pub(in crate::jiansun) last_reply: Option<(&'a str, usize)>,
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) enum TurnItem<'a> {
|
||||
Reply(&'a str, usize),
|
||||
Notice(&'a str, usize),
|
||||
Thinking(&'a Value, usize),
|
||||
Tools(Vec<(&'a Value, usize)>),
|
||||
Images(usize, Vec<&'a Value>),
|
||||
Choice(usize),
|
||||
}
|
||||
|
||||
impl TurnItem<'_> {
|
||||
pub(in crate::jiansun) fn message_index(&self) -> usize {
|
||||
match self {
|
||||
Self::Reply(_, index) | Self::Notice(_, index) | Self::Thinking(_, index)
|
||||
| Self::Images(index, _) | Self::Choice(index) => *index,
|
||||
Self::Tools(rows) => rows[0].1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(in crate::jiansun) enum TurnItemContent {
|
||||
Reply(String),
|
||||
Notice(String),
|
||||
Thinking(bool),
|
||||
Tools(Vec<Value>),
|
||||
Images(Vec<Value>),
|
||||
Choice(Value),
|
||||
}
|
||||
|
||||
impl TurnItemContent {
|
||||
pub(in crate::jiansun) fn capture(item: &TurnItem<'_>, messages: &[Value]) -> Self {
|
||||
match item {
|
||||
TurnItem::Reply(text, _) => Self::Reply((*text).to_owned()),
|
||||
TurnItem::Notice(text, _) => Self::Notice((*text).to_owned()),
|
||||
TurnItem::Thinking(value, _) => Self::Thinking(value["active"] == true),
|
||||
TurnItem::Tools(rows) => Self::Tools(rows.iter().map(|(value, _)| (*value).clone()).collect()),
|
||||
TurnItem::Images(_, images) => Self::Images(images.iter().map(|value| (*value).clone()).collect()),
|
||||
TurnItem::Choice(index) => Self::Choice(messages[*index].clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn matches(&self, item: &TurnItem<'_>, messages: &[Value]) -> bool {
|
||||
match (self, item) {
|
||||
(Self::Reply(previous), TurnItem::Reply(text, _))
|
||||
| (Self::Notice(previous), TurnItem::Notice(text, _)) => previous.as_str() == *text,
|
||||
(Self::Thinking(previous), TurnItem::Thinking(value, _)) => *previous == (value["active"] == true),
|
||||
(Self::Tools(previous), TurnItem::Tools(rows)) =>
|
||||
previous.iter().eq(rows.iter().map(|(value, _)| *value)),
|
||||
(Self::Images(previous), TurnItem::Images(_, images)) =>
|
||||
previous.iter().eq(images.iter().copied()),
|
||||
(Self::Choice(previous), TurnItem::Choice(index)) => previous == &messages[*index],
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Turn<'a> {
|
||||
pub(in crate::jiansun) fn images(&self) -> impl Iterator<Item = &'a Value> + '_ {
|
||||
self.items.iter().flat_map(|item| match item {
|
||||
TurnItem::Images(_, images) => images.as_slice(),
|
||||
_ => &[],
|
||||
}).copied()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(in crate::jiansun) struct StreamHandoffs(pub(in crate::jiansun) Vec<(Id, String)>);
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(in crate::jiansun) enum ReplyHandoff { Displayed, Append }
|
||||
|
||||
|
||||
|
||||
/// A settled turn owns no request, pause or unresolved result. Follow-ups and
|
||||
/// composer suggestions both wait for it.
|
||||
#[derive(Clone, Default)]
|
||||
pub(in crate::jiansun) struct ConversationRows {
|
||||
pub(in crate::jiansun) layout: Option<(Id, usize, u32, u32, crate::theme::ThemeKind)>,
|
||||
pub(in crate::jiansun) rects: Vec<Option<Rect>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(in crate::jiansun) struct TurnItemLayout {
|
||||
pub(in crate::jiansun) content: TurnItemContent,
|
||||
pub(in crate::jiansun) bounds: Rect,
|
||||
pub(in crate::jiansun) advance: f32,
|
||||
pub(in crate::jiansun) rail: Option<Rect>,
|
||||
pub(in crate::jiansun) settled_at: f64,
|
||||
pub(in crate::jiansun) texture_sizes: Vec<Option<[usize; 2]>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(in crate::jiansun) struct TurnItemLayouts {
|
||||
pub(in crate::jiansun) key: Option<(u32, u32, crate::theme::ThemeKind, bool, bool)>,
|
||||
#[cfg(test)]
|
||||
pub(in crate::jiansun) benchmark_count: usize,
|
||||
pub(in crate::jiansun) disclose_until: f64,
|
||||
pub(in crate::jiansun) items: Vec<Option<TurnItemLayout>>,
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn conversation_settled(workspace: &Workspace, production: bool) -> bool {
|
||||
!production && workspace.turn_idle() && !workspace.unknown && !workspace.pi_review
|
||||
&& !workspace.agent_effects_paused && workspace.error.is_empty() && workspace.stream_reply.is_empty()
|
||||
}
|
||||
|
||||
|
||||
/// A tool's public label is constructed locally, never from its arguments,
|
||||
/// output, arbitrary summary or error string. Unknown values stay unknown.
|
||||
/// The name and status tables live in the kit (`stitch_state`), so a tool reads
|
||||
/// the same here as in its row badge; this only assembles the legacy line.
|
||||
pub(in crate::jiansun) fn is_tool_event(event: &Value) -> bool {
|
||||
event["version"] == 1 && event["type"] == "tool"
|
||||
}
|
||||
|
||||
/// People read durations coarsely: milliseconds under a second, tenths below
|
||||
/// ten, whole seconds below a minute, then minutes.
|
||||
pub(in crate::jiansun) fn duration_text(ms: u64) -> String {
|
||||
super::stitch_state::duration_text(ms)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn activity(message: &Value) -> bool {
|
||||
if message["kind"] == "reply" {
|
||||
return false;
|
||||
}
|
||||
if message["kind"] == "activity" {
|
||||
return true;
|
||||
}
|
||||
let text = message["text"].as_str().unwrap_or("");
|
||||
["已完成:", "图片已生成", "图片已保留", "已替换当前屏", "已置入生成", "已接手", "画布已修改", "98k图片结果"].iter().any(|prefix| text.starts_with(prefix))
|
||||
}
|
||||
|
||||
/// Historical activity is not a live undo capability. Keep the original
|
||||
/// journal intact while avoiding a stale promise after native undo or redo.
|
||||
pub(in crate::jiansun) fn activity_history_label(text: &str) -> &str {
|
||||
if text == "已采纳图片,可撤销" { "图片采纳记录" } else if text.starts_with("专业编辑已回填") { "专业编辑回填记录 · 编辑源文件保留" } else { text }
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn turns(messages: &[Value]) -> Vec<Turn<'_>> {
|
||||
let mut out = Vec::new();
|
||||
let mut current = Turn::default();
|
||||
let mut call_rows = std::collections::HashMap::<(&str, &str), (usize, usize)>::new();
|
||||
for (index, message) in messages.iter().enumerate() {
|
||||
if message["role"] == "user" {
|
||||
if current.user.is_some() || !current.items.is_empty() {
|
||||
out.push(std::mem::take(&mut current));
|
||||
call_rows.clear();
|
||||
}
|
||||
current.user = message["text"].as_str();
|
||||
current.user_index = Some(index);
|
||||
} else if matches!(message["kind"].as_str(), Some("copywriting-options" | "copywriting-fields" | "pi-ui-request")) {
|
||||
current.items.push(TurnItem::Choice(index));
|
||||
} else if message["kind"] == "pi-ui-decoration" {
|
||||
continue;
|
||||
} else if matches!(message["kind"].as_str(), Some("image" | "template-image" | "image-job")) {
|
||||
if let Some(TurnItem::Images(_, images)) = current.items.last_mut() {
|
||||
images.push(message);
|
||||
} else {
|
||||
current.items.push(TurnItem::Images(index, vec![message]));
|
||||
}
|
||||
} else if message["kind"] == "thinking" {
|
||||
if let Some(TurnItem::Thinking(previous, previous_index)) = current.items.last_mut() {
|
||||
*previous = message;
|
||||
*previous_index = index;
|
||||
} else {
|
||||
current.items.push(TurnItem::Thinking(message, index));
|
||||
}
|
||||
} else if activity(message) && is_tool_event(&message["event"]) {
|
||||
let event = &message["event"];
|
||||
let identity = event["run"].as_str().zip(event["toolCallId"].as_str());
|
||||
if let Some(&(group, row)) = identity.and_then(|key| call_rows.get(&key))
|
||||
&& let Some(TurnItem::Tools(tools)) = current.items.get_mut(group)
|
||||
&& let Some((previous, _)) = tools.get_mut(row)
|
||||
{
|
||||
if matches!(previous["status"].as_str(), Some("started" | "pending")) {
|
||||
*previous = event;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let len = current.items.len();
|
||||
let location = if let Some(TurnItem::Tools(tools)) = current.items.last_mut() {
|
||||
let row = tools.len();
|
||||
tools.push((event, index));
|
||||
(len - 1, row)
|
||||
} else {
|
||||
current.items.push(TurnItem::Tools(vec![(event, index)]));
|
||||
(len, 0)
|
||||
};
|
||||
if let Some(key) = identity { call_rows.insert(key, location); }
|
||||
} else if let Some(text) = message["text"].as_str().filter(|s| !s.is_empty()) {
|
||||
if activity(message) {
|
||||
current.items.push(TurnItem::Notice(text, index));
|
||||
} else {
|
||||
current.items.push(TurnItem::Reply(text, index));
|
||||
current.last_reply = Some((text, index));
|
||||
}
|
||||
}
|
||||
if current.target.is_none() {
|
||||
current.target = message.get("target").filter(|target| target.is_object());
|
||||
}
|
||||
}
|
||||
if current.user.is_some() || !current.items.is_empty() {
|
||||
out.push(current);
|
||||
}
|
||||
// The same status can be recorded again each time a stage resumes. The
|
||||
// transcript keeps every record; the timeline shows only the latest copy.
|
||||
let mut latest = std::collections::HashMap::new();
|
||||
for (turn_index, turn) in out.iter().enumerate() {
|
||||
for (item_index, item) in turn.items.iter().enumerate() {
|
||||
if let TurnItem::Notice(text, _) = item { latest.insert(*text, (turn_index, item_index)); }
|
||||
}
|
||||
}
|
||||
for (turn_index, turn) in out.iter_mut().enumerate() {
|
||||
let mut item_index = 0;
|
||||
turn.items.retain(|item| {
|
||||
let keep = match item {
|
||||
TurnItem::Notice(text, _) => latest.get(text).copied() == Some((turn_index, item_index)),
|
||||
_ => true,
|
||||
};
|
||||
item_index += 1;
|
||||
keep
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,150 @@
|
||||
use super::super::{Value, json};
|
||||
use super::brief::{brief_variants, non_empty_str, set_brief_variants};
|
||||
use super::form_widgets_ui::{field_key, field_kind};
|
||||
use super::intake::BARCODE_SEPARATORS;
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(in crate::jiansun) fn binding_barcodes(binding: &Value) -> impl Iterator<Item = &str> {
|
||||
let legacy = binding.as_str().into_iter().flat_map(|text| text.split(BARCODE_SEPARATORS));
|
||||
let current = binding.as_array().into_iter().flatten().filter_map(Value::as_str);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
legacy.chain(current).map(str::trim)
|
||||
.filter(move |barcode| !barcode.is_empty() && seen.insert(*barcode))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn project_barcodes(brief: &Value) -> impl Iterator<Item = &str> {
|
||||
let has_cards = brief["barcodeEntries"].is_array();
|
||||
let from_cards = brief["barcodeEntries"].as_array().into_iter().flatten()
|
||||
.filter_map(|row| non_empty_str(&row["barcode"]));
|
||||
let from_bindings = brief["barcodeBindings"].as_object().into_iter().flat_map(|groups| groups.values()).flat_map(binding_barcodes);
|
||||
let from_normalized = brief["normalizedProduct"]["variants"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flat_map(|variant| variant["barcodes"].as_array().into_iter().flatten())
|
||||
.filter_map(|row| non_empty_str(&row["barcode"]));
|
||||
let mut seen = HashSet::new();
|
||||
from_cards.chain(from_bindings.chain(from_normalized).filter(move |_| !has_cards))
|
||||
.filter(move |code| seen.insert(*code))
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) 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,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) 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::<f64>().ok())
|
||||
.and_then(|value| serde_json::Number::from_f64(value * ratio)).map_or_else(|| json!(""), Value::Number)
|
||||
} else {
|
||||
row.get(key).cloned().unwrap_or_else(|| json!(""))
|
||||
};
|
||||
brief["intake"]["barcodeValues"][&code][key] = value;
|
||||
}
|
||||
}
|
||||
if variants != brief_variants(brief) { set_brief_variants(brief, variants); }
|
||||
brief["barcodeBindings"] = Value::Object(bindings);
|
||||
brief["barcodeEntries"] = json!(rows);
|
||||
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(in crate::jiansun) fn update_detail_barcode(brief: &mut Value) -> bool {
|
||||
let selected = brief["detailBarcode"].as_str();
|
||||
let next = {
|
||||
let mut codes = project_barcodes(brief);
|
||||
let first = codes.next();
|
||||
let next = if codes.next().is_none() {
|
||||
first
|
||||
} else {
|
||||
selected.filter(|selected| project_barcodes(brief).any(|code| code == *selected))
|
||||
};
|
||||
if selected == next { return false; }
|
||||
next.map(str::to_owned)
|
||||
};
|
||||
if let Some(next) = next {
|
||||
brief["detailBarcode"] = json!(next);
|
||||
} else if let Some(fields) = brief.as_object_mut() {
|
||||
fields.remove("detailBarcode");
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn replace_barcode(brief: &mut Value, old: &str, replacement: Option<&str>) {
|
||||
if brief["detailBarcode"] == old {
|
||||
if let Some(code) = replacement {
|
||||
brief["detailBarcode"] = json!(code);
|
||||
} else if let Some(fields) = brief.as_object_mut() {
|
||||
fields.remove("detailBarcode");
|
||||
}
|
||||
}
|
||||
if let Some(images) = brief["images"].as_array_mut() {
|
||||
if let Some(barcode) = replacement {
|
||||
for image in images.iter_mut().filter(|image| image["barcode"] == old) { image["barcode"] = json!(barcode); }
|
||||
} else {
|
||||
images.retain(|image| image["barcode"] != old);
|
||||
}
|
||||
}
|
||||
if let Some(values) = brief.get_mut("platformFacts").and_then(|facts| facts["barcodes"].as_object_mut())
|
||||
&& let Some(value) = values.remove(old) && let Some(code) = replacement
|
||||
{
|
||||
values.insert(code.to_owned(), value);
|
||||
}
|
||||
if let Some(values) = brief.get_mut("intake").and_then(|intake| intake.get_mut("barcodeValues"))
|
||||
.and_then(Value::as_object_mut)
|
||||
&& let Some(value) = values.remove(old)
|
||||
&& let Some(code) = replacement
|
||||
{
|
||||
values.insert(code.to_owned(), value);
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,779 @@
|
||||
use super::super::{Value, json};
|
||||
use super::super::creation_reads::wizard::{self, CreationStage};
|
||||
use super::barcode::{binding_barcodes, project_barcodes, update_detail_barcode, write_legacy_barcode_fields};
|
||||
use super::form_widgets_ui::{field_kind, is_product_name_field, spu_field};
|
||||
use super::intake::dimension_text;
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(in crate::jiansun) fn empty_brief() -> Value {
|
||||
json!({"source":"upload","name":"","brandId":"","brandName":"","categoryId":"","categoryName":"","identifierType":"spu","identifier":"","barcodeBindings":{},"variant":"","colorMaterialId":"","colorName":"","variants":[],"templateSelection":null,"dimensions":{"length":"","width":"","height":"","unit":"mm"},"images":[],"note":""})
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn variant_identity(material: &str) -> String {
|
||||
if material.len() == 36
|
||||
&& material.bytes().enumerate().all(|(index, byte)| if [8, 13, 18, 23].contains(&index) { byte == b'-' } else { byte.is_ascii_hexdigit() })
|
||||
{
|
||||
return material.to_ascii_lowercase();
|
||||
}
|
||||
// Application-defined UUIDv8 for non-UUID legacy material identifiers. It
|
||||
// is persisted with the selected row; no order/index becomes its identity.
|
||||
let left = egui::Id::unique(("material-variant-a-v1", material)).value();
|
||||
let right = egui::Id::unique(("material-variant-b-v1", material)).value();
|
||||
format!(
|
||||
"{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
|
||||
left >> 32,
|
||||
(left >> 16) & 0xffff,
|
||||
(left & 0x0fff) | 0x8000,
|
||||
((right >> 48) & 0x0fff) | 0x8000,
|
||||
right & 0xffff_ffff_ffff
|
||||
)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn brief_variants(brief: &Value) -> Vec<Value> {
|
||||
if let Some(rows) = brief["variants"].as_array().filter(|rows| !rows.is_empty()) {
|
||||
return rows.clone();
|
||||
}
|
||||
let Some(material) = brief["colorMaterialId"].as_str().filter(|id| !id.is_empty()) else { return vec![] };
|
||||
let name = brief["colorName"].as_str().filter(|name| !name.is_empty()).unwrap_or("花色");
|
||||
vec![json!({"id":variant_identity(material),"name":name,"colorMaterialId":material,"colorName":brief["colorName"],"images":[]})]
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn set_brief_variants(brief: &mut Value, rows: Vec<Value>) {
|
||||
brief["colorMaterialId"] = rows.first().map(|row| row["colorMaterialId"].clone()).unwrap_or(json!(""));
|
||||
brief["colorName"] = rows.first().map(|row| row["colorName"].clone()).unwrap_or(json!(""));
|
||||
brief["variants"] = json!(rows);
|
||||
// brief.variant is the original product option text, not the selected color.
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn template_identity(value: &Value) -> bool {
|
||||
value["id"].as_str().is_some_and(|id| !id.is_empty() && id.chars().count() <= 160)
|
||||
&& value["version"].as_str().is_some_and(|version| !version.is_empty() && version.chars().count() <= 100)
|
||||
&& value["contentHash"].as_str().is_some_and(|hash| hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn template_compatibility_warnings(sources: &[&Value]) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
for source in sources {
|
||||
for key in ["compatibilityWarnings", "warnings"] {
|
||||
for item in source[key].as_array().into_iter().flatten() {
|
||||
let Some(text) = item.as_str().map(str::trim).filter(|s| !s.is_empty()) else { continue };
|
||||
let text = text.chars().take(400).collect::<String>();
|
||||
if !out.contains(&text) {
|
||||
out.push(text);
|
||||
if out.len() >= 20 {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn default_resource_component(parts: &[Value]) -> Option<&Value> {
|
||||
if let [only] = parts {
|
||||
return Some(only);
|
||||
}
|
||||
let mut detail = parts.iter().filter(|part| part["kind"] == "detail");
|
||||
let candidate = detail.next()?;
|
||||
detail.next().is_none().then_some(candidate)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn selected_template(brief: &Value, workflow: &Value, canonical_brief: &Value) -> Value {
|
||||
let selected = &brief["templateSelection"];
|
||||
if template_identity(selected)
|
||||
&& selected.get("brandId").is_none_or(|id| *id == brief["brandId"])
|
||||
&& selected.get("categoryId").is_none_or(|id| *id == brief["categoryId"])
|
||||
{
|
||||
return selected.clone();
|
||||
}
|
||||
if brief["brandId"] != canonical_brief["brandId"] || brief["categoryId"] != canonical_brief["categoryId"] {
|
||||
return Value::Null;
|
||||
}
|
||||
let installed = json!({"id":workflow["templateId"],"version":workflow["templateVersion"],"contentHash":workflow["templateHash"],"name":workflow["templateName"],"brandId":brief["brandId"],"categoryId":brief["categoryId"]});
|
||||
if template_identity(&installed) { installed } else { Value::Null }
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn image_rows(brief: &Value) -> Vec<(Value, String)> {
|
||||
let mut rows = brief["images"].as_array().into_iter().flatten().cloned().map(|image| (image, String::new())).collect::<Vec<_>>();
|
||||
for variant in brief_variants(brief) {
|
||||
let owner = variant["id"].as_str().unwrap_or("").to_owned();
|
||||
rows.extend(variant["images"].as_array().into_iter().flatten().cloned().map(|image| (image, owner.clone())));
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn store_image_rows(brief: &mut Value, rows: Vec<(Value, String)>) -> Result<(), String> {
|
||||
if !brief.is_object() {
|
||||
return Err("产品资料格式无效,未更改图片归属".into());
|
||||
}
|
||||
let mut variants = brief_variants(brief);
|
||||
if rows.iter().any(|(_, owner)| !owner.is_empty() && !variants.iter().any(|variant| variant["id"] == owner.as_str())) {
|
||||
return Err("图片所属花色已变化,请重新选择归属".into());
|
||||
}
|
||||
for variant in &mut variants {
|
||||
variant["images"] = json!([]);
|
||||
}
|
||||
let mut common = Vec::new();
|
||||
for (image, owner) in rows {
|
||||
if let Some(variant) = variants.iter_mut().find(|row| row["id"] == owner) {
|
||||
let Some(images) = variant["images"].as_array_mut() else { return Err("花色图片记录无效,未更改图片归属".into()) };
|
||||
images.push(image);
|
||||
} else {
|
||||
common.push(image);
|
||||
}
|
||||
}
|
||||
let removed = brief["images"].as_array().into_iter().flatten()
|
||||
.filter(|old| old["barcode"].is_string() && !common.iter().any(|image| image["source"] == old["source"]
|
||||
&& image["barcode"] == old["barcode"] && image["fieldKey"] == old["fieldKey"]))
|
||||
.cloned().collect::<Vec<_>>();
|
||||
for row in brief["barcodeEntries"].as_array_mut().into_iter().flatten() {
|
||||
if let Some(pictures) = row["images"].as_array_mut() {
|
||||
pictures.retain(|picture| !removed.iter().any(|old| old["source"] == picture["source"]
|
||||
&& old["barcode"] == picture["barcode"] && old["fieldKey"] == picture["fieldKey"]));
|
||||
}
|
||||
}
|
||||
brief["images"] = json!(common);
|
||||
if brief.get("variants").is_some() || !variants.is_empty() {
|
||||
set_brief_variants(brief, variants);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) struct ReadinessItem {
|
||||
pub(in crate::jiansun) field_key: String,
|
||||
pub(in crate::jiansun) label: String,
|
||||
pub(in crate::jiansun) message: String,
|
||||
pub(in crate::jiansun) ready: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(in crate::jiansun) struct NormalizedProductSummary {
|
||||
pub(in crate::jiansun) has_platform_data: bool,
|
||||
pub(in crate::jiansun) spu: String,
|
||||
pub(in crate::jiansun) platform_brand: String,
|
||||
pub(in crate::jiansun) platform_category: String,
|
||||
pub(in crate::jiansun) series_or_model: String,
|
||||
pub(in crate::jiansun) dimensions_display: Option<String>,
|
||||
pub(in crate::jiansun) materials: Vec<String>,
|
||||
pub(in crate::jiansun) attributes: Vec<(String, String)>,
|
||||
pub(in crate::jiansun) summary: String,
|
||||
pub(in crate::jiansun) selling_points: Vec<String>,
|
||||
pub(in crate::jiansun) trace_source: String,
|
||||
#[cfg(test)]
|
||||
pub(in crate::jiansun) fetched_at: String,
|
||||
pub(in crate::jiansun) raw_field_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(in crate::jiansun) struct NormalizedSkuRow {
|
||||
pub(in crate::jiansun) barcode: String,
|
||||
#[cfg(test)]
|
||||
pub(in crate::jiansun) color_name: String,
|
||||
#[cfg(test)]
|
||||
pub(in crate::jiansun) spec: String,
|
||||
#[cfg(test)]
|
||||
pub(in crate::jiansun) dimensions_display: Option<String>,
|
||||
#[cfg(test)]
|
||||
pub(in crate::jiansun) image_count: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(in crate::jiansun) struct NormalizedColorGroup {
|
||||
pub(in crate::jiansun) id: String,
|
||||
pub(in crate::jiansun) color_name: String,
|
||||
pub(in crate::jiansun) skus: Vec<NormalizedSkuRow>,
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn non_empty_str(value: &Value) -> Option<&str> {
|
||||
value.as_str().map(str::trim).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn string_list(value: &Value) -> Vec<String> {
|
||||
match value {
|
||||
Value::String(text) => text
|
||||
.split(['\n', '、', ',', ',', ';', ';'])
|
||||
.map(str::trim)
|
||||
.filter(|item| !item.is_empty())
|
||||
.map(str::to_owned)
|
||||
.collect(),
|
||||
Value::Array(items) => items
|
||||
.iter()
|
||||
.filter_map(non_empty_str)
|
||||
.map(str::to_owned)
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn dedupe_strings(items: Vec<String>) -> Vec<String> {
|
||||
let mut seen = HashSet::new();
|
||||
items.into_iter().filter(|item| seen.insert(item.to_lowercase())).collect()
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn normalized_product_summary(brief: &Value) -> NormalizedProductSummary {
|
||||
let np = &brief["normalizedProduct"];
|
||||
let pf = &brief["platformFacts"];
|
||||
if np.is_object() {
|
||||
let identity = &np["identity"];
|
||||
let specs = &np["specs"];
|
||||
let copy = &np["copy"];
|
||||
let trace = &np["trace"];
|
||||
let dims = if specs["dimensions"].is_object() {
|
||||
non_empty_str(&specs["dimensions"]["display"])
|
||||
.map(str::to_owned)
|
||||
.or_else(|| dimension_text(&specs["dimensions"]))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let materials = dedupe_strings(string_list(&specs["materials"]));
|
||||
let mut seen_attr = HashSet::new();
|
||||
let mut attributes = Vec::new();
|
||||
for attr in specs["attributes"].as_array().into_iter().flatten() {
|
||||
let label = non_empty_str(&attr["label"]).or_else(|| non_empty_str(&attr["key"]));
|
||||
let value = non_empty_str(&attr["value"]);
|
||||
if let (Some(label), Some(value)) = (label, value) {
|
||||
let lower = label.to_lowercase();
|
||||
if matches!(label, "尺寸" | "产品尺寸" | "长" | "宽" | "高" | "品牌" | "品类" | "颜色" | "花色")
|
||||
&& (dims.is_some() || !materials.is_empty())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if seen_attr.insert(format!("{lower}:{value}")) {
|
||||
attributes.push((label.to_owned(), value.to_owned()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return NormalizedProductSummary {
|
||||
has_platform_data: true,
|
||||
spu: non_empty_str(&identity["spu"]).or_else(|| non_empty_str(&trace["upstreamSpu"])).or_else(|| non_empty_str(&brief["identifier"])).unwrap_or("").to_owned(),
|
||||
platform_brand: non_empty_str(&identity["platformBrand"]).unwrap_or("").to_owned(),
|
||||
platform_category: non_empty_str(&identity["platformCategory"]).unwrap_or("").to_owned(),
|
||||
series_or_model: non_empty_str(&identity["seriesOrModel"]).unwrap_or("").to_owned(),
|
||||
dimensions_display: dims,
|
||||
materials,
|
||||
attributes,
|
||||
summary: non_empty_str(©["summary"]).unwrap_or("").to_owned(),
|
||||
selling_points: dedupe_strings(string_list(©["sellingPoints"])),
|
||||
trace_source: non_empty_str(&trace["source"]).unwrap_or("产品平台").to_owned(),
|
||||
#[cfg(test)]
|
||||
fetched_at: non_empty_str(&trace["fetchedAt"]).unwrap_or("").to_owned(),
|
||||
raw_field_warnings: dedupe_strings(string_list(&trace["rawFieldWarnings"])),
|
||||
};
|
||||
}
|
||||
if pf.is_object() {
|
||||
let shared = &pf["shared"];
|
||||
let dims = dimension_text(&shared["dimensions"]);
|
||||
let materials = dedupe_strings(string_list(&shared["material"]));
|
||||
let mut attributes = Vec::new();
|
||||
if let Some(map) = shared["attributes"].as_object() {
|
||||
for (k, v) in map {
|
||||
if let Some(text) = non_empty_str(v)
|
||||
&& !matches!(k.as_str(), "尺寸" | "产品尺寸" | "长" | "宽" | "高")
|
||||
{
|
||||
attributes.push((k.clone(), text.to_owned()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return NormalizedProductSummary {
|
||||
has_platform_data: true,
|
||||
spu: non_empty_str(&pf["spu"]).or_else(|| non_empty_str(&brief["identifier"])).unwrap_or("").to_owned(),
|
||||
platform_brand: non_empty_str(&shared["brandName"]).or_else(|| non_empty_str(&pf["brandName"])).unwrap_or("").to_owned(),
|
||||
platform_category: non_empty_str(&shared["categoryName"]).or_else(|| non_empty_str(&pf["categoryName"])).unwrap_or("").to_owned(),
|
||||
series_or_model: non_empty_str(&brief["variant"]).unwrap_or("").to_owned(),
|
||||
dimensions_display: dims,
|
||||
materials,
|
||||
attributes,
|
||||
summary: non_empty_str(&shared["description"]).unwrap_or("").to_owned(),
|
||||
selling_points: dedupe_strings(string_list(&shared["sellingPoints"])),
|
||||
trace_source: "产品平台".into(),
|
||||
#[cfg(test)]
|
||||
fetched_at: String::new(),
|
||||
raw_field_warnings: Vec::new(),
|
||||
};
|
||||
}
|
||||
NormalizedProductSummary::default()
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn sku_display_label(brief: &Value, barcode: &str) -> String {
|
||||
let mut color = String::new();
|
||||
let mut spec = String::new();
|
||||
if let Some(variants) = brief["normalizedProduct"]["variants"].as_array() {
|
||||
'outer: for variant in variants {
|
||||
let v_color = non_empty_str(&variant["colorName"]).unwrap_or("");
|
||||
for row in variant["barcodes"].as_array().into_iter().flatten() {
|
||||
if non_empty_str(&row["barcode"]) == Some(barcode) {
|
||||
color = v_color.to_owned();
|
||||
let s = non_empty_str(&row["spec"])
|
||||
.or_else(|| non_empty_str(&row["skuName"]))
|
||||
.map(str::to_owned)
|
||||
.or_else(|| non_empty_str(&row["dimensions"]["display"]).map(str::to_owned))
|
||||
.or_else(|| dimension_text(&row["dimensions"]))
|
||||
.unwrap_or_default();
|
||||
spec = s;
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if color.is_empty() && spec.is_empty() {
|
||||
let pf = &brief["platformFacts"]["barcodes"][barcode];
|
||||
if pf.is_object() {
|
||||
color = non_empty_str(&pf["colorName"]).unwrap_or("").to_owned();
|
||||
spec = non_empty_str(&pf["spec"])
|
||||
.or_else(|| non_empty_str(&pf["sizeText"]))
|
||||
.map(str::to_owned)
|
||||
.or_else(|| dimension_text(&pf["dimensions"]))
|
||||
.unwrap_or_default();
|
||||
}
|
||||
}
|
||||
if color.is_empty() {
|
||||
for variant in brief_variants(brief) {
|
||||
if let Some(id) = variant["id"].as_str()
|
||||
&& binding_barcodes(&brief["barcodeBindings"][id]).any(|code| code == barcode)
|
||||
{
|
||||
color = non_empty_str(&variant["colorName"])
|
||||
.or_else(|| non_empty_str(&variant["name"]))
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Deduplicate color prefix if spec already includes the color name.
|
||||
if !color.is_empty() && !spec.is_empty() && spec.eq_ignore_ascii_case(&color) {
|
||||
spec.clear();
|
||||
}
|
||||
match (color.is_empty(), spec.is_empty()) {
|
||||
(false, false) => format!("{color} · {spec} ({barcode})"),
|
||||
(false, true) => format!("{color} ({barcode})"),
|
||||
(true, false) => format!("{spec} ({barcode})"),
|
||||
(true, true) => barcode.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn sku_short_label(brief: &Value, barcode: &str) -> String {
|
||||
let full = sku_display_label(brief, barcode);
|
||||
full.strip_suffix(&format!(" ({barcode})")).unwrap_or(&full).to_owned()
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn normalized_color_groups(brief: &Value) -> Vec<NormalizedColorGroup> {
|
||||
let mut groups: Vec<NormalizedColorGroup> = Vec::new();
|
||||
let mut seen_barcodes: HashSet<String> = HashSet::new();
|
||||
#[cfg(test)]
|
||||
let image_count_for = |code: &str, asset_ids: Option<&[Value]>| -> usize {
|
||||
let explicit_ids = asset_ids.map(|arr| arr.len()).unwrap_or(0);
|
||||
let brief_imgs = brief["images"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|img| img["barcode"] == code)
|
||||
.count();
|
||||
let norm_imgs = brief["normalizedProduct"]["assets"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|asset| asset["barcode"] == code && asset["selectedForProject"] != false)
|
||||
.count();
|
||||
explicit_ids.max(brief_imgs).max(norm_imgs)
|
||||
};
|
||||
|
||||
if let Some(np_variants) = brief["normalizedProduct"]["variants"].as_array().filter(|a| !a.is_empty()) {
|
||||
for variant in np_variants {
|
||||
let color_name = non_empty_str(&variant["colorName"]).unwrap_or("默认花色").to_owned();
|
||||
let id = non_empty_str(&variant["id"]).unwrap_or(&color_name).to_owned();
|
||||
let mut skus = Vec::new();
|
||||
for row in variant["barcodes"].as_array().into_iter().flatten() {
|
||||
let Some(code) = non_empty_str(&row["barcode"]) else { continue };
|
||||
if !seen_barcodes.insert(code.to_owned()) {
|
||||
continue;
|
||||
}
|
||||
skus.push(NormalizedSkuRow {
|
||||
barcode: code.to_owned(),
|
||||
#[cfg(test)]
|
||||
color_name: color_name.clone(),
|
||||
#[cfg(test)]
|
||||
spec: non_empty_str(&row["spec"])
|
||||
.or_else(|| non_empty_str(&row["skuName"]))
|
||||
.filter(|spec| !spec.eq_ignore_ascii_case(&color_name))
|
||||
.unwrap_or("")
|
||||
.to_owned(),
|
||||
#[cfg(test)]
|
||||
dimensions_display: non_empty_str(&row["dimensions"]["display"])
|
||||
.map(str::to_owned)
|
||||
.or_else(|| dimension_text(&row["dimensions"])),
|
||||
#[cfg(test)]
|
||||
image_count: image_count_for(code, row["imageIds"].as_array().map(Vec::as_slice)),
|
||||
});
|
||||
}
|
||||
if !skus.is_empty() {
|
||||
groups.push(NormalizedColorGroup { id, color_name, skus });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Merge any manual / legacy barcodeBindings not yet covered by normalizedProduct.variants.
|
||||
let variants = brief_variants(brief);
|
||||
let mut binding_groups: Vec<(String, String)> = variants
|
||||
.iter()
|
||||
.filter_map(|v| Some((v["id"].as_str()?.to_owned(), v["name"].as_str().unwrap_or("默认花色").to_owned())))
|
||||
.collect();
|
||||
if binding_groups.is_empty() || binding_barcodes(&brief["barcodeBindings"]["default"]).next().is_some() {
|
||||
binding_groups.insert(0, ("default".into(), "默认花色".into()));
|
||||
}
|
||||
for (group_id, group_label) in binding_groups {
|
||||
let codes: Vec<String> = binding_barcodes(&brief["barcodeBindings"][&group_id])
|
||||
.filter(|code| seen_barcodes.insert((*code).to_owned()))
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
for code in codes {
|
||||
let pf = &brief["platformFacts"]["barcodes"][&code];
|
||||
let color_name = non_empty_str(&pf["colorName"])
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| group_label.clone());
|
||||
let row = NormalizedSkuRow {
|
||||
#[cfg(test)]
|
||||
color_name: color_name.clone(),
|
||||
#[cfg(test)]
|
||||
spec: non_empty_str(&pf["spec"])
|
||||
.or_else(|| non_empty_str(&pf["sizeText"]))
|
||||
.filter(|spec| !spec.eq_ignore_ascii_case(&color_name))
|
||||
.unwrap_or("")
|
||||
.to_owned(),
|
||||
#[cfg(test)]
|
||||
dimensions_display: dimension_text(&pf["dimensions"]),
|
||||
#[cfg(test)]
|
||||
image_count: image_count_for(&code, None),
|
||||
barcode: code,
|
||||
};
|
||||
if let Some(existing) = groups.iter_mut().find(|g| g.color_name == color_name) {
|
||||
existing.skus.push(row);
|
||||
} else {
|
||||
groups.push(NormalizedColorGroup {
|
||||
id: if group_id == "default" { color_name.clone() } else { group_id.clone() },
|
||||
color_name,
|
||||
skus: vec![row],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn selected_output_scopes(brief: &Value) -> Vec<String> {
|
||||
if let Some(arr) = brief["outputScopes"].as_array() {
|
||||
let items: Vec<String> = arr
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.filter(|s| matches!(*s, "detail" | "main_images" | "sku_images"))
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if !items.is_empty() {
|
||||
return items;
|
||||
}
|
||||
}
|
||||
vec!["detail".into(), "main_images".into(), "sku_images".into()]
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn selected_visual_asset_count(brief: &Value) -> usize {
|
||||
let mut sources = HashSet::new();
|
||||
let mut count = 0usize;
|
||||
for (image, _) in image_rows(brief) {
|
||||
if let Some(src) = non_empty_str(&image["source"]) {
|
||||
if sources.insert(src.to_owned()) {
|
||||
count += 1;
|
||||
}
|
||||
} else {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
for asset in brief["normalizedProduct"]["assets"].as_array().into_iter().flatten() {
|
||||
if asset["selectedForProject"] == false {
|
||||
continue;
|
||||
}
|
||||
if let Some(src) = non_empty_str(&asset["localSource"]).or_else(|| non_empty_str(&asset["url"])).or_else(|| non_empty_str(&asset["id"])) {
|
||||
if sources.insert(src.to_owned()) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn has_selected_product_image(brief: &Value) -> bool {
|
||||
selected_product_image(brief, |_| true)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn selected_product_image(brief: &Value, local_exists: impl Fn(&str) -> bool) -> bool {
|
||||
let mut platform_assets = brief["normalizedProduct"]["assets"].as_array().into_iter().flatten();
|
||||
let local_ok = reference_images(brief).any(|image| {
|
||||
image["purpose"] == "product" && (image["barcode"].is_null() || image["barcode"] == brief["detailBarcode"])
|
||||
&& non_empty_str(&image["source"]).is_some_and(&local_exists)
|
||||
&& !(image["platformImage"] == true && platform_assets.clone().any(|asset| {
|
||||
asset["localSource"] == image["source"] && asset["selectedForProject"] == false
|
||||
}))
|
||||
});
|
||||
if local_ok || brief["barcodeEntries"].as_array().into_iter().flatten().any(|row| {
|
||||
(brief["detailBarcode"].is_null() || row["barcode"] == brief["detailBarcode"])
|
||||
&& row["images"].as_array().into_iter().flatten().any(|image| {
|
||||
image["purpose"] == "product" && non_empty_str(&image["source"]).is_some_and(&local_exists)
|
||||
})
|
||||
}) {
|
||||
return true;
|
||||
}
|
||||
platform_assets.any(|asset| {
|
||||
asset["selectedForProject"] != false
|
||||
&& matches!(asset["kind"].as_str(), Some("whiteBackground" | "main"))
|
||||
&& (asset["barcode"].is_null()
|
||||
|| non_empty_str(&asset["barcode"]).is_none()
|
||||
|| asset["barcode"] == brief["detailBarcode"])
|
||||
&& (non_empty_str(&asset["localSource"]).is_some_and(&local_exists) || non_empty_str(&asset["url"]).is_some())
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn reference_images(brief: &Value) -> impl Iterator<Item = &Value> {
|
||||
brief["images"].as_array().into_iter().flatten().chain(
|
||||
brief["variants"].as_array().into_iter().flatten()
|
||||
.flat_map(|variant| variant["images"].as_array().into_iter().flatten()),
|
||||
)
|
||||
}
|
||||
|
||||
/// The canvas may save a form snapshot before the initial creation read returns revision zero.
|
||||
pub(in crate::jiansun) const OUTPUT_SCOPE_OPTIONS: [(&str, &str, &str); 3] = [
|
||||
("output-tag-detail", "detail", "详情页"),
|
||||
("output-tag-main_images", "main_images", "主图"),
|
||||
("output-tag-sku_images", "sku_images", "SKU 图"),
|
||||
];
|
||||
|
||||
pub fn saved_creation_draft_brief<'a>(record: &Value, draft: &'a Value) -> Option<&'a Value> {
|
||||
(draft["brief"].is_object()
|
||||
&& (draft["revision"] == record["revision"] || draft["revision"].is_null() && record["revision"] == 0))
|
||||
.then_some(&draft["brief"])
|
||||
}
|
||||
|
||||
/// Use the same required fields as the wizard when classifying a saved brief.
|
||||
pub fn incomplete_brief_stage(brief: &Value, workflow: &Value, local_exists: impl Fn(&str) -> bool) -> Option<CreationStage> {
|
||||
if workflow["canvasFirst"] == true {
|
||||
return None;
|
||||
}
|
||||
let template = selected_template(brief, workflow, brief);
|
||||
let has_template = template_identity(&template);
|
||||
let has_source = reference_images(brief).any(|image| non_empty_str(&image["source"]).is_some_and(&local_exists))
|
||||
|| ["normalizedProduct", "platformFacts"].into_iter().any(|key| {
|
||||
brief[key].as_object().is_some_and(|fields| !fields.is_empty())
|
||||
})
|
||||
|| (brief["source"] == "library" && non_empty_str(&brief["name"]).is_some()
|
||||
&& non_empty_str(&brief["identifier"]).is_some());
|
||||
if !has_template && !has_source {
|
||||
return Some(CreationStage::Source);
|
||||
}
|
||||
let readiness = brief_readiness_with_images(brief, &template, selected_product_image(brief, local_exists));
|
||||
if readiness.iter().any(|item| !item.ready && matches!(item.field_key.as_str(), "brand" | "category" | "template")) {
|
||||
Some(CreationStage::Template)
|
||||
} else {
|
||||
readiness.iter().any(|item| !item.ready).then_some(CreationStage::Details)
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn intake_value_filled(field: &Value, value: &Value) -> bool {
|
||||
match field["type"].as_str() {
|
||||
Some("boolean") => value.is_boolean(),
|
||||
Some("number") => value.is_number() || value.as_str().is_some_and(|s| !s.trim().is_empty()),
|
||||
_ => value.as_str().is_some_and(|s| !s.trim().is_empty()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn brief_readiness(brief: &Value, template: &Value) -> Vec<ReadinessItem> {
|
||||
brief_readiness_with_images(brief, template, has_selected_product_image(brief))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn brief_readiness_with_images(brief: &Value, template: &Value, product_image_ready: bool) -> Vec<ReadinessItem> {
|
||||
let filled = |field: &str| brief[field].as_str().is_some_and(|value| !value.trim().is_empty());
|
||||
let mut items = vec![
|
||||
ReadinessItem { field_key: "brand".into(), label: "品牌".into(), message: "请选择品牌".into(), ready: filled("brandId") },
|
||||
ReadinessItem { field_key: "category".into(), label: "品类".into(), message: "请选择品类".into(), ready: filled("categoryId") },
|
||||
ReadinessItem { field_key: "template".into(), label: "模板".into(), message: "请选择项目模板".into(), ready: template_identity(template) },
|
||||
ReadinessItem { field_key: "name".into(), label: "产品名称".into(), message: "请输入产品名称".into(), ready: filled("name") },
|
||||
ReadinessItem { field_key: "images".into(), label: "产品图".into(), message: "添加或勾选至少一张商品主体图".into(), ready: product_image_ready },
|
||||
];
|
||||
if project_barcodes(brief).next().is_some() {
|
||||
items.push(ReadinessItem {
|
||||
field_key: "identifier".into(),
|
||||
label: "SPU 型号".into(),
|
||||
message: "请填写 SPU 型号".into(),
|
||||
ready: filled(spu_field(brief)),
|
||||
});
|
||||
}
|
||||
if project_barcodes(brief).nth(1).is_some() {
|
||||
let ready = brief["detailBarcode"].as_str().is_some_and(|selected| project_barcodes(brief).any(|code| code == selected));
|
||||
items.push(ReadinessItem {
|
||||
field_key: "detail-barcode".into(),
|
||||
label: "详情主款".into(),
|
||||
message: "请选择一个款式条码作为详情主款".into(),
|
||||
ready,
|
||||
});
|
||||
}
|
||||
if brief["intake"]["schema"]["version"] == 1 {
|
||||
let product_values = &brief["intake"]["productValues"];
|
||||
for field in brief["intake"]["schema"]["productFields"].as_array().into_iter().flatten() {
|
||||
if field["required"] == true && field_kind(field) != "image" && !is_product_name_field(field) {
|
||||
let Some(id) = field["id"].as_str().filter(|id| !id.trim().is_empty()) else { continue };
|
||||
let label = field["label"].as_str().unwrap_or(id);
|
||||
items.push(ReadinessItem {
|
||||
field_key: format!("intake-product:{id}"),
|
||||
label: label.to_owned(),
|
||||
message: format!("请填写必填字段「{label}」"),
|
||||
ready: intake_value_filled(field, &product_values[id]),
|
||||
});
|
||||
}
|
||||
}
|
||||
let active_code = brief["detailBarcode"].as_str().or_else(|| project_barcodes(brief).next());
|
||||
if let Some(code) = active_code {
|
||||
let barcode_values = &brief["intake"]["barcodeValues"][code];
|
||||
for field in brief["intake"]["schema"]["barcodeFields"].as_array().into_iter().flatten() {
|
||||
if field["required"] == true && field_kind(field) != "image" {
|
||||
let Some(id) = field["id"].as_str().filter(|id| !id.trim().is_empty()) else { continue };
|
||||
let label = field["label"].as_str().unwrap_or(id);
|
||||
items.push(ReadinessItem {
|
||||
field_key: format!("intake-barcode:{code}:{id}"),
|
||||
label: label.to_owned(),
|
||||
message: format!("请填写主款必填字段「{label}」"),
|
||||
ready: intake_value_filled(field, &barcode_values[id]),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn merge_dimensions(current: &Value, incoming: &Value, cleared: impl Fn(&str) -> bool) -> Value {
|
||||
let mut merged = incoming.clone();
|
||||
if !current.is_object() { return merged; }
|
||||
let axes = ["length", "width", "height", "depth", "secondaryHeight"];
|
||||
let keep_unit = cleared("unit") || axes.iter().any(|axis| non_empty_str(¤t[*axis]).is_some()
|
||||
|| current[*axis].is_number());
|
||||
let mm = |unit: &Value| match unit.as_str() {
|
||||
Some("m" | "米") => 1000.0, Some("cm" | "厘米") => 10.0, _ => 1.0,
|
||||
};
|
||||
if keep_unit {
|
||||
let scale = mm(&incoming["unit"]) / mm(¤t["unit"]);
|
||||
if scale != 1.0 {
|
||||
for axis in axes {
|
||||
if let Some(value) = incoming[axis].as_f64().or_else(|| incoming[axis].as_str()?.parse().ok()) {
|
||||
merged[axis] = json!(((value * scale * 1000.0).round() / 1000.0).to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
merged["unit"] = current["unit"].clone();
|
||||
}
|
||||
for axis in axes {
|
||||
let value = ¤t[axis];
|
||||
if non_empty_str(value).is_some() || value.is_number() || cleared(axis) {
|
||||
merged[axis] = value.clone();
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn merge_platform_brief_preserving_manual_edits(current: &Value, incoming: &Value, edited: &HashSet<String>) -> (Value, usize) {
|
||||
let mut merged = incoming.clone();
|
||||
let mut preserved = 0;
|
||||
for (key, fields) in [
|
||||
("name", &["name"][..]), ("note", &["note"][..]),
|
||||
("brand", &["brandId", "brandName"][..]), ("category", &["categoryId", "categoryName"][..]),
|
||||
("outputScopes", &["outputScopes"][..]),
|
||||
] {
|
||||
if edited.contains(key) || fields.iter().any(|field| non_empty_str(¤t[*field]).is_some()) {
|
||||
for field in fields {
|
||||
if let Some(value) = current.get(field) { merged[*field] = value.clone(); }
|
||||
}
|
||||
preserved += usize::from(edited.contains(key));
|
||||
}
|
||||
}
|
||||
if edited.contains("dimensions") {
|
||||
preserved += 1;
|
||||
}
|
||||
if incoming["dimensions"].is_object() {
|
||||
merged["dimensions"] = merge_dimensions(¤t["dimensions"], &incoming["dimensions"],
|
||||
|axis| edited.contains("dimensions") || edited.contains(&format!("dimensions:{axis}")));
|
||||
}
|
||||
|
||||
if merged["intake"]["schema"]["version"] == 1 && merged["intake"]["templateId"] == current["intake"]["templateId"] {
|
||||
for (field, value) in current["intake"]["productValues"].as_object().into_iter().flatten() {
|
||||
merged["intake"]["productValues"][field] = value.clone();
|
||||
preserved += usize::from(edited.contains(&format!("intake-product:{field}")));
|
||||
}
|
||||
for (code, row) in current["intake"]["barcodeValues"].as_object().into_iter().flatten() {
|
||||
for (field, value) in row.as_object().into_iter().flatten() {
|
||||
merged["intake"]["barcodeValues"][code][field] = value.clone();
|
||||
preserved += usize::from(edited.contains(&format!("intake-barcode:{code}:{field}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
(merged, preserved)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn merge_platform_barcode_cards(current: &Value, brief: &mut Value, edited: &HashSet<String>) {
|
||||
if let Some(fields) = brief.as_object_mut() { fields.remove("barcodeEntries"); }
|
||||
wizard::ensure_default_barcode(brief);
|
||||
let mut old = current.clone();
|
||||
wizard::ensure_default_barcode(&mut old);
|
||||
let mut rows = old["barcodeEntries"].as_array().cloned().unwrap_or_default();
|
||||
if current["barcodeEntries"].is_null() { rows.retain(|row| non_empty_str(&row["barcode"]).is_some()); }
|
||||
for incoming in brief["barcodeEntries"].as_array().into_iter().flatten() {
|
||||
let Some(code) = non_empty_str(&incoming["barcode"]) else { continue; };
|
||||
if let Some(row) = rows.iter_mut().find(|row| row["barcode"] == code) {
|
||||
let id = row["id"].as_str().unwrap_or("").to_owned();
|
||||
row["dimensions"] = merge_dimensions(&row["dimensions"], &incoming["dimensions"],
|
||||
|axis| edited.contains(&format!("barcode-card:{id}:dimensions.{axis}")));
|
||||
for field in ["material", "boardType", "colorName", "specId", "specName", "spec", "skuName", "variantName"] {
|
||||
if non_empty_str(&row[field]).is_none() && !edited.contains(&format!("barcode-card:{id}:{field}"))
|
||||
&& let Some(value) = incoming.get(field)
|
||||
{
|
||||
row[field] = value.clone();
|
||||
}
|
||||
}
|
||||
if row["variantId"].is_null() { row["variantId"] = incoming["variantId"].clone(); }
|
||||
} else if !edited.contains(&format!("removed-barcode:{code}")) {
|
||||
rows.push(incoming.clone());
|
||||
}
|
||||
}
|
||||
if rows.is_empty() && current["barcodeEntries"].is_null() {
|
||||
return;
|
||||
}
|
||||
let mut variants = brief_variants(brief);
|
||||
for variant in brief_variants(current) {
|
||||
if let Some(fresh) = variants.iter_mut().find(|row| row["id"] == variant["id"]) {
|
||||
if variant["images"].as_array().is_some_and(|images| !images.is_empty()) {
|
||||
fresh["images"] = variant["images"].clone();
|
||||
}
|
||||
} else if rows.iter().any(|row| row["variantId"] == variant["id"]) {
|
||||
variants.push(variant);
|
||||
}
|
||||
}
|
||||
set_brief_variants(brief, variants);
|
||||
let dimensions = brief["dimensions"].clone();
|
||||
write_legacy_barcode_fields(brief, &mut rows, &Value::Null);
|
||||
brief["dimensions"] = dimensions;
|
||||
brief["barcodeEntries"] = json!(rows);
|
||||
update_detail_barcode(brief);
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn canvas_entry_missing(brief: &Value, template: &Value) -> Vec<&'static str> {
|
||||
let filled = |field: &str| brief[field].as_str().is_some_and(|value| !value.trim().is_empty());
|
||||
[
|
||||
(filled("brandId"), "品牌"),
|
||||
(filled("categoryId"), "品类"),
|
||||
(template_identity(template), "模板"),
|
||||
(filled("name"), "产品名称"),
|
||||
(has_selected_product_image(brief), "产品图"),
|
||||
(project_barcodes(brief).next().is_none() || filled(spu_field(brief)), "SPU 型号"),
|
||||
(project_barcodes(brief).nth(1).is_none() ||
|
||||
brief["detailBarcode"].as_str().is_some_and(|selected| project_barcodes(brief).any(|code| code == selected)), "详情页出图条码"),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(present, label)| (!present).then_some(label))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@ -0,0 +1,643 @@
|
||||
use super::super::{Duration, Instant, PhotocraftApp, Request, Tokens, Ui, Value, Workspace, json, stitch_kit, stitch_state::Tone, stitch_ui};
|
||||
use super::super::agent_panel::rect_value;
|
||||
use super::super::creation_reads::wizard::{self, CreationStage, WizardFooterOutcome, WizardFooterState};
|
||||
use super::{PICKER_HEIGHT, PICKER_ROW_HEIGHT};
|
||||
use super::barcode::project_barcodes;
|
||||
use super::brief::{ReadinessItem, brief_readiness, brief_variants, canvas_entry_missing, normalized_color_groups, selected_template, variant_identity};
|
||||
use super::form_widgets_ui::{edit_named, picker_height, picker_row, picker_toggle_row};
|
||||
use super::project::remember_delivery_dir;
|
||||
use super::reducers::listing_status_text;
|
||||
use super::review_hints::{ReviewHintItem, parse_review_hints};
|
||||
use crate::theme::agent_scale::{Type, radius, space};
|
||||
use egui::vec2;
|
||||
|
||||
pub(in crate::jiansun) fn format_upload_bytes(bytes: u64) -> String {
|
||||
const MB: f64 = 1024.0 * 1024.0;
|
||||
if bytes >= 1024 * 1024 {
|
||||
format!("{:.1} MB", bytes as f64 / MB)
|
||||
} else if bytes >= 1024 {
|
||||
format!("{:.0} KB", bytes as f64 / 1024.0)
|
||||
} else {
|
||||
format!("{bytes} B")
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn format_eta_seconds(seconds: u64) -> String {
|
||||
if seconds >= 60 {
|
||||
let mins = seconds / 60;
|
||||
let secs = seconds % 60;
|
||||
format!("预计剩余 {mins} 分 {secs:02} 秒")
|
||||
} else {
|
||||
format!("预计剩余 {seconds} 秒")
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn upload_progress_summary(progress: &Value) -> (f32, String, String) {
|
||||
let uploaded = progress["uploadedBytes"].as_u64().unwrap_or(0);
|
||||
let total = progress["totalBytes"].as_u64().unwrap_or(0);
|
||||
let completed_chunks = progress["completedChunks"].as_u64().unwrap_or(0);
|
||||
let total_chunks = progress["totalChunks"].as_u64().unwrap_or(0);
|
||||
let file_index = progress["fileIndex"].as_u64().unwrap_or(0) + 1;
|
||||
let total_files = progress["totalFiles"].as_u64().unwrap_or(0);
|
||||
let file_name = progress["fileName"].as_str().unwrap_or("");
|
||||
let stage = match progress["stage"].as_str() {
|
||||
Some("merging") => "正在合并文件",
|
||||
Some("submitting") => "正在提交素材库",
|
||||
_ => "正在上传成品",
|
||||
};
|
||||
let fraction = if total > 0 {
|
||||
(uploaded as f32 / total as f32).clamp(0.0, 1.0)
|
||||
} else if total_chunks > 0 {
|
||||
(completed_chunks as f32 / total_chunks as f32).clamp(0.0, 1.0)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let percent = (fraction * 100.0).round() as u32;
|
||||
let eta = progress["etaSeconds"]
|
||||
.as_u64()
|
||||
.map(format_eta_seconds)
|
||||
.unwrap_or_else(|| "正在测算速度".to_owned());
|
||||
let headline = if total_files > 0 {
|
||||
format!("{stage} · {percent}%(第 {file_index}/{total_files} 个 · {eta})")
|
||||
} else {
|
||||
format!("{stage} · {percent}%({eta})")
|
||||
};
|
||||
let detail = if total > 0 && total_chunks > 0 {
|
||||
format!(
|
||||
"{} / {} · 分片 {completed_chunks}/{total_chunks}{}",
|
||||
format_upload_bytes(uploaded),
|
||||
format_upload_bytes(total),
|
||||
if file_name.is_empty() { String::new() } else { format!(" · {file_name}") }
|
||||
)
|
||||
} else {
|
||||
file_name.to_owned()
|
||||
};
|
||||
(fraction, headline, detail)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn paint_upload_progress_bar(ui: &mut Ui, progress: &Value) {
|
||||
let (fraction, headline, detail) = upload_progress_summary(progress);
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
stitch_ui::status_label(ui, &headline, stitch_ui::StatusTone::Neutral);
|
||||
let width = ui.available_width().clamp(140.0, 340.0);
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(width, 6.0), egui::Sense::hover());
|
||||
let painter = ui.painter();
|
||||
painter.rect_filled(rect, 3.0, t.field_border);
|
||||
if fraction > 0.0 {
|
||||
let mut fill = rect;
|
||||
fill.set_width((rect.width() * fraction).max(6.0).min(rect.width()));
|
||||
painter.rect_filled(fill, 3.0, t.accent);
|
||||
}
|
||||
if !detail.is_empty() {
|
||||
stitch_kit::caption(ui, &detail);
|
||||
}
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn delivery_controls(&mut self, app: &PhotocraftApp, ui: &mut Ui) {
|
||||
let idle = self.busy.is_none() && self.saving.is_none() && !self.project_operation_pending();
|
||||
let delivered = self.project_context["materialDelivery"]["materialId"].is_string()
|
||||
&& self.project_context["status"] == "completed";
|
||||
let uploading = self.busy.as_deref() == Some("project-sync");
|
||||
let (label, role) = if delivered {
|
||||
("上架状态", stitch_ui::ButtonRole::Secondary)
|
||||
} else if uploading {
|
||||
("上传中…", stitch_ui::ButtonRole::Secondary)
|
||||
} else {
|
||||
("完结", stitch_ui::ButtonRole::Primary)
|
||||
};
|
||||
let button = stitch_ui::action_button(ui, label, role, delivered || uploading || (idle && !self.unknown && !self.creation_dirty));
|
||||
self.navigation_geometry["delivery"] = rect_value(button.rect);
|
||||
let finish = button.clicked();
|
||||
if finish {
|
||||
self.sync_confirm = true;
|
||||
self.delivery_completion = false;
|
||||
self.listing_read_at = None;
|
||||
self.listing_read_error = None;
|
||||
}
|
||||
if uploading && !self.sync_confirm {
|
||||
if let Some(progress) = &self.delivery_upload_progress {
|
||||
paint_upload_progress_bar(ui, progress);
|
||||
} else {
|
||||
stitch_ui::status_label(ui, "正在准备上传成品…", stitch_ui::StatusTone::Neutral);
|
||||
}
|
||||
}
|
||||
if self.sync_confirm && self.project_context["cloudLink"]["source"] == "desktop"
|
||||
&& let Some(doc) = app.session.active().map(|state| state.doc.id.0)
|
||||
{
|
||||
let now = Instant::now();
|
||||
if self.listing_read_at.is_none_or(|(last_doc, next)| last_doc != doc || now >= next) {
|
||||
self.listing_read_at = Some((doc, now + Duration::from_secs(15)));
|
||||
if self.tx.send(Request::Action("delivery-status".into(), json!({"doc":doc}))).is_err() {
|
||||
self.listing_read_error = Some("本机服务已停止,请重启后查看".into());
|
||||
}
|
||||
}
|
||||
ui.ctx().request_repaint_after(Duration::from_secs(15));
|
||||
}
|
||||
let receipt = &self.project_context["materialDelivery"];
|
||||
let completion_receipt = self.delivery_completion && receipt["materialId"].is_string();
|
||||
let confirming = !delivered && !completion_receipt;
|
||||
let title = if completion_receipt {
|
||||
"成品已提交素材库"
|
||||
} else if delivered {
|
||||
"上架状态"
|
||||
} else {
|
||||
"完结项目"
|
||||
};
|
||||
let mut jump_target: Option<ReviewHintItem> = None;
|
||||
let review_hints = self.collect_delivery_review_hints(ui);
|
||||
let closed = stitch_ui::dialog(ui, egui::Id::unique("xiaoyi-finish-project"), title,
|
||||
self.sync_confirm, self.reduce_motion, 380.0, |ui| {
|
||||
if uploading {
|
||||
if let Some(progress) = &self.delivery_upload_progress {
|
||||
paint_upload_progress_bar(ui, progress);
|
||||
} else {
|
||||
stitch_ui::status_label(ui, "正在准备上传成品…", stitch_ui::StatusTone::Neutral);
|
||||
}
|
||||
ui.add_space(space::XS);
|
||||
} else if confirming {
|
||||
ui.label("将已完成的详情、主图和 SKU 成品提交到素材库?");
|
||||
}
|
||||
let barcodes: Vec<_> = project_barcodes(&self.creation_brief).collect();
|
||||
let color_groups = normalized_color_groups(&self.creation_brief);
|
||||
if !barcodes.is_empty() || !color_groups.is_empty() {
|
||||
let sku_summary = if !color_groups.is_empty() {
|
||||
format!(
|
||||
"SKU 按 <条码>.jpg 命名({} 个花色 · {} 个条码),多分辨率与同条码多图将自动按子目录隔离。",
|
||||
color_groups.len(),
|
||||
barcodes.len()
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"SKU 按 <条码>.jpg 命名({} 个条码),多分辨率与同条码多图将自动按子目录隔离。",
|
||||
barcodes.len()
|
||||
)
|
||||
};
|
||||
stitch_kit::caption(ui, &sku_summary);
|
||||
}
|
||||
if !review_hints.is_empty() {
|
||||
ui.add_space(space::XS);
|
||||
stitch_ui::status_label(
|
||||
ui,
|
||||
&format!("{} 项人工核对提示(不阻断完结)", review_hints.len()),
|
||||
stitch_ui::StatusTone::Warning,
|
||||
);
|
||||
egui::CollapsingHeader::new("查看人工核对清单").default_open(true).show(ui, |ui| {
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("xiaoyi-review-hints-scroll")
|
||||
.max_height(140.0)
|
||||
.show(ui, |ui| {
|
||||
for hint in &review_hints {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(&hint.message);
|
||||
if hint.has_target()
|
||||
&& stitch_ui::action_button(ui, "去核对", stitch_ui::ButtonRole::Quiet, true).clicked()
|
||||
{
|
||||
jump_target = Some(hint.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
let receipt = &self.project_context["materialDelivery"];
|
||||
if let Some(id) = receipt["materialId"].as_str() {
|
||||
let (text, tone) = listing_status_text(receipt);
|
||||
if receipt["state"].is_string() || self.listing_read_error.is_none() {
|
||||
stitch_ui::status_label(ui, text, tone);
|
||||
}
|
||||
if let Some(message) = receipt["listingStatus"]["message"].as_str()
|
||||
&& receipt["listingStatus"]["state"] == "failed" && receipt["state"] != "removed"
|
||||
{
|
||||
ui.label(message);
|
||||
}
|
||||
ui.label(format!("素材 ID {id}"));
|
||||
if let Some(listing_id) = receipt["listingStatus"]["listingId"].as_str()
|
||||
&& receipt["listingStatus"]["state"] == "listed" && receipt["state"] != "removed"
|
||||
{
|
||||
ui.label(format!("上架编号 {listing_id}"));
|
||||
}
|
||||
}
|
||||
if let Some(error) = &self.listing_read_error {
|
||||
stitch_ui::status_label(ui, "上架状态刷新失败", stitch_ui::StatusTone::Warning)
|
||||
.on_hover_text(error);
|
||||
}
|
||||
if let Some(error) = &self.finished_web_error
|
||||
&& !confirming
|
||||
{
|
||||
stitch_ui::status_label(ui, error, stitch_ui::StatusTone::Error);
|
||||
}
|
||||
let target = receipt["materialId"].as_str().filter(|_| !confirming && receipt["state"] != "removed")
|
||||
.zip(app.session.active().map(|state| state.doc.id.0))
|
||||
.map(|(material, doc)| json!({"materialId":material, "doc":doc}));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if let Some(target) = target {
|
||||
let label = if self.finished_web_pending { "正在打开…" } else { "打开成品上架工作台" };
|
||||
if stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Primary, !self.finished_web_pending).clicked() {
|
||||
self.finished_web_error = None;
|
||||
match self.tx.send(Request::Action("finished-web-open".into(), target)) {
|
||||
Ok(()) => self.finished_web_pending = true,
|
||||
Err(_) => self.finished_web_error = Some("本机服务已停止,请重启后重试".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
let dismiss = if confirming { "取消" } else { "关闭" };
|
||||
if stitch_ui::action_button(ui, dismiss, stitch_ui::ButtonRole::Secondary, true).clicked() {
|
||||
self.sync_confirm = false;
|
||||
}
|
||||
if confirming && stitch_ui::action_button(ui, "完结并提交", stitch_ui::ButtonRole::Primary, idle).clicked() {
|
||||
self.sync_confirm = false;
|
||||
self.sync_action(app, "project-sync", json!({"status":"completed"}));
|
||||
}
|
||||
});
|
||||
});
|
||||
if closed { self.sync_confirm = false; }
|
||||
if let Some(target) = jump_target {
|
||||
self.jump_to_review_hint(app, &target);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn collect_delivery_review_hints(&self, ui: &Ui) -> Vec<ReviewHintItem> {
|
||||
let mut hints = Vec::new();
|
||||
for source in [
|
||||
&self.project_context["materialDelivery"]["reviewHints"],
|
||||
&self.project_context["delivery"]["reviewHints"],
|
||||
&self.project_context["reviewHints"],
|
||||
&self.creation["reviewHints"],
|
||||
] {
|
||||
parse_review_hints(source, &mut hints);
|
||||
}
|
||||
if hints.is_empty() {
|
||||
let manifest_dir = self.project_context["materialDelivery"]["path"]
|
||||
.as_str()
|
||||
.or(self.creation_delivery_dir.as_deref())
|
||||
.map(str::trim)
|
||||
.filter(|path| !path.is_empty());
|
||||
if let Some(dir) = manifest_dir {
|
||||
let cache_id = egui::Id::unique(("xiaoyi-delivery-review-hints", dir));
|
||||
let cached = ui.ctx().data_mut(|data| data.get_temp::<Vec<ReviewHintItem>>(cache_id));
|
||||
if let Some(cached) = cached {
|
||||
return cached;
|
||||
}
|
||||
let manifest_path = std::path::Path::new(dir).join("交付清单.json");
|
||||
if let Ok(raw) = std::fs::read_to_string(&manifest_path)
|
||||
&& let Ok(manifest) = serde_json::from_str::<Value>(&raw)
|
||||
{
|
||||
parse_review_hints(&manifest["reviewHints"], &mut hints);
|
||||
}
|
||||
ui.ctx().data_mut(|data| data.insert_temp(cache_id, hints.clone()));
|
||||
}
|
||||
}
|
||||
hints
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn brief_footer_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, barcode_pending: bool) {
|
||||
let template = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]);
|
||||
let readiness = brief_readiness(&self.creation_brief, &template);
|
||||
let missing_items: Vec<&ReadinessItem> = readiness.iter().filter(|item| !item.ready).collect();
|
||||
let missing = canvas_entry_missing(&self.creation_brief, &template);
|
||||
let new_project = self.template_workflow["canvasFirst"] != true;
|
||||
let chosen_pending = template.is_null() && self.creation_reads.resource_set["id"].is_string();
|
||||
let scoped_pending = self.scoped_production_pending();
|
||||
let setup_warning = new_project.then(|| self.brief_setup_warning()).flatten();
|
||||
|
||||
let blocked = if self.unknown {
|
||||
Some(if scoped_pending { "可继续制作其余图位。" } else { "请先核查原请求,再进入模板画布。" }.to_owned())
|
||||
} else if self.busy.is_some() {
|
||||
Some("请等待当前操作完成。".to_owned())
|
||||
} else if barcode_pending {
|
||||
Some("请确认正在编辑的条码。".to_owned())
|
||||
} else if missing == ["模板"] && chosen_pending {
|
||||
if self.creation_catalog_loading("resource-set") || self.creation_catalog_loading("resource-component") {
|
||||
Some("正在核对模板资料,请稍候。".to_owned())
|
||||
} else if self.creation_reads.resource_component.is_empty()
|
||||
&& self.creation_catalog.get("resource-set").is_some_and(|parts| parts.len() > 1)
|
||||
{
|
||||
Some("请选择要使用的模板组件。".to_owned())
|
||||
} else {
|
||||
Some("所选模板暂不可用,请查看模板区的提示。".to_owned())
|
||||
}
|
||||
} else if !missing_items.is_empty() {
|
||||
let names: Vec<&str> = missing_items.iter().map(|i| i.label.as_str()).collect();
|
||||
Some(format!("待补齐:{}", names.join("、")))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Compact single-row footer when in 3-stage wizard mode
|
||||
let mut clicked_missing: Option<(String, String)> = None;
|
||||
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() && 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));
|
||||
Some(ui.data(|data| data.get_temp::<bool>(id)).unwrap_or(false))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if self.creation_reads.wizard_stage.is_some() {
|
||||
self.reference_drop_warning_ui(ui);
|
||||
let resume = self.has_production_stages() || self.has_paused_production();
|
||||
let mut open_settings = false;
|
||||
let mut recorded_geometries: Vec<(String, egui::Rect)> = Vec::new();
|
||||
let mut button_geometries: Vec<(WizardFooterOutcome, egui::Rect)> = Vec::new();
|
||||
let autosave_info = if self.creation_reads.staged_new_project {
|
||||
("草稿暂存中", Tone::Quiet)
|
||||
} else if self.busy.as_deref() == Some("creation-save") {
|
||||
("保存中…", Tone::Quiet)
|
||||
} else if self.creation_dirty {
|
||||
("有未保存修改 · 将自动保存", Tone::Warning)
|
||||
} else {
|
||||
("已自动保存", Tone::Success)
|
||||
};
|
||||
let key_saved = self.key_saved;
|
||||
let action = wizard::wizard_footer_ui_with_status(
|
||||
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,
|
||||
|ui| {
|
||||
let hint_row = ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = space::XS;
|
||||
if !missing_items.is_empty() {
|
||||
stitch_kit::label(ui, "待补齐:", Type::Meta, Tone::Warning);
|
||||
for item in &missing_items {
|
||||
let chip = stitch_ui::action_button(ui, &item.label, stitch_ui::ButtonRole::Quiet, true)
|
||||
.on_hover_text(&item.message);
|
||||
recorded_geometries.push((format!("readiness-{}", item.field_key), chip.rect));
|
||||
if chip.clicked() {
|
||||
clicked_missing = Some((item.field_key.clone(), item.message.clone()));
|
||||
}
|
||||
}
|
||||
} else if let Some(msg) = blocked.as_deref() {
|
||||
stitch_ui::status_label(ui, msg, stitch_ui::StatusTone::Warning);
|
||||
} else {
|
||||
stitch_kit::label(ui, autosave_info.0, Type::Meta, autosave_info.1);
|
||||
}
|
||||
if let Some((message, chip, action)) = setup_warning {
|
||||
stitch_ui::status_chip(ui, chip, stitch_ui::StatusTone::Warning).on_hover_text(message);
|
||||
let configure = stitch_ui::action_button(ui, action, stitch_ui::ButtonRole::Quiet, true);
|
||||
recorded_geometries.push((if key_saved { "select-model" } else { "configure-personal-key" }.to_owned(), configure.rect));
|
||||
if configure.clicked() {
|
||||
open_settings = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
recorded_geometries.push(("entry-hint".to_owned(), hint_row.response.rect));
|
||||
},
|
||||
|action, response| {
|
||||
button_geometries.push((action, response.rect));
|
||||
},
|
||||
);
|
||||
for (k, rect) in recorded_geometries {
|
||||
self.control_geometry(&k, rect);
|
||||
}
|
||||
for (btn_action, rect) in button_geometries {
|
||||
match btn_action {
|
||||
WizardFooterOutcome::EnterCanvas => self.control_geometry("enter-canvas", rect),
|
||||
WizardFooterOutcome::Start => self.control_geometry(if resume { "resume-product" } else { "start-product" }, rect),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if open_settings {
|
||||
self.open_brief_setup_settings();
|
||||
}
|
||||
if let Some((key, msg)) = clicked_missing.take() {
|
||||
self.focus_brief_field(&key, &msg);
|
||||
}
|
||||
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() {
|
||||
let hint_row = ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = space::SM;
|
||||
if !missing_items.is_empty() {
|
||||
stitch_kit::label(ui, "待补齐:", Type::Meta, Tone::Warning);
|
||||
for item in &missing_items {
|
||||
let chip = stitch_ui::action_button(ui, &item.label, stitch_ui::ButtonRole::Quiet, true)
|
||||
.on_hover_text(&item.message);
|
||||
self.control_geometry(&format!("readiness-{}", item.field_key), chip.rect);
|
||||
if chip.clicked() {
|
||||
clicked_missing = Some((item.field_key.clone(), item.message.clone()));
|
||||
}
|
||||
}
|
||||
} else if let Some(msg) = blocked.as_deref() {
|
||||
stitch_ui::status_label(ui, msg, stitch_ui::StatusTone::Warning);
|
||||
}
|
||||
if let Some((message, chip, action)) = setup_warning {
|
||||
stitch_ui::status_chip(ui, chip, stitch_ui::StatusTone::Warning).on_hover_text(message);
|
||||
let configure = stitch_ui::action_button(ui, action, stitch_ui::ButtonRole::Secondary, true);
|
||||
self.control_geometry(if self.key_saved { "select-model" } else { "configure-personal-key" }, configure.rect);
|
||||
if configure.clicked() {
|
||||
self.open_brief_setup_settings();
|
||||
}
|
||||
}
|
||||
});
|
||||
self.control_geometry("entry-hint", hint_row.response.rect);
|
||||
if let Some((key, msg)) = clicked_missing {
|
||||
self.focus_brief_field(&key, &msg);
|
||||
}
|
||||
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);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn brief_enter_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, template: &Value, production_ready: bool, canvas_ready: bool, refinement: Option<bool>) {
|
||||
let whole_allowed = self.template_workflow["canvasFirst"] != true;
|
||||
// Right-to-left parent places Primary on the far right, Secondary beside it.
|
||||
let generate = whole_allowed && {
|
||||
let button = stitch_ui::action_button(ui, "确认并开始制作", stitch_ui::ButtonRole::Primary, production_ready);
|
||||
self.control_geometry("generate-product", button.rect);
|
||||
button.clicked()
|
||||
};
|
||||
let enter = stitch_ui::action_button(
|
||||
ui,
|
||||
"进入模板画布",
|
||||
if whole_allowed { stitch_ui::ButtonRole::Secondary } else { stitch_ui::ButtonRole::Primary },
|
||||
canvas_ready,
|
||||
);
|
||||
self.control_geometry("enter-canvas", enter.rect);
|
||||
if enter.clicked() || generate {
|
||||
self.enter_creation_canvas(app, template, generate, refinement);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn sku_colors_bar_ui(&mut self, ui: &mut Ui, width: f32, scope: egui::Id) {
|
||||
let mut variants = brief_variants(&self.creation_brief);
|
||||
let draft_id = scope.with("manual-sku-color");
|
||||
let mut draft = ui.data(|data| data.get_temp::<Value>(draft_id)).unwrap_or(Value::Null);
|
||||
let add_width = 76.0;
|
||||
let gap = space::SM;
|
||||
let add = ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = gap;
|
||||
let entry = ui.scope(|ui| {
|
||||
edit_named(ui, draft_id, &mut draft, (width - add_width - gap).max(120.0), false, "输入花色名称", "新增花色")
|
||||
});
|
||||
self.control_geometry("sku-color-input", entry.response.rect);
|
||||
let color = draft.as_str().unwrap_or("").trim();
|
||||
let duplicate = variants.iter().any(|row| row["colorName"].as_str().is_some_and(|name| name.eq_ignore_ascii_case(color)));
|
||||
let enabled = !color.is_empty() && color.chars().count() <= 120 && !duplicate && variants.len() < 64;
|
||||
let button = stitch_ui::action_button(ui, "添加颜色", stitch_ui::ButtonRole::Secondary, enabled)
|
||||
.on_disabled_hover_text(if duplicate { "此花色已添加" } else { "请输入颜色名称,最多添加 64 个花色" });
|
||||
self.control_geometry("sku-color-add", button.rect);
|
||||
button.clicked()
|
||||
}).inner;
|
||||
if add {
|
||||
let color = draft.as_str().unwrap_or("").trim();
|
||||
variants.push(json!({"id":variant_identity(&format!("manual-sku:{color}")),"name":color,"colorName":color,"colorMaterialId":"","images":[]}));
|
||||
self.save_sku_colors(variants.clone());
|
||||
draft = Value::Null;
|
||||
}
|
||||
ui.data_mut(|data| data.insert_temp(draft_id, draft));
|
||||
|
||||
let mut remove = None;
|
||||
if !variants.is_empty() {
|
||||
ui.add_space(space::XS);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for variant in &variants {
|
||||
let name = variant["name"].as_str().filter(|name| !name.is_empty()).unwrap_or("原项目花色");
|
||||
let removable = self.sku_color_removable(variant);
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
egui::Frame::NONE
|
||||
.fill(t.dock)
|
||||
.stroke(egui::Stroke::new(1.0, t.card_border))
|
||||
.corner_radius(egui::CornerRadius::same(radius::ROW as u8))
|
||||
.inner_margin(egui::Margin::symmetric(8, 3))
|
||||
.show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let font = Type::Meta.font_id();
|
||||
let measured = ui.painter().layout_no_wrap(name.into(), font.clone(), t.text).size().x;
|
||||
ui.add_sized(
|
||||
vec2(measured.min((width - 42.0).max(20.0)), 22.0),
|
||||
egui::Label::new(egui::RichText::new(name).font(font)).truncate(),
|
||||
)
|
||||
.on_hover_text(name);
|
||||
if removable && stitch_ui::icon_button(ui, "x", 20.0, false, &format!("移除 {name}")).clicked() {
|
||||
remove = variant["id"].as_str().map(str::to_owned);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(remove) = remove {
|
||||
variants.retain(|row| row["id"] != remove);
|
||||
self.save_sku_colors(variants);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn sku_output_picker(&mut self, ui: &mut Ui, width: f32, component: &str, variants: &[Value]) {
|
||||
let mut selected = self.creation_brief["outputVariantIds"][component].as_array().cloned().unwrap_or_default();
|
||||
let summary = match selected.as_slice() {
|
||||
[] if variants.is_empty() => "请先添加花色".into(),
|
||||
[] => format!("全部 {} 个花色", variants.len()),
|
||||
[id] => variants.iter().find(|row| row["id"] == *id).and_then(|row| row["name"].as_str()).unwrap_or("已选 1 个颜色").to_owned(),
|
||||
ids => format!("已选 {} 个花色", ids.len()),
|
||||
};
|
||||
let picker_id = format!("sku-output-{component}");
|
||||
let mut changed = false;
|
||||
let menu_height = ((variants.len() + 1) as f32 * (PICKER_ROW_HEIGHT + ui.spacing().item_spacing.y)).min(PICKER_HEIGHT);
|
||||
let result = ui.add_enabled_ui(!variants.is_empty(), |ui| picker_height(ui, &picker_id, width, menu_height, &summary, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| {
|
||||
if picker_row(ui, selected.is_empty(), "全部 SKU 颜色", true).clicked() {
|
||||
selected.clear();
|
||||
changed = true;
|
||||
ui.close();
|
||||
}
|
||||
for row in variants {
|
||||
let name = row["name"].as_str().filter(|name| !name.is_empty()).unwrap_or("原项目花色");
|
||||
let index = selected.iter().position(|id| *id == row["id"]);
|
||||
let response = picker_toggle_row(ui, index.is_some(), name, index.is_none() || selected.len() > 1)
|
||||
.on_disabled_hover_text("至少保留一个颜色,或选择全部 SKU 颜色");
|
||||
self.control_geometry(&format!("{picker_id}-{}", row["id"].as_str().unwrap_or("")), response.rect);
|
||||
if response.clicked() {
|
||||
if let Some(index) = index { selected.remove(index); }
|
||||
else { selected.push(row["id"].clone()); }
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
})).inner;
|
||||
self.control_geometry(&picker_id, result.response.rect);
|
||||
if changed {
|
||||
if !self.creation_brief["outputVariantIds"].is_object() {
|
||||
self.creation_brief["outputVariantIds"] = json!({});
|
||||
}
|
||||
if let Some(outputs) = self.creation_brief["outputVariantIds"].as_object_mut() {
|
||||
if selected.is_empty() { outputs.remove(component); }
|
||||
else { outputs.insert(component.to_owned(), json!(selected)); }
|
||||
}
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn delivery_directory_control(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, editable: bool) {
|
||||
stitch_kit::label(ui, "成品保存位置", Type::Meta, Tone::Quiet);
|
||||
let path = self.creation_delivery_dir.as_deref().unwrap_or("未选择(默认仅保存到项目内)");
|
||||
ui.add(egui::Label::new(egui::RichText::new(path).font(Type::Meta.font_id())).wrap()).on_hover_text(path);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let choose = stitch_ui::action_button(ui, "选择文件夹", stitch_ui::ButtonRole::Secondary, editable);
|
||||
self.control_geometry("choose-delivery-directory", choose.rect);
|
||||
if choose.clicked() {
|
||||
let initial_dir = self.creation_delivery_dir.clone();
|
||||
let doc = self.creation_doc;
|
||||
let identity = self.local_identity("");
|
||||
if let Err(error) = app.ask_file(crate::FileDialogRequest::Folder { initial_dir }, move |app, answer| {
|
||||
let path = match answer {
|
||||
crate::FileDialogAnswer::FolderTo(path) => path,
|
||||
crate::FileDialogAnswer::Unavailable(error) => return Err(error),
|
||||
_ => return Ok(Value::Null),
|
||||
};
|
||||
let w = app.jiansun.as_mut().filter(|w| w.creation_doc == doc && w.local_identity("") == identity)
|
||||
.ok_or("账号或项目已切换,未修改保存目录")?;
|
||||
if !std::path::Path::new(&path).is_absolute() {
|
||||
return Err("请选择绝对路径的成品目录".into());
|
||||
}
|
||||
if app.session.active().and_then(|state| state.path.as_deref())
|
||||
.map(std::path::Path::new).and_then(std::path::Path::parent)
|
||||
.is_some_and(|draft| std::path::Path::new(&path).starts_with(draft) && draft.ends_with(
|
||||
w.open_projects.get(&doc.unwrap_or_default()).and_then(|id| id.rsplit('|').next()).unwrap_or_default()))
|
||||
{
|
||||
return Err("请选择项目草稿目录以外的位置".into());
|
||||
}
|
||||
w.creation_delivery_dir = Some(path.clone());
|
||||
w.creation_dirty = true;
|
||||
remember_delivery_dir(app, &path);
|
||||
Ok(Value::Null)
|
||||
}) {
|
||||
self.error = error;
|
||||
}
|
||||
}
|
||||
let clear = stitch_ui::action_button(ui, "清除", stitch_ui::ButtonRole::Quiet, editable && self.creation_delivery_dir.is_some());
|
||||
self.control_geometry("clear-delivery-directory", clear.rect);
|
||||
if clear.clicked() {
|
||||
self.creation_delivery_dir = None;
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,93 @@
|
||||
use super::super::{Ui, Workspace, json, stitch_kit, stitch_state::Tone, stitch_ui};
|
||||
use super::brief::{OUTPUT_SCOPE_OPTIONS, normalized_color_groups, selected_output_scopes, sku_display_label};
|
||||
use super::form_widgets_ui::field_group;
|
||||
use crate::theme::agent_scale::{Type, control};
|
||||
use egui::vec2;
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn detail_barcode_selector_ui(&mut self, ui: &mut Ui, width: f32, scope: egui::Id, codes: &[String]) {
|
||||
let current = self.creation_brief["detailBarcode"].as_str().unwrap_or("").to_owned();
|
||||
let selected_label = if current.is_empty() {
|
||||
"请选择详情主款".to_owned()
|
||||
} else {
|
||||
sku_display_label(&self.creation_brief, ¤t)
|
||||
};
|
||||
let error = self.creation_reads.inline_errors.get("detail-barcode").cloned();
|
||||
let scroll = self.creation_reads.scroll_to_field.as_deref() == Some("detail-barcode");
|
||||
if scroll {
|
||||
self.creation_reads.scroll_to_field = None;
|
||||
}
|
||||
field_group(ui, width, "详情主款 *", |ui| {
|
||||
let picker = stitch_ui::halo_select_with_behavior(
|
||||
ui,
|
||||
scope.with("detail-barcode"),
|
||||
width,
|
||||
&selected_label,
|
||||
self.reduce_motion,
|
||||
egui::PopupCloseBehavior::CloseOnClickOutside,
|
||||
|ui| {
|
||||
egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| {
|
||||
for (index, code) in codes.iter().enumerate() {
|
||||
let display = sku_display_label(&self.creation_brief, code);
|
||||
let option = stitch_ui::select_option_sized(ui, &display, code == ¤t, true, vec2(ui.available_width(), control::STANDARD));
|
||||
self.control_geometry(&format!("detail-barcode-option-{index}"), option.rect);
|
||||
if option.clicked() {
|
||||
self.creation_brief["detailBarcode"] = json!(code);
|
||||
self.creation_reads.inline_errors.remove("detail-barcode");
|
||||
if let Some(color) = normalized_color_groups(&self.creation_brief)
|
||||
.into_iter()
|
||||
.find(|g| g.skus.iter().any(|s| s.barcode == *code))
|
||||
.map(|g| g.color_name)
|
||||
{
|
||||
self.creation_brief["colorName"] = json!(color);
|
||||
} else if self.creation_brief["source"] == "product_platform" {
|
||||
self.creation_brief["colorName"] = json!(self.creation_brief["platformFacts"]["barcodes"][code.as_str()]["colorName"].as_str().unwrap_or(""));
|
||||
}
|
||||
self.creation_dirty = true;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
if scroll {
|
||||
picker.response.scroll_to_me(Some(egui::Align::Center));
|
||||
picker.response.request_focus();
|
||||
}
|
||||
self.control_geometry("detail-barcode", picker.response.rect);
|
||||
if let Some(err) = error.as_deref() {
|
||||
stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn output_tags_ui(&mut self, ui: &mut Ui) {
|
||||
let mut scopes = selected_output_scopes(&self.creation_brief);
|
||||
let mut changed = false;
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
stitch_kit::label(ui, "输出内容", Type::Meta, Tone::Quiet);
|
||||
for (control_id, scope_key, label) in OUTPUT_SCOPE_OPTIONS {
|
||||
let selected = scopes.iter().any(|item| item == scope_key);
|
||||
let enabled = !selected || scopes.len() > 1;
|
||||
let response = stitch_ui::toggle_option(ui, label, selected, enabled)
|
||||
.on_disabled_hover_text("至少保留一项输出内容");
|
||||
self.control_geometry(control_id, response.rect);
|
||||
if response.clicked() {
|
||||
if selected {
|
||||
scopes.retain(|item| item != scope_key);
|
||||
} else {
|
||||
scopes.push(scope_key.to_owned());
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
if changed {
|
||||
self.creation_brief["outputScopes"] = json!(scopes);
|
||||
self.creation_reads.manual_edited_fields.insert("outputScopes".into());
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,437 @@
|
||||
use super::super::{PhotocraftApp, Tokens, Ui, Value, Workspace, json, stitch_kit, stitch_state::Tone, stitch_ui};
|
||||
use super::brief::{NormalizedProductSummary, brief_variants, normalized_product_summary};
|
||||
use super::form_widgets_ui::{IntakeScope, edit_named, edit_named_with_error, field_group, field_kind, intake_fields_with_errors, intake_hint, is_product_name_field, reveal_template_intake, spu_field};
|
||||
use crate::theme::agent_scale::{Type, radius, space};
|
||||
use egui::vec2;
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) 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);
|
||||
ui.add_space(space::SM);
|
||||
}
|
||||
if !self.creation_progress.is_empty() {
|
||||
stitch_ui::disclosure(ui, egui::Id::unique("creation-progress"), if self.busy.is_some() { "处理中…" } else { "最近结果" }, false, self.reduce_motion, |ui| {
|
||||
ui.label(&self.creation_progress);
|
||||
});
|
||||
ui.add_space(space::SM);
|
||||
}
|
||||
if self.unknown {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
stitch_ui::status_chip(ui, "原请求待核查", stitch_ui::StatusTone::Warning);
|
||||
if ui.add_enabled_ui(self.busy.is_none(), |ui| stitch_ui::button(ui, "核查原结果", false)).inner.clicked() {
|
||||
self.recover(app);
|
||||
}
|
||||
if self.creation["generation"]["screens"].as_object().is_some_and(|m| !m.is_empty())
|
||||
&& ui.add_enabled_ui(self.busy.is_none(), |ui| stitch_ui::button(ui, "载入已有结果", false)).inner.clicked()
|
||||
{
|
||||
self.creation_submit(app, "creation-load", json!({}));
|
||||
}
|
||||
});
|
||||
ui.add_space(space::SM);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn brief_autosave_status_ui(&self, ui: &mut Ui) {
|
||||
let (text, tone) = if self.creation_reads.staged_new_project {
|
||||
("草稿暂存中", Tone::Quiet)
|
||||
} else if self.busy.as_deref() == Some("creation-save") {
|
||||
("保存中…", Tone::Quiet)
|
||||
} else if self.creation_dirty {
|
||||
("有未保存修改 · 将自动保存", Tone::Warning)
|
||||
} else {
|
||||
("已自动保存", Tone::Success)
|
||||
};
|
||||
stitch_kit::label(ui, text, Type::Meta, tone);
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn unmatched_platform_taxonomy_chips_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, np: &NormalizedProductSummary) {
|
||||
let cur_brand = self.creation_brief["brandName"].as_str().unwrap_or("").trim();
|
||||
let cur_cat = self.creation_brief["categoryName"].as_str().unwrap_or("").trim();
|
||||
let brand_unmatched = !np.platform_brand.is_empty() && !cur_brand.eq_ignore_ascii_case(&np.platform_brand);
|
||||
let cat_unmatched = !np.platform_category.is_empty() && !cur_cat.eq_ignore_ascii_case(&np.platform_category);
|
||||
if !brand_unmatched && !cat_unmatched {
|
||||
return;
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
stitch_kit::label(ui, "平台分类参考:", Type::Meta, Tone::Quiet);
|
||||
if brand_unmatched {
|
||||
let brands = self.creation_catalog.get("brands").cloned().unwrap_or_default();
|
||||
let matched = brands.iter().find(|row| {
|
||||
row["ready"] == true
|
||||
&& row["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&np.platform_brand) || n.contains(&np.platform_brand))
|
||||
});
|
||||
let label = if matched.is_some() {
|
||||
format!("应用品牌:{}", np.platform_brand)
|
||||
} else {
|
||||
format!("平台品牌:{}(待选择对应品牌)", np.platform_brand)
|
||||
};
|
||||
let chip = stitch_ui::action_button(ui, &label, stitch_ui::ButtonRole::Quiet, true);
|
||||
self.control_geometry("platform-brand-hint", chip.rect);
|
||||
if chip.clicked() {
|
||||
if let Some(row) = matched {
|
||||
self.creation_brief["brandId"] = row["id"].clone();
|
||||
self.creation_brief["brandName"] = row["name"].clone();
|
||||
self.creation_brief["categoryId"] = json!("");
|
||||
self.creation_brief["categoryName"] = json!("");
|
||||
self.creation_brief["templateSelection"] = Value::Null;
|
||||
self.creation_catalog.remove("categories");
|
||||
self.creation_catalog.remove("templates");
|
||||
self.catalog(app, "categories", String::new());
|
||||
self.creation_reads.inline_errors.remove("brand");
|
||||
self.creation_reads.manual_edited_fields.insert("brand".into());
|
||||
self.creation_dirty = true;
|
||||
} else {
|
||||
self.focus_brief_field("brand", &format!("请在品牌列表中选择与「{}」对应的品牌", np.platform_brand));
|
||||
}
|
||||
}
|
||||
}
|
||||
if cat_unmatched {
|
||||
let brand_id = self.creation_brief["brandId"].as_str().unwrap_or("").to_owned();
|
||||
let categories = self.creation_catalog.get("categories").cloned().unwrap_or_default();
|
||||
let matched = categories.iter().find(|row| {
|
||||
row["brandId"] == brand_id
|
||||
&& row["ready"] == true
|
||||
&& row["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&np.platform_category) || n.contains(&np.platform_category))
|
||||
});
|
||||
let label = if matched.is_some() {
|
||||
format!("应用品类:{}", np.platform_category)
|
||||
} else {
|
||||
format!("平台品类:{}(待选择对应品类)", np.platform_category)
|
||||
};
|
||||
let chip = stitch_ui::action_button(ui, &label, stitch_ui::ButtonRole::Quiet, true);
|
||||
self.control_geometry("platform-category-hint", chip.rect);
|
||||
if chip.clicked() {
|
||||
if let Some(row) = matched {
|
||||
self.creation_brief["categoryId"] = row["id"].clone();
|
||||
self.creation_brief["categoryName"] = row["name"].clone();
|
||||
self.creation_brief["templateSelection"] = Value::Null;
|
||||
self.creation_catalog.remove("templates");
|
||||
self.creation_reads.inline_errors.remove("category");
|
||||
self.creation_reads.manual_edited_fields.insert("category".into());
|
||||
self.creation_dirty = true;
|
||||
} else {
|
||||
self.focus_brief_field("category", &format!("请在品类列表中选择与「{}」对应的品类", np.platform_category));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) 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 || 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 {
|
||||
let spu_w = (width * 0.36).clamp(180.0, 300.0);
|
||||
let name_w = (width - spu_w - gap).max(160.0);
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = gap;
|
||||
self.product_name_field_ui(ui, field_scope, name_w);
|
||||
self.spu_identifier_field_ui(ui, field_scope, spu_w);
|
||||
});
|
||||
} else {
|
||||
self.product_name_field_ui(ui, field_scope, width);
|
||||
if show_spu_here {
|
||||
ui.add_space(space::SM);
|
||||
self.spu_identifier_field_ui(ui, field_scope, width);
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
});
|
||||
|
||||
// Clean Platform Specs & Copy summary (materials, key attributes, selling points)
|
||||
let np = normalized_product_summary(&self.creation_brief);
|
||||
if np.has_platform_data && (!np.materials.is_empty() || !np.attributes.is_empty() || !np.summary.is_empty() || !np.selling_points.is_empty()) {
|
||||
ui.add_space(space::SM);
|
||||
self.platform_archive_summary_ui(ui, field_scope, width, &np);
|
||||
}
|
||||
|
||||
// Dynamic template productFields (with inline error + scroll-to-field support)
|
||||
let product_fields = self.creation_brief["intake"]["schema"]["productFields"].clone();
|
||||
self.poll_imported_reference_previews(app, ui.ctx());
|
||||
let image_fields = product_fields.as_array().into_iter().flatten()
|
||||
.filter(|field| field_kind(field) == "image").collect::<Vec<_>>();
|
||||
let product_fields = product_fields.as_array().into_iter().flatten()
|
||||
.filter(|field| field_kind(field) != "image" && !is_product_name_field(field)).collect::<Vec<_>>();
|
||||
reveal_template_intake(ui, field_scope.with("product-intake-reveal"),
|
||||
!product_fields.is_empty() || !image_fields.is_empty(), self.reduce_motion, |ui| {
|
||||
ui.add_space(space::MD);
|
||||
stitch_kit::label(ui, "模板商品字段", Type::Body, Tone::Active);
|
||||
ui.add_space(space::XS);
|
||||
let mut values = self.creation_brief["intake"]["productValues"].clone();
|
||||
if !values.is_object() { values = json!({}); }
|
||||
if intake_fields_with_errors(
|
||||
ui,
|
||||
field_scope.with("intake-product"),
|
||||
width,
|
||||
&product_fields,
|
||||
IntakeScope::Product,
|
||||
&mut values,
|
||||
self.reduce_motion,
|
||||
None,
|
||||
&mut self.creation_reads.inline_errors,
|
||||
&mut self.creation_reads.scroll_to_field,
|
||||
&mut self.creation_reads.manual_edited_fields,
|
||||
) {
|
||||
self.creation_brief["intake"]["productValues"] = values;
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
for field in image_fields {
|
||||
ui.add_space(space::SM);
|
||||
self.image_slot_ui(app, ui, width, field, None);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn product_name_field_ui(&mut self, ui: &mut Ui, field_scope: egui::Id, field_width: f32) {
|
||||
let error = self.creation_reads.inline_errors.get("name").cloned();
|
||||
let scroll = self.creation_reads.scroll_to_field.as_deref() == Some("name");
|
||||
if scroll {
|
||||
self.creation_reads.scroll_to_field = None;
|
||||
}
|
||||
let hint = self.creation_brief["intake"]["schema"]["productFields"].as_array().into_iter().flatten()
|
||||
.find(|field| is_product_name_field(field)).map(intake_hint).filter(|hint| !hint.is_empty())
|
||||
.unwrap_or("输入当前商品名称").to_owned();
|
||||
field_group(ui, field_width, "产品名称 *", |ui| {
|
||||
let field = ui.scope(|ui| {
|
||||
edit_named_with_error(
|
||||
ui,
|
||||
(field_scope, "name"),
|
||||
&mut self.creation_brief["name"],
|
||||
field_width,
|
||||
false,
|
||||
&hint,
|
||||
"产品名称",
|
||||
error.as_deref(),
|
||||
scroll,
|
||||
).0
|
||||
});
|
||||
if field.inner {
|
||||
self.creation_dirty = true;
|
||||
self.creation_reads.inline_errors.remove("name");
|
||||
self.creation_reads.manual_edited_fields.insert("name".into());
|
||||
}
|
||||
self.control_geometry("name", field.response.rect);
|
||||
});
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn spu_identifier_field_ui(&mut self, ui: &mut Ui, field_scope: egui::Id, field_width: f32) {
|
||||
let error = self.creation_reads.inline_errors.get("identifier").cloned();
|
||||
let scroll = self.creation_reads.scroll_to_field.as_deref() == Some("identifier");
|
||||
if scroll {
|
||||
self.creation_reads.scroll_to_field = None;
|
||||
}
|
||||
field_group(ui, field_width, "SPU 型号", |ui| {
|
||||
let field_name = spu_field(&self.creation_brief);
|
||||
let mut spu = self.creation_brief[field_name].clone();
|
||||
let field = ui.scope(|ui| {
|
||||
edit_named_with_error(
|
||||
ui,
|
||||
(field_scope, "identifier"),
|
||||
&mut spu,
|
||||
field_width,
|
||||
false,
|
||||
"输入 SPU 型号",
|
||||
"SPU 型号",
|
||||
error.as_deref(),
|
||||
scroll,
|
||||
).0
|
||||
});
|
||||
if field.inner {
|
||||
self.creation_brief[field_name] = spu;
|
||||
self.creation_dirty = true;
|
||||
self.creation_reads.inline_errors.remove("identifier");
|
||||
}
|
||||
if field_name == "deliverySpu"
|
||||
&& let Some(legacy) = self.creation_brief["identifier"].as_str().filter(|value| !value.is_empty())
|
||||
{
|
||||
stitch_kit::caption(ui, format!("原项目编号 {legacy}"));
|
||||
}
|
||||
self.control_geometry("identifier", field.response.rect);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn platform_archive_summary_ui(&mut self, ui: &mut Ui, field_scope: egui::Id, width: f32, np: &NormalizedProductSummary) {
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let frame = egui::Frame::NONE
|
||||
.fill(t.dock)
|
||||
.stroke(egui::Stroke::new(1.0, t.card_border))
|
||||
.corner_radius(egui::CornerRadius::same(radius::CONTROL as u8))
|
||||
.inner_margin(egui::Margin::same(space::MD as i8));
|
||||
frame.show(ui, |ui| {
|
||||
let inner_width = (width - 2.0 * space::MD - 2.0).max(160.0);
|
||||
ui.set_width(inner_width);
|
||||
ui.spacing_mut().item_spacing.y = space::XS;
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
stitch_kit::label(ui, "平台规格与卖点摘要", Type::Meta, Tone::Active);
|
||||
if !np.series_or_model.is_empty() {
|
||||
stitch_kit::label(ui, format!("系列:{}", np.series_or_model), Type::Meta, Tone::Quiet);
|
||||
}
|
||||
if let Some(dims) = np.dimensions_display.as_deref() {
|
||||
stitch_kit::label(ui, format!("参考尺寸:{dims}"), Type::Meta, Tone::Quiet);
|
||||
}
|
||||
});
|
||||
if !np.materials.is_empty() {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
stitch_kit::label(ui, "材质:", Type::Meta, Tone::Quiet);
|
||||
stitch_kit::label(ui, np.materials.join(" · "), Type::Meta, Tone::Active);
|
||||
});
|
||||
}
|
||||
if !np.attributes.is_empty() {
|
||||
let preview_count = 6usize;
|
||||
let cols = if inner_width >= 520.0 { 2 } else { 1 };
|
||||
let col_w = (inner_width - space::MD * (cols - 1) as f32) / cols as f32;
|
||||
egui::Grid::new(field_scope.with("platform-attrs"))
|
||||
.num_columns(cols)
|
||||
.min_col_width(col_w)
|
||||
.spacing(vec2(space::MD, space::XXS))
|
||||
.show(ui, |ui| {
|
||||
for (idx, (label, value)) in np.attributes.iter().take(preview_count).enumerate() {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.set_max_width(col_w);
|
||||
stitch_kit::label(ui, format!("{label}:"), Type::Meta, Tone::Quiet);
|
||||
stitch_kit::label(ui, value, Type::Meta, Tone::Active);
|
||||
});
|
||||
if (idx + 1) % cols == 0 {
|
||||
ui.end_row();
|
||||
}
|
||||
}
|
||||
});
|
||||
if np.attributes.len() > preview_count {
|
||||
stitch_ui::disclosure(ui, field_scope.with("platform-attrs-more"), &format!("查看全部 {} 项规格参数", np.attributes.len()), false, self.reduce_motion, |ui| {
|
||||
for (label, value) in np.attributes.iter().skip(preview_count) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
stitch_kit::label(ui, format!("{label}:"), Type::Meta, Tone::Quiet);
|
||||
stitch_kit::label(ui, value, Type::Meta, Tone::Active);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
if !np.summary.is_empty() {
|
||||
ui.add(egui::Label::new(egui::RichText::new(&np.summary).font(Type::Meta.font_id()).color(t.text_dim)).wrap());
|
||||
}
|
||||
if !np.selling_points.is_empty() {
|
||||
let shown = 3usize;
|
||||
for point in np.selling_points.iter().take(shown) {
|
||||
ui.add(egui::Label::new(egui::RichText::new(format!("· {point}")).font(Type::Meta.font_id()).color(t.text)).wrap());
|
||||
}
|
||||
if np.selling_points.len() > shown {
|
||||
stitch_ui::disclosure(ui, field_scope.with("platform-points-more"), &format!("展开其余 {} 条卖点", np.selling_points.len() - shown), false, self.reduce_motion, |ui| {
|
||||
for point in np.selling_points.iter().skip(shown) {
|
||||
ui.add(egui::Label::new(egui::RichText::new(format!("· {point}")).font(Type::Meta.font_id()).color(t.text)).wrap());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn template_and_brand_block_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) {
|
||||
let gap = space::MD;
|
||||
if width >= 520.0 {
|
||||
let column = (width - gap) / 2.0;
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = gap;
|
||||
field_group(ui, column, "品牌 *", |ui| self.brand_select(app, ui, column));
|
||||
field_group(ui, column, "品类 *", |ui| self.category_select(app, ui, column));
|
||||
});
|
||||
} else {
|
||||
field_group(ui, width, "品牌 *", |ui| self.brand_select(app, ui, width));
|
||||
ui.add_space(space::SM);
|
||||
field_group(ui, width, "品类 *", |ui| self.category_select(app, ui, width));
|
||||
}
|
||||
ui.add_space(space::SM);
|
||||
field_group(ui, width, "模板 *", |ui| self.template_select(app, ui, width));
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn advanced_export_settings_ui(&mut self, _app: &mut PhotocraftApp, ui: &mut Ui, field_scope: egui::Id, width: f32, _editable: bool) {
|
||||
let variants = brief_variants(&self.creation_brief);
|
||||
let has_variant_subsets = variants.len() > 1;
|
||||
let has_legacy_sku = self.creation_brief.get("barcodeBindings").is_none();
|
||||
if !has_variant_subsets && !has_legacy_sku {
|
||||
return;
|
||||
}
|
||||
let disclosure = stitch_ui::disclosure(ui, field_scope.with("advanced-export-settings"), "高级导出设置(选填)", false, self.reduce_motion, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = space::SM;
|
||||
if has_variant_subsets {
|
||||
ui.add_space(space::XS);
|
||||
stitch_kit::label(ui, "指定出图花色范围", Type::Meta, Tone::Quiet);
|
||||
let fields = [("detail", "详情图颜色"), ("main_images", "主图颜色")];
|
||||
let inner_w = width.min(ui.available_width()).max(120.0);
|
||||
if inner_w >= 520.0 {
|
||||
let column = (inner_w - space::MD) / 2.0;
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = space::MD;
|
||||
for (key, label) in fields {
|
||||
field_group(ui, column, label, |ui| self.sku_output_picker(ui, column, key, &variants));
|
||||
}
|
||||
});
|
||||
} else {
|
||||
for (key, label) in fields {
|
||||
field_group(ui, inner_w, label, |ui| self.sku_output_picker(ui, inner_w, key, &variants));
|
||||
}
|
||||
}
|
||||
}
|
||||
if has_legacy_sku {
|
||||
ui.add_space(space::XS);
|
||||
stitch_ui::disclosure(ui, field_scope.with("legacy-sku-bindings"), "旧项目商品编号", false, self.reduce_motion, |ui| {
|
||||
let mut list = variants.clone();
|
||||
if list.is_empty() {
|
||||
list.push(json!({"id":"default","name":"当前花色"}));
|
||||
}
|
||||
let inner_w = ui.available_width();
|
||||
for variant in list {
|
||||
let Some(id) = variant["id"].as_str() else { continue };
|
||||
let name = variant["name"].as_str().filter(|name| !name.is_empty()).unwrap_or("当前花色");
|
||||
let label = format!("{name} · SKU 编号");
|
||||
let mut binding = self.creation_brief["skuBindings"][id].clone();
|
||||
if field_group(ui, inner_w, &label, |ui| {
|
||||
edit_named(ui, field_scope.with(("delivery-skus", id)), &mut binding, inner_w, false, "多个 SKU 用逗号分隔", &label)
|
||||
}).inner {
|
||||
self.creation_brief["skuBindings"][id] = binding;
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
self.control_geometry("advanced-export-settings", disclosure.rect);
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn special_requirements_ui(&mut self, ui: &mut Ui, scope: egui::Id) {
|
||||
let width = ui.available_width();
|
||||
let group = field_group(ui, width, "制作要求与重点(选填)", |ui| {
|
||||
let (edited, resp) = edit_named_with_error(
|
||||
ui,
|
||||
(scope, "note"),
|
||||
&mut self.creation_brief["note"],
|
||||
width,
|
||||
true,
|
||||
"可补充核心卖点侧重、画面风格、禁用元素或场景偏好,无特殊要求可留空。",
|
||||
"制作要求与重点",
|
||||
None,
|
||||
false,
|
||||
);
|
||||
if edited {
|
||||
self.creation_dirty = true;
|
||||
self.creation_reads.manual_edited_fields.insert("note".into());
|
||||
}
|
||||
self.control_geometry("special-requirements-input", resp.rect);
|
||||
});
|
||||
self.control_geometry("special-requirements", group.response.rect);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,584 @@
|
||||
use super::super::{PhotocraftApp, Tokens, Ui, Value, Workspace, agent_panel::rect_value, json, stitch_kit, stitch_ui};
|
||||
use super::super::creation_reads::wizard::{CreationStage, WizardFooterOutcome};
|
||||
use super::{MATERIAL_THUMB_SIDE, PICKER_HEIGHT, PICKER_ROW_HEIGHT};
|
||||
use super::barcode::project_barcodes;
|
||||
use super::brief::non_empty_str;
|
||||
use super::intake::BARCODE_HINT;
|
||||
use super::structure_preview_ui::paint_template_structure;
|
||||
use crate::theme::agent_scale::{Type, control, space};
|
||||
use egui::vec2;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub(crate) fn creation_escape_active(app: &PhotocraftApp) -> bool {
|
||||
app.jiansun.as_ref().is_some_and(|workspace|
|
||||
workspace.creation_open && workspace.creation_step != 3 && !workspace.library && !workspace.material)
|
||||
}
|
||||
|
||||
/// Constrain the native ComboBox before its first measuring pass. Its default
|
||||
/// popup extends labels and shrinks loading content to one row, producing a
|
||||
/// different menu on first open and after the asynchronous catalogue arrives.
|
||||
pub(in crate::jiansun) fn picker<R>(ui: &mut Ui, id: &str, width: f32, selected: &str, contents: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse<Option<R>> {
|
||||
picker_height(ui, id, width, PICKER_HEIGHT, selected, egui::PopupCloseBehavior::CloseOnClick, contents)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn picker_height<R>(ui: &mut Ui, id: &str, width: f32, height: f32, selected: &str, close_behavior: egui::PopupCloseBehavior, contents: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse<Option<R>> {
|
||||
ui.scope(|ui| {
|
||||
ui.set_width(width);
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
ui.spacing_mut().interact_size.y = 34.0;
|
||||
ui.spacing_mut().button_padding = vec2(10.0, 7.0);
|
||||
let visuals = ui.visuals_mut();
|
||||
visuals.widgets.inactive.corner_radius = egui::CornerRadius::same(9);
|
||||
visuals.widgets.hovered.corner_radius = egui::CornerRadius::same(9);
|
||||
visuals.widgets.inactive.weak_bg_fill = t.field;
|
||||
visuals.widgets.inactive.bg_stroke = egui::Stroke::new(1.0, t.field_border);
|
||||
stitch_ui::halo_select_with_behavior(ui, id, width, selected, ui.style().animation_time == 0.0, close_behavior, |ui| {
|
||||
// Reserve the same scrollbar gutter before and after data arrives.
|
||||
ui.set_width(
|
||||
(width - ui.spacing().menu_margin.sum().x - ui.spacing().scroll.allocated_width() - ui.spacing().scroll.content_margin.sum().x).max(120.0),
|
||||
);
|
||||
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
|
||||
egui::ScrollArea::vertical().max_height(height).min_scrolled_height(height)
|
||||
.auto_shrink([false, true]).show(ui, contents).inner
|
||||
},
|
||||
)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn picker_row(ui: &mut Ui, selected: bool, label: &str, enabled: bool) -> egui::Response {
|
||||
// add_sized centers its child and reports the text's intrinsic width on the
|
||||
// first sizing pass. An explicit native minimum keeps the whole left-aligned
|
||||
// row the same size before and after the popup's layout cache is populated.
|
||||
let size = vec2(ui.available_width(), PICKER_ROW_HEIGHT);
|
||||
ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
// The shared option inherits wrap mode; clamp long template names to
|
||||
// the space left after the preview instead of widening the popup.
|
||||
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
|
||||
stitch_ui::select_option_sized(ui, label, selected, enabled, size)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn template_picker_row(ui: &mut Ui, selected: bool, label: &str, enabled: bool, preview: Option<&Value>) -> egui::Response {
|
||||
if let Some(preview) = preview {
|
||||
ui.horizontal(|ui| {
|
||||
let (area, thumbnail) = ui.allocate_exact_size(vec2(26.0, PICKER_ROW_HEIGHT), if enabled { egui::Sense::click() } else { egui::Sense::hover() });
|
||||
paint_template_structure(ui, preview, area.shrink(2.0));
|
||||
let thumbnail = thumbnail.on_hover_text("首屏结构示意,不含图片");
|
||||
picker_row(ui, selected, label, enabled).union(thumbnail)
|
||||
}).inner
|
||||
} else {
|
||||
picker_row(ui, selected, label, enabled)
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn picker_toggle_row(ui: &mut Ui, selected: bool, label: &str, enabled: bool) -> egui::Response {
|
||||
let size = vec2(ui.available_width(), PICKER_ROW_HEIGHT);
|
||||
ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
stitch_ui::menu_toggle_sized(ui, label, selected, enabled, size)
|
||||
}).inner
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn picker_notice(ui: &mut Ui, loading: bool, error: Option<&str>, empty: bool, empty_label: &str) -> bool {
|
||||
let mut retry = false;
|
||||
if loading {
|
||||
ui.horizontal(|ui| {
|
||||
let reduced = ui.style().animation_time == 0.0;
|
||||
stitch_ui::ai_loader(ui, egui::Id::unique("creation-catalog-loader"), true, reduced);
|
||||
ui.label("正在读取…");
|
||||
});
|
||||
} else if let Some(error) = error {
|
||||
stitch_ui::status_label(ui, "读取失败", stitch_ui::StatusTone::Error).on_hover_text(error);
|
||||
retry = stitch_ui::action_button(ui, "重新读取", stitch_ui::ButtonRole::Secondary, true).clicked();
|
||||
} else if empty {
|
||||
stitch_ui::status_label(ui, empty_label, stitch_ui::StatusTone::Neutral);
|
||||
retry = stitch_ui::action_button(ui, "重新读取", stitch_ui::ButtonRole::Secondary, true).clicked();
|
||||
}
|
||||
retry
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn preview_size(size: egui::Vec2, max: egui::Vec2) -> egui::Vec2 {
|
||||
if !size.is_finite() || size.x <= 0.0 || size.y <= 0.0 {
|
||||
return egui::Vec2::ZERO;
|
||||
}
|
||||
size * (max.x / size.x).min(max.y / size.y)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn material_thumbnail(ui: &mut Ui, texture: Option<&egui::TextureHandle>, loading: bool, failed: bool) -> egui::Response {
|
||||
let (rect, response) =
|
||||
ui.allocate_exact_size(vec2(MATERIAL_THUMB_SIDE, MATERIAL_THUMB_SIDE), if failed { egui::Sense::click() } else { egui::Sense::hover() });
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
ui.painter().rect_filled(rect, t.radius_sm, t.field);
|
||||
ui.painter().rect_stroke(rect, t.radius_sm, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);
|
||||
if let Some(texture) = texture {
|
||||
let size = preview_size(texture.size_vec2(), rect.size());
|
||||
let image_rect = egui::Align2::CENTER_CENTER.align_size_within_rect(size, rect);
|
||||
ui.painter().image(texture.id(), image_rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), egui::Color32::WHITE);
|
||||
} else if loading {
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().id_salt(response.id.with("loader")).max_rect(rect.shrink(3.0)));
|
||||
child.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
let reduced = ui.style().animation_time == 0.0;
|
||||
stitch_ui::ai_loader(&mut child, response.id.with("loader"), true, reduced);
|
||||
} else if failed {
|
||||
crate::icons::paint(ui, rect.shrink(8.0), "triangle-alert", 14.0, t.text_dim);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn edit(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &mut Value, width: f32, multiline: bool, name: &str) -> bool {
|
||||
edit_named(ui, id, value, width, multiline, "", name)
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(in crate::jiansun) struct MaterialSearchPending { query: String, changed_at: f64, pub(in crate::jiansun) pending: bool }
|
||||
|
||||
pub(in crate::jiansun) fn material_search_due(state: &mut MaterialSearchPending, query: &str, changed: bool, enter: bool, now: f64) -> bool {
|
||||
if changed {
|
||||
state.query = query.to_owned();
|
||||
state.changed_at = now;
|
||||
state.pending = true;
|
||||
}
|
||||
if enter || (state.pending && (query.is_empty() || now - state.changed_at >= 0.3)) {
|
||||
state.pending = false;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn edit_named(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &mut Value, width: f32, multiline: bool, hint: &str, name: &str) -> bool {
|
||||
edit_named_with_error(ui, id, value, width, multiline, hint, name, None, false).0
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn edit_named_with_error(
|
||||
ui: &mut Ui,
|
||||
id: impl std::hash::Hash + std::fmt::Debug,
|
||||
value: &mut Value,
|
||||
width: f32,
|
||||
multiline: bool,
|
||||
hint: &str,
|
||||
name: &str,
|
||||
error: Option<&str>,
|
||||
focus_and_scroll: bool,
|
||||
) -> (bool, egui::Response) {
|
||||
let mut text = match value {
|
||||
Value::String(text) => text.clone(),
|
||||
Value::Number(number) => number.to_string(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let hint = egui::RichText::new(hint).color(Tokens::get(ui.ctx()).agent().text_dim);
|
||||
let mut field = stitch_ui::text_input(&mut text, "", multiline).hint_text(hint);
|
||||
if multiline {
|
||||
field = field.desired_rows(3);
|
||||
}
|
||||
let response = form_editor_with_error(ui, id, field, width, name, error);
|
||||
if focus_and_scroll {
|
||||
response.scroll_to_me(Some(egui::Align::Center));
|
||||
response.request_focus();
|
||||
}
|
||||
let changed = response.changed();
|
||||
if changed { *value = json!(text); }
|
||||
(changed, response)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn form_editor_with_error(
|
||||
ui: &mut Ui,
|
||||
id: impl std::hash::Hash + std::fmt::Debug,
|
||||
field: egui::TextEdit<'_>,
|
||||
width: f32,
|
||||
name: &str,
|
||||
error: Option<&str>,
|
||||
) -> egui::Response {
|
||||
// Halo Field consumes 10pt inner margin plus its 1pt stroke on each side.
|
||||
let content_width = (width - 22.0).max(0.0);
|
||||
let editor = creation_editor_id(ui, id);
|
||||
let field = field.desired_width(content_width).id(editor).frame(egui::Frame::NONE);
|
||||
let reduced = ui.style().animation_time == 0.0;
|
||||
stitch_ui::halo_field(ui, editor.with("halo"), error, reduced, |ui| ui.add(field).accessible_name(name))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) 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::<Vec<egui::Id>>(egui::Id::unique("creation-active-editors")).push(editor));
|
||||
editor
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) 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("条码编码")
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn field_group<R>(ui: &mut Ui, width: f32, label: &str, contents: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse<R> {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(width);
|
||||
ui.spacing_mut().item_spacing.y = space::XS + space::XXS;
|
||||
ui.label(egui::RichText::new(label).font(Type::Meta.font_id()).color(Tokens::get(ui.ctx()).agent().text_dim));
|
||||
contents(ui)
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn intake_columns(width: f32) -> usize {
|
||||
if width >= 420.0 { 3 } else if width >= 152.0 { 2 } else { 1 }
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn product_intake_columns(width: f32) -> usize {
|
||||
if width >= 560.0 { 2 } else { 1 }
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn is_product_name_field(field: &Value) -> bool {
|
||||
field["type"] == "text"
|
||||
&& field["label"].as_str().is_some_and(|label| {
|
||||
matches!(label.trim().trim_end_matches(['*', '*']).trim(), "产品名称" | "产品名" | "商品名称" | "商品名")
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn intake_multiline(field: &Value) -> bool {
|
||||
field["type"] == "text" && field["multiline"].as_bool().unwrap_or_else(|| {
|
||||
matches!(field["label"].as_str().map(str::trim),
|
||||
Some("核心卖点" | "产品卖点" | "卖点描述" | "注意事项" | "产品描述" | "产品介绍" | "使用说明"))
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn intake_hint(field: &Value) -> &str {
|
||||
["placeholder", "hint", "example", "promptHint", "description", "help"].into_iter()
|
||||
.filter_map(|key| non_empty_str(&field[key]))
|
||||
.find(|hint| *hint != "按本款确认资料填写;尺寸注明单位,暂无资料可留空。")
|
||||
.unwrap_or(match field_kind(field).as_str() {
|
||||
Some("number") => "数字",
|
||||
Some("select") => "请选择",
|
||||
Some("image") => "拖放图片或点击选择",
|
||||
_ => "",
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn reveal_template_intake(ui: &mut Ui, id: egui::Id, open: bool, reduced: bool, contents: impl FnOnce(&mut Ui)) {
|
||||
let height_id = id.with("intake-height");
|
||||
stitch_ui::morph_surface(ui, id, open, reduced, |ui| {
|
||||
if open {
|
||||
contents(ui);
|
||||
let height = ui.min_rect().height();
|
||||
ui.data_mut(|data| data.insert_temp(height_id, height));
|
||||
} else if let Some(height) = ui.data(|data| data.get_temp::<f32>(height_id)) {
|
||||
// Field definitions can disappear when a template is cleared. Keep
|
||||
// the measured space while it collapses without mounting stale fields.
|
||||
ui.add_space(height);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::jiansun) enum IntakeScope {
|
||||
Product,
|
||||
Barcode,
|
||||
}
|
||||
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in crate::jiansun) fn intake_fields_with_errors(
|
||||
ui: &mut Ui,
|
||||
scope: egui::Id,
|
||||
width: f32,
|
||||
fields: &[&Value],
|
||||
kind: IntakeScope,
|
||||
values: &mut Value,
|
||||
reduced: bool,
|
||||
barcode: Option<&str>,
|
||||
inline_errors: &mut HashMap<String, String>,
|
||||
scroll_to_field: &mut Option<String>,
|
||||
manual_edited: &mut HashSet<String>,
|
||||
) -> bool {
|
||||
let (columns, gap) = match kind {
|
||||
IntakeScope::Product => (product_intake_columns(width), space::MD),
|
||||
IntakeScope::Barcode => (intake_columns(width), space::SM),
|
||||
};
|
||||
let spans_row = |field: &Value| match kind {
|
||||
IntakeScope::Product => intake_multiline(field),
|
||||
IntakeScope::Barcode => !matches!(field["type"].as_str(), Some("number" | "select" | "boolean")),
|
||||
};
|
||||
let column_width = (width - gap * (columns - 1) as f32) / columns as f32;
|
||||
let mut changed = false;
|
||||
ui.scope(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = space::MD;
|
||||
let mut remaining = fields;
|
||||
while let Some((first, _)) = remaining.split_first() {
|
||||
let full_width = spans_row(first);
|
||||
let count = if full_width { 1 } else {
|
||||
remaining.iter().take(columns).take_while(|field| !spans_row(field)).count()
|
||||
};
|
||||
let (row, rest) = remaining.split_at(count);
|
||||
let field_width = if full_width { width } else { column_width };
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = gap;
|
||||
let label_height = row.iter().map(|field| ui.painter().layout(
|
||||
intake_label(field), Type::Meta.font_id(), Tokens::get(ui.ctx()).agent().text_dim, field_width,
|
||||
).size().y).fold(0.0_f32, f32::max);
|
||||
for field in row {
|
||||
let raw_hint = intake_hint(field);
|
||||
let fallback;
|
||||
let effective_hint = if !raw_hint.is_empty() {
|
||||
raw_hint
|
||||
} else {
|
||||
let clean_label = field["label"].as_str().unwrap_or("").trim().trim_end_matches(['*', '*']).trim();
|
||||
fallback = match clean_label {
|
||||
"" => String::new(),
|
||||
"核心卖点" => "输入核心卖点、材质亮点或使用场景优势".to_owned(),
|
||||
"注意事项" => "输入安装、保养或画面避坑注意事项(选填)".to_owned(),
|
||||
other if field["required"] == true => format!("输入{other}"),
|
||||
other => format!("输入{other}(选填)"),
|
||||
};
|
||||
fallback.as_str()
|
||||
};
|
||||
changed |= intake_field(
|
||||
ui, scope, field_width, label_height, field, effective_hint,
|
||||
values, reduced, barcode, inline_errors, scroll_to_field, manual_edited,
|
||||
);
|
||||
}
|
||||
});
|
||||
remaining = rest;
|
||||
}
|
||||
});
|
||||
changed
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn intake_label(field: &Value) -> String {
|
||||
let name = field["label"].as_str().or(field["id"].as_str()).unwrap_or("未命名字段");
|
||||
format!("{}{}{}", name,
|
||||
field["unit"].as_str().map(|unit| format!(" ({unit})")).unwrap_or_default(),
|
||||
if field["required"] == true { " *" } else { "" })
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in crate::jiansun) fn intake_field(
|
||||
ui: &mut Ui,
|
||||
scope: egui::Id,
|
||||
width: f32,
|
||||
label_height: f32,
|
||||
field: &Value,
|
||||
hint: &str,
|
||||
values: &mut Value,
|
||||
reduced: bool,
|
||||
barcode: Option<&str>,
|
||||
inline_errors: &mut HashMap<String, String>,
|
||||
scroll_to_field: &mut Option<String>,
|
||||
manual_edited: &mut HashSet<String>,
|
||||
) -> bool {
|
||||
let label = intake_label(field);
|
||||
let Some(id) = field["id"].as_str().filter(|id| !id.trim().is_empty()) else {
|
||||
stitch_ui::status_label(ui, &format!("{label}缺少字段编号"), stitch_ui::StatusTone::Warning);
|
||||
return false;
|
||||
};
|
||||
let error_key = match barcode {
|
||||
Some(code) => format!("intake-barcode:{code}:{id}"),
|
||||
None => format!("intake-product:{id}"),
|
||||
};
|
||||
let field_error = inline_errors.get(&error_key).cloned();
|
||||
let should_scroll = scroll_to_field.as_deref() == Some(error_key.as_str());
|
||||
if should_scroll {
|
||||
*scroll_to_field = None;
|
||||
}
|
||||
let mut changed = false;
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(width);
|
||||
ui.spacing_mut().item_spacing.y = space::XS + space::XXS;
|
||||
let text_dim = Tokens::get(ui.ctx()).agent().text_dim;
|
||||
ui.allocate_ui(vec2(width, label_height), |ui| {
|
||||
ui.set_min_height(label_height);
|
||||
ui.add(egui::Label::new(egui::RichText::new(&label).font(Type::Meta.font_id()).color(text_dim)).wrap());
|
||||
});
|
||||
match field["type"].as_str() {
|
||||
Some("text" | "number") => {
|
||||
let mut value = values[id].clone();
|
||||
let (edited, _) = edit_named_with_error(
|
||||
ui, scope.with(id), &mut value, width, intake_multiline(field), hint, &label,
|
||||
field_error.as_deref(), should_scroll,
|
||||
);
|
||||
if edited {
|
||||
values[id] = value;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Some("select") => {
|
||||
let selected = values[id].as_str().filter(|value| !value.is_empty()).map(str::to_owned);
|
||||
let response = stitch_ui::halo_select_hint(ui, scope.with(id), width, selected.as_deref(), hint, reduced, |ui| {
|
||||
for option in field["options"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||
if stitch_ui::select_option_sized(ui, option, values[id] == option, true, vec2(ui.available_width(), control::STANDARD)).clicked() {
|
||||
values[id] = json!(option);
|
||||
changed = true;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
let resp = response.response.accessible_name(&label);
|
||||
if should_scroll {
|
||||
resp.scroll_to_me(Some(egui::Align::Center));
|
||||
resp.request_focus();
|
||||
}
|
||||
if let Some(err) = field_error.as_deref() {
|
||||
stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error);
|
||||
}
|
||||
}
|
||||
Some("boolean") => {
|
||||
let value = values[id] == true;
|
||||
let resp = stitch_ui::toggle_option_sized(ui, "是", value, true, vec2(width, control::STANDARD)).accessible_name(&label);
|
||||
if should_scroll {
|
||||
resp.scroll_to_me(Some(egui::Align::Center));
|
||||
resp.request_focus();
|
||||
}
|
||||
if resp.clicked() {
|
||||
values[id] = json!(!value);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let kind = field["type"].as_str().unwrap_or("未指定");
|
||||
stitch_ui::status_label(ui, &format!("暂不支持此字段类型({kind})"), stitch_ui::StatusTone::Warning);
|
||||
}
|
||||
}
|
||||
});
|
||||
if changed {
|
||||
inline_errors.remove(&error_key);
|
||||
manual_edited.insert(error_key);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn spu_field(brief: &Value) -> &'static str {
|
||||
if brief["identifierType"] == "spu" { "identifier" } else { "deliverySpu" }
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn field_kind(field: &Value) -> &Value { field.get("type").unwrap_or(&field["kind"]) }
|
||||
|
||||
pub(in crate::jiansun) fn field_key(field: &Value) -> &Value { field.get("id").unwrap_or(&field["key"]) }
|
||||
|
||||
pub(in crate::jiansun) fn image_slot(template: &Value, field: &Value, barcode: Option<&str>) -> Value {
|
||||
json!({"templateId":template,"fieldKey":field_key(field),"barcode":barcode,
|
||||
"imageRole":field["imageRole"].as_str().or_else(|| field_key(field).as_str()),
|
||||
"multiple":field["multiple"] != false,
|
||||
"purpose":if field["imageRole"].as_str().is_none_or(|role| matches!(role, "product" | "detail")) { "product" } else { "scene" }})
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) 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|
|
||||
field_kind(field) == "image" && image_slot(&intake["templateId"], field, barcode) == *slot)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn in_image_slot(image: &Value, slot: &Value) -> bool {
|
||||
image["barcode"] == slot["barcode"]
|
||||
&& (slot["scope"] == "barcode" || (image["fieldKey"] == slot["fieldKey"] && image["templateId"] == slot["templateId"]))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn uses_template_images(brief: &Value) -> bool {
|
||||
["productFields", "barcodeFields"].into_iter().any(|scope|
|
||||
brief["intake"]["schema"][scope].as_array().into_iter().flatten().any(|field| field_kind(field) == "image"))
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn section_heading(ui: &mut Ui, title: &str, description: &str) {
|
||||
stitch_kit::section_heading(ui, title);
|
||||
if !description.is_empty() {
|
||||
ui.add_space(space::XXS);
|
||||
stitch_kit::caption(ui, description);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn section_break(ui: &mut Ui) {
|
||||
ui.add_space(space::LG);
|
||||
stitch_ui::divider(ui);
|
||||
ui.add_space(space::LG);
|
||||
}
|
||||
pub(in crate::jiansun) fn brief_section_break(ui: &mut Ui) {
|
||||
ui.add_space(space::LG);
|
||||
stitch_ui::divider(ui);
|
||||
ui.add_space(space::MD);
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn creation_escape(&mut self, app: &PhotocraftApp, ui: &mut Ui) {
|
||||
let composing_id = egui::Id::unique("creation-ime-composing");
|
||||
let ime_events = ui.input(|input| input.events.iter().filter_map(|event| match event { egui::Event::Ime(event) => Some(event.clone()), _ => None }).collect::<Vec<_>>());
|
||||
let (ime_event, composing) = ui.ctx().data_mut(|data| {
|
||||
let state = data.get_temp_mut_or_default::<bool>(composing_id);
|
||||
for event in &ime_events {
|
||||
match event {
|
||||
egui::ImeEvent::Preedit { text, .. } => *state = !text.is_empty(),
|
||||
egui::ImeEvent::Commit(_) => *state = false,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(!ime_events.is_empty(), *state)
|
||||
});
|
||||
let previous_editors = ui.ctx().data_mut(|data| data.remove_temp::<Vec<egui::Id>>(egui::Id::unique("creation-active-editors"))).unwrap_or_default();
|
||||
if !ui.input(|input| input.key_pressed(egui::Key::Escape)) || composing || ime_event || app.file_dialog_open()
|
||||
|| self.sync_confirm || ui.ctx().memory(|memory| memory.top_modal_layer().is_some()) { return; }
|
||||
if egui::Popup::is_any_open(ui.ctx()) {
|
||||
if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
|
||||
egui::Popup::close_all(ui.ctx());
|
||||
// egui clears focused_widget during input preprocessing, even
|
||||
// when Escape belongs to an overlying popup. Restore the
|
||||
// underlying editor so this key closes only the popup.
|
||||
if let Some(id) = previous_editors.iter().copied().find(|id| ui.ctx().memory(|memory| memory.had_focus_last_frame(*id))) {
|
||||
ui.ctx().memory_mut(|memory| memory.request_focus(id));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
// The workspace settings popup handles Escape before the brief does.
|
||||
if self.model_settings || self.key_settings {
|
||||
return;
|
||||
}
|
||||
let editor = ui.ctx().memory(|memory| previous_editors.iter().copied().find(|id| memory.has_focus(*id) || memory.had_focus_last_frame(*id)));
|
||||
if let Some(id) = editor {
|
||||
if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
|
||||
ui.ctx().memory_mut(|memory| memory.surrender_focus(id));
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn control_geometry(&mut self, name: &str, rect: egui::Rect) {
|
||||
self.creation_view_geometry[name] = rect_value(rect);
|
||||
self.creation_view_geometry["controls"][name] = rect_value(rect);
|
||||
}
|
||||
pub(in crate::jiansun) fn picker_geometry(&mut self, ui: &Ui, name: &str, response: &egui::Response, loading: bool, ready: bool, rows: Vec<Value>) {
|
||||
self.control_geometry(name, response.rect);
|
||||
let open = egui::Popup::is_id_open(ui.ctx(), response.id.with("popup"));
|
||||
let rect = open.then(|| ui.ctx().memory(|memory| memory.area_rect(response.id.with("popup")))).flatten();
|
||||
self.creation_view_geometry["popups"][name] = json!({"open":open,"loading":loading,"ready":ready,"rect":rect.map(rect_value),"rows":rows});
|
||||
}
|
||||
pub(in crate::jiansun) fn material_preview(&mut self, response: egui::Response, id: &str, _label: &str, image: &egui::TextureHandle) {
|
||||
if response.hovered() {
|
||||
let mut tooltip = egui::Tooltip::for_widget(&response);
|
||||
tooltip.popup = tooltip.popup.frame(egui::Frame::NONE);
|
||||
tooltip.show(|ui| {
|
||||
let size = preview_size(image.size_vec2(), vec2(240.0, 240.0));
|
||||
let image_response = ui.image((image.id(), size));
|
||||
self.creation_view_geometry["hoverPreview"] = json!({"id":id,"ready":true,"rect":rect_value(image_response.rect),"sourceSize":image.size()});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,356 @@
|
||||
use super::super::{PhotocraftApp, Tokens, Ui, Workspace, agent_panel::rect_value, json, stitch_kit, stitch_state::Tone, stitch_ui};
|
||||
use super::REFERENCE_DROP_HINT;
|
||||
use super::brief::{brief_variants, has_selected_product_image, image_rows, non_empty_str, store_image_rows};
|
||||
use super::form_widgets_ui::{field_kind, image_slot, in_image_slot, preview_size, uses_template_images};
|
||||
use super::reducers::reference_import_activity;
|
||||
use crate::theme::{AGENT_SEMANTIC, agent_scale::{Type, control, icon, radius, space}};
|
||||
use egui::vec2;
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn visual_assets_gallery_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) -> bool {
|
||||
self.poll_imported_reference_previews(app, ui.ctx());
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let variants = brief_variants(&self.creation_brief);
|
||||
let mut rows = image_rows(&self.creation_brief);
|
||||
let mut changed = false;
|
||||
let mut remove = None;
|
||||
let mut errors = Vec::new();
|
||||
let explicit = uses_template_images(&self.creation_brief);
|
||||
let hidden: Vec<_> = rows.iter().map(|(image, _)| explicit && image["fieldKey"].is_string()
|
||||
&& ["productFields", "barcodeFields"].into_iter().any(|scope| {
|
||||
let intake = &self.creation_brief["intake"];
|
||||
(scope == "barcodeFields") == image["barcode"].is_string()
|
||||
&& intake["schema"][scope].as_array().into_iter().flatten().any(|field|
|
||||
field_kind(field) == "image" && in_image_slot(image,
|
||||
&image_slot(&intake["templateId"], field, image["barcode"].as_str())))
|
||||
})).collect();
|
||||
let has_visible = hidden.iter().any(|&hidden| !hidden);
|
||||
let has_norm_assets = self.creation_brief["normalizedProduct"]["assets"].as_array().is_some_and(|a| !a.is_empty());
|
||||
|
||||
let img_scroll = self.creation_reads.scroll_to_field.as_deref() == Some("images");
|
||||
if img_scroll {
|
||||
self.creation_reads.scroll_to_field = None;
|
||||
}
|
||||
let img_error = self.creation_reads.inline_errors.get("images").cloned();
|
||||
|
||||
let show_gallery = !explicit || has_visible || has_norm_assets;
|
||||
if show_gallery {
|
||||
ui.set_min_width(width);
|
||||
let label = if explicit { "其他视觉素材" } else { "视觉素材库 *" };
|
||||
let resp = stitch_kit::label(ui, label, Type::Body, Tone::Active);
|
||||
if img_scroll {
|
||||
resp.scroll_to_me(Some(egui::Align::Center));
|
||||
}
|
||||
}
|
||||
|
||||
// Role segmentation filter bar when there are assets or references.
|
||||
if has_norm_assets || has_visible {
|
||||
ui.add_space(space::XS);
|
||||
let options = [("全部", true), ("主体图", true), ("主图/场景", true), ("细节图", true)];
|
||||
let filter_idx = self.creation_reads.visual_asset_filter.min(options.len() - 1);
|
||||
let seg = stitch_ui::segmented_control(ui, egui::Id::unique("creation-visual-asset-filter"), &options, filter_idx, self.reduce_motion);
|
||||
if let Some(next) = seg.selected {
|
||||
self.creation_reads.visual_asset_filter = next;
|
||||
}
|
||||
ui.add_space(space::XS);
|
||||
}
|
||||
|
||||
if let Some(err) = img_error.as_deref() {
|
||||
stitch_kit::inline_notice(ui, "triangle-alert", Tone::Failure, err, |_| {});
|
||||
ui.add_space(space::XS);
|
||||
} else if !explicit && (!rows.is_empty() || has_norm_assets) && !has_selected_product_image(&self.creation_brief) {
|
||||
stitch_kit::inline_notice(ui, "triangle-alert", Tone::Warning, "请将至少一张参考图的用途设为「产品图」,或勾选已拉取的平台白底/主图。", |_| {});
|
||||
ui.add_space(space::XS);
|
||||
}
|
||||
|
||||
// Normalized Platform Assets grid (toggleable selectedForProject, preserving kind)
|
||||
let active_filter = self.creation_reads.visual_asset_filter;
|
||||
if has_norm_assets {
|
||||
let mut assets = self.creation_brief["normalizedProduct"]["assets"].as_array().cloned().unwrap_or_default();
|
||||
let mut asset_changed = false;
|
||||
let filtered_indices: Vec<usize> = assets
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, asset)| {
|
||||
let kind = asset["kind"].as_str().unwrap_or("reference");
|
||||
match active_filter {
|
||||
1 => matches!(kind, "whiteBackground" | "sku"),
|
||||
2 => kind == "main",
|
||||
3 => kind == "reference",
|
||||
_ => true,
|
||||
}
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
if !filtered_indices.is_empty() {
|
||||
let grid_cols = stitch_kit::GridColumns { min_cell: 200.0, max_cell: 300.0, most: 4 };
|
||||
let (_, cell_w) = grid_cols.measure(width.max(1.0), space::SM, filtered_indices.len());
|
||||
let cols = stitch_kit::adaptive_grid(ui, egui::Id::unique("creation-norm-assets"), grid_cols, vec2(space::SM, space::SM), filtered_indices.len(), |ui, slot_idx| {
|
||||
let asset_idx = filtered_indices[slot_idx];
|
||||
let asset = &mut assets[asset_idx];
|
||||
let selected = asset["selectedForProject"] != false;
|
||||
let kind = asset["kind"].as_str().unwrap_or("reference");
|
||||
let kind_label = match kind {
|
||||
"whiteBackground" => "白底图",
|
||||
"main" => "主图",
|
||||
"sku" => "SKU 图",
|
||||
_ => "参考图",
|
||||
};
|
||||
let label = non_empty_str(&asset["label"])
|
||||
.or_else(|| non_empty_str(&asset["colorName"]))
|
||||
.or_else(|| non_empty_str(&asset["barcode"]))
|
||||
.unwrap_or(kind_label)
|
||||
.to_owned();
|
||||
let sub = non_empty_str(&asset["barcode"]).unwrap_or("").to_owned();
|
||||
let local_src = non_empty_str(&asset["localSource"]).map(str::to_owned);
|
||||
let border = if selected { t.primary_bg } else { t.card_border };
|
||||
let frame = egui::Frame::NONE
|
||||
.fill(t.dock)
|
||||
.stroke(egui::Stroke::new(1.0, border))
|
||||
.corner_radius(egui::CornerRadius::same(radius::CONTROL as u8))
|
||||
.inner_margin(8);
|
||||
let resp = frame.show(ui, |ui| {
|
||||
ui.vertical(|ui| {
|
||||
let inner_w = (cell_w - 18.0).max(120.0);
|
||||
ui.set_width(inner_w);
|
||||
ui.spacing_mut().item_spacing.y = space::XS;
|
||||
let thumb_h = 92.0;
|
||||
let (preview_rect, preview) = ui.allocate_exact_size(vec2(inner_w, thumb_h), egui::Sense::hover());
|
||||
ui.painter().rect_filled(preview_rect, radius::ROW, t.field);
|
||||
if let Some(src) = local_src.as_deref() {
|
||||
if ui.is_rect_visible(preview_rect) {
|
||||
self.queue_creation_reference(app, src);
|
||||
}
|
||||
let key = super::creation_reads::reference_key(src);
|
||||
if let Some(tex) = self.creation_thumbs.get(&key).cloned() {
|
||||
let size = preview_size(tex.size_vec2(), preview_rect.size());
|
||||
let rect = egui::Align2::CENTER_CENTER.align_size_within_rect(size, preview_rect);
|
||||
ui.painter().image(tex.id(), rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text);
|
||||
self.material_preview(preview, &key, &label, &tex);
|
||||
} else {
|
||||
crate::icons::paint(ui, preview_rect, "image", icon::LG, t.text_dim);
|
||||
}
|
||||
} else {
|
||||
crate::icons::paint(ui, preview_rect, "image", icon::LG, t.text_dim);
|
||||
}
|
||||
ui.add(egui::Label::new(egui::RichText::new(&label).font(Type::Meta.font_id()).color(t.text)).truncate()).on_hover_text(&label);
|
||||
ui.horizontal(|ui| {
|
||||
ui.set_width(inner_w);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let toggle = stitch_ui::toggle_option_sized(ui, if selected { "已选用" } else { "选用" }, selected, true, vec2(60.0, 24.0));
|
||||
self.control_geometry(&format!("platform-asset-toggle-{asset_idx}"), toggle.rect);
|
||||
if toggle.clicked() {
|
||||
asset["selectedForProject"] = json!(!selected);
|
||||
asset_changed = true;
|
||||
}
|
||||
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::Meta.font_id()).color(t.text_dim)).truncate());
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
self.control_geometry(&format!("platform-asset-{asset_idx}"), resp.response.rect);
|
||||
});
|
||||
let _ = cols;
|
||||
ui.add_space(space::SM);
|
||||
}
|
||||
if asset_changed {
|
||||
self.creation_brief["normalizedProduct"]["assets"] = json!(assets);
|
||||
self.creation_reads.inline_errors.remove("images");
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Local / Uploaded Reference Images grid — filename on full-width top row (never truncated to 4 chars!)
|
||||
let visible_indices: Vec<usize> = rows
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(idx, (image, _))| {
|
||||
if hidden.get(*idx) != Some(&false) {
|
||||
return false;
|
||||
}
|
||||
match active_filter {
|
||||
1 => image["purpose"] == "product",
|
||||
2 => image["purpose"] == "scene",
|
||||
3 => image["imageRole"] == "material" || image["imageRole"] == "detail",
|
||||
_ => true,
|
||||
}
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
|
||||
let columns = if width >= 780.0 { 3 } else if width >= 560.0 { 2 } else { 1 };
|
||||
let card_width = (width - 12.0 * (columns - 1) as f32) / columns as f32;
|
||||
egui::Grid::new("creation-references").num_columns(columns).spacing(vec2(12.0, 12.0)).show(ui, |ui| {
|
||||
for (position, &index) in visible_indices.iter().enumerate() {
|
||||
let (image, owner) = &mut rows[index];
|
||||
let source = image["source"].as_str().unwrap_or("").to_owned();
|
||||
let preview_key = super::creation_reads::reference_key(&source);
|
||||
let frame = stitch_ui::material_frame(
|
||||
ui,
|
||||
stitch_ui::surface_frame(ui.ctx(), stitch_ui::SurfaceRole::Input).corner_radius(radius::CONTROL as u8).inner_margin(10),
|
||||
|ui| {
|
||||
ui.vertical(|ui| {
|
||||
let inner_width = (card_width - 22.0).max(120.0);
|
||||
ui.set_width(inner_width);
|
||||
ui.spacing_mut().item_spacing.y = space::XS;
|
||||
// Full-width filename header row so filenames are always readable
|
||||
let name = image["name"].as_str().unwrap_or("产品图片").to_owned();
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 6.0;
|
||||
ui.add(crate::icons::image("image", icon::SM, t.text_dim));
|
||||
ui.add_sized(
|
||||
vec2((inner_width - 52.0).max(60.0), 24.0),
|
||||
egui::Label::new(egui::RichText::new(&name).font(Type::Meta.font_id()).color(t.text)).truncate(),
|
||||
)
|
||||
.on_hover_text(&name);
|
||||
let response = stitch_ui::icon_button(ui, "trash", 24.0, false, "移除此参考图");
|
||||
self.control_geometry(&format!("reference-remove-{index}"), response.rect);
|
||||
if response.clicked() {
|
||||
remove = Some(index);
|
||||
}
|
||||
});
|
||||
// Thumbnail + Role/Color controls side-by-side below header
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 10.0;
|
||||
let thumbnail_width = (inner_width * 0.28).clamp(56.0, 76.0);
|
||||
let details_width = (inner_width - thumbnail_width - 10.0).max(96.0);
|
||||
let (preview_rect, preview) = ui.allocate_exact_size(vec2(thumbnail_width, thumbnail_width), egui::Sense::hover());
|
||||
if ui.is_rect_visible(preview_rect) {
|
||||
self.queue_creation_reference(app, &source);
|
||||
}
|
||||
let texture = self.creation_thumbs.get(&preview_key).cloned();
|
||||
let loading = self.creation_thumbnail_loading(&preview_key);
|
||||
let error = self.creation_thumbnail_error(&preview_key).map(str::to_owned);
|
||||
let saved = self.creation_reference_saved(app, &source);
|
||||
let status = if texture.is_some() {
|
||||
"ready"
|
||||
} else if error.is_some() {
|
||||
"failed"
|
||||
} else if loading {
|
||||
"loading"
|
||||
} else if saved {
|
||||
"queued"
|
||||
} else {
|
||||
"unsaved"
|
||||
};
|
||||
ui.painter().rect_filled(preview_rect, radius::ROW, t.dock);
|
||||
if let Some(texture) = texture.as_ref() {
|
||||
let size = preview_size(texture.size_vec2(), preview_rect.size());
|
||||
let rect = egui::Align2::CENTER_CENTER.align_size_within_rect(size, preview_rect);
|
||||
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);
|
||||
self.material_preview(preview, &preview_key, &name, texture);
|
||||
} else {
|
||||
let label = if error.is_some() {
|
||||
"读取失败"
|
||||
} else if loading {
|
||||
"加载中…"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
if label.is_empty() {
|
||||
crate::icons::paint(ui, preview_rect, "image", icon::MD, t.text_dim);
|
||||
} else {
|
||||
ui.painter().text(preview_rect.center(), egui::Align2::CENTER_CENTER, label, Type::Meta.font_id(), t.text_dim);
|
||||
}
|
||||
if let Some(error) = error.as_deref() {
|
||||
let msg = crate::client_brand::user_error(error, "参考图读取失败");
|
||||
preview.on_hover_text(msg);
|
||||
}
|
||||
}
|
||||
self.control_geometry(&format!("reference-preview-{index}"), preview_rect);
|
||||
self.creation_view_geometry["referenceRows"][index.to_string()] =
|
||||
json!({"source":source,"owner":owner.as_str(),"status":status,"rect":rect_value(preview_rect)});
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(details_width);
|
||||
ui.spacing_mut().item_spacing.y = 6.0;
|
||||
if let Some(error) = error.as_deref() {
|
||||
let msg = crate::client_brand::user_error(error, "参考图读取失败");
|
||||
errors.push(format!("{name} · {msg}"));
|
||||
if saved && stitch_ui::action_button(ui, "重试", stitch_ui::ButtonRole::Quiet, true).clicked() {
|
||||
self.retry_creation_reference(app, &source);
|
||||
}
|
||||
}
|
||||
let reference_id = (&source, owner.clone());
|
||||
let purpose = stitch_ui::halo_select(ui, ("creation-purpose", &reference_id), details_width, if image["purpose"] == "scene" { "场景参考" } else { "产品图" }, self.reduce_motion, |ui| {
|
||||
for (purpose, label) in [("product", "产品图"), ("scene", "场景参考")] {
|
||||
if stitch_ui::select_option(ui, label, image["purpose"] == purpose, true).clicked() {
|
||||
image["purpose"] = json!(purpose);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
self.control_geometry(&format!("reference-purpose-{index}"), purpose.response.rect);
|
||||
let selected = variants
|
||||
.iter()
|
||||
.find(|variant| variant["id"] == owner.as_str())
|
||||
.and_then(|variant| variant["name"].as_str())
|
||||
.unwrap_or(if owner.is_empty() { "共用 · 所有花色" } else { "选择花色" });
|
||||
let ownership = stitch_ui::halo_select(ui, ("creation-reference-variant", &reference_id), details_width, selected, self.reduce_motion, |ui| {
|
||||
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
|
||||
let size = vec2(ui.available_width(), control::STANDARD);
|
||||
if stitch_ui::select_option_sized(ui, "共用 · 所有花色", owner.is_empty(), true, size).clicked() {
|
||||
owner.clear();
|
||||
changed = true;
|
||||
}
|
||||
for variant in &variants {
|
||||
let Some(id) = variant["id"].as_str() else { continue };
|
||||
if stitch_ui::select_option_sized(
|
||||
ui, variant["name"].as_str().unwrap_or("花色"), owner.as_str() == id, true, size,
|
||||
).clicked() {
|
||||
*owner = id.into();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
self.control_geometry(&format!("reference-owner-{index}"), ownership.response.rect);
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
self.control_geometry(&format!("reference-{index}"), frame.response.rect);
|
||||
if (position + 1) % columns == 0 {
|
||||
ui.end_row();
|
||||
}
|
||||
}
|
||||
});
|
||||
if !explicit {
|
||||
ui.add_space(space::XS);
|
||||
let drop_rect = self.add_reference_button(app, ui, width);
|
||||
if rows.is_empty() {
|
||||
self.control_geometry("reference-empty", drop_rect);
|
||||
}
|
||||
}
|
||||
for error in errors {
|
||||
stitch_ui::status_label(ui, &error, stitch_ui::StatusTone::Error);
|
||||
}
|
||||
if !self.creation_reads.reference_import_error.is_empty() && self.creation_reads.reference_import_error != REFERENCE_DROP_HINT {
|
||||
let status = stitch_ui::status_label(ui, &self.creation_reads.reference_import_error, stitch_ui::StatusTone::Error);
|
||||
self.control_geometry("reference-import-error", status.rect);
|
||||
}
|
||||
if let Some(label) = reference_import_activity(self.busy.as_deref()) {
|
||||
ui.add_space(space::SM);
|
||||
let id = egui::Id::unique(("creation-reference-import", &self.origin, self.account["id"].as_str(), self.creation_doc));
|
||||
let response = stitch_ui::progress(ui, id, label, None, self.reduce_motion);
|
||||
self.control_geometry("reference-import-progress", response.rect);
|
||||
}
|
||||
if let Some(index) = remove {
|
||||
rows = rows.into_iter().enumerate().filter_map(|(position, row)| (position != index).then_some(row)).collect();
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
match store_image_rows(&mut self.creation_brief, rows) {
|
||||
Ok(()) => {
|
||||
self.creation_reads.inline_errors.remove("images");
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
Err(error) => self.error = error,
|
||||
}
|
||||
}
|
||||
show_gallery
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,202 @@
|
||||
use super::super::{Value, json};
|
||||
use super::super::creation_reads::wizard;
|
||||
use super::brief::{dedupe_strings, non_empty_str, string_list};
|
||||
use super::form_widgets_ui::{current_image_slot, field_key, field_kind, in_image_slot};
|
||||
|
||||
pub(in crate::jiansun) fn assign_platform_images(brief: &mut Value) {
|
||||
let intake = brief["intake"].clone();
|
||||
if let Some(images) = brief["images"].as_array_mut() {
|
||||
for image in images.iter_mut().filter(|image| image["platformImage"] == true) {
|
||||
let scope = if image["barcode"].is_string() { "barcodeFields" } else { "productFields" };
|
||||
if let Some(field) = intake["schema"][scope].as_array().into_iter().flatten().find(|field|
|
||||
field_kind(field) == "image" && field["imageRole"] == "product" && field["multiple"] != false) {
|
||||
image["fieldKey"] = field_key(field).clone();
|
||||
image["templateId"] = intake["templateId"].clone();
|
||||
} else if let Some(row) = image.as_object_mut() {
|
||||
row.remove("fieldKey");
|
||||
row.remove("templateId");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn add_slot_images(brief: &mut Value, slot: &Value, images: &[Value]) -> Result<(), String> {
|
||||
if !current_image_slot(brief, slot) {
|
||||
return Err("图片框已变化,请重新选择".into());
|
||||
}
|
||||
let mut current = brief["images"].as_array().cloned().unwrap_or_default();
|
||||
if slot["multiple"] == false {
|
||||
current.retain(|image| !in_image_slot(image, slot));
|
||||
}
|
||||
for mut image in images.iter().take(if slot["multiple"] == false { 1 } else { 8 }).cloned() {
|
||||
if current.iter().any(|row| in_image_slot(row, slot) && row["source"] == image["source"]) { continue; }
|
||||
for key in ["fieldKey","templateId","imageRole","barcode"] {
|
||||
if !slot[key].is_null() { image[key] = slot[key].clone(); }
|
||||
}
|
||||
image["purpose"] = slot["purpose"].clone();
|
||||
current.push(image);
|
||||
}
|
||||
if current.len() > 8 { return Err("共用及条码图片最多 8 张,请先删除不用的图片".into()); }
|
||||
brief["images"] = json!(current);
|
||||
if let Some(code) = slot["barcode"].as_str()
|
||||
&& let Some(row) = brief["barcodeEntries"].as_array_mut().into_iter().flatten()
|
||||
.find(|row| row["barcode"] == code)
|
||||
{
|
||||
let mut pictures = row["images"].as_array().cloned().unwrap_or_default();
|
||||
if slot["multiple"] == false { pictures.retain(|image| !in_image_slot(image, slot)); }
|
||||
for image in current.into_iter().filter(|image| in_image_slot(image, slot)) {
|
||||
if !pictures.contains(&image) { pictures.push(image); }
|
||||
}
|
||||
row["images"] = json!(pictures);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn field_fact(field: &Value, facts: &Value) -> Option<Value> {
|
||||
let lookup = |name: &str| -> Option<Value> {
|
||||
let alias = match name {
|
||||
"颜色" | "花色" | "color" => "colorName",
|
||||
"商品名" | "产品名称" | "name" => "productName",
|
||||
"条码" | "商品条码" => "barcode",
|
||||
"SKU 编号" | "SKU编码" => "skuCode",
|
||||
"规格" | "规格型号" => "spec",
|
||||
"尺寸" | "产品尺寸" | "size" => "sizeText",
|
||||
"材质" | "主要材质" => "material",
|
||||
"说明" | "产品说明" | "产品描述" | "描述" => "description",
|
||||
"卖点" | "产品卖点" => "sellingPoints",
|
||||
"长" | "长度" => "length",
|
||||
"宽" | "宽度" => "width",
|
||||
"高" | "高度" => "height",
|
||||
"深" | "进深" => "depth",
|
||||
_ => name,
|
||||
};
|
||||
if matches!(alias, "length" | "width" | "height" | "depth" | "secondaryHeight") {
|
||||
let dimension = &facts["dimensions"];
|
||||
let value = dimension.get(alias).or_else(|| (alias == "width").then(|| dimension.get("depth")).flatten())
|
||||
.or_else(|| facts.get(alias))?;
|
||||
let numeric = value.as_f64().or_else(|| value.as_str()?.parse::<f64>().ok())?;
|
||||
if !field["unit"].is_string() || dimension["unit"] == field["unit"] {
|
||||
return Some(value.clone());
|
||||
}
|
||||
let millimetres = |unit: &Value| match unit.as_str()? {
|
||||
"mm" => Some(1.0), "cm" => Some(10.0), "m" => Some(1000.0), _ => None,
|
||||
};
|
||||
let converted = numeric * millimetres(&dimension["unit"])? / millimetres(&field["unit"])?;
|
||||
return converted.is_finite().then(|| json!(converted));
|
||||
}
|
||||
facts.get(alias).or_else(|| facts["attributes"].get(name))
|
||||
.or_else(|| match alias {
|
||||
"sizeText" => facts.get("spec").or_else(|| facts.get("dimensions")),
|
||||
"spec" => facts.get("sizeText"),
|
||||
_ => None,
|
||||
}).filter(|value| !value.is_null()).cloned()
|
||||
};
|
||||
let key = field_key(field).as_str()?;
|
||||
let label = field["label"].as_str().unwrap_or(key);
|
||||
let value = lookup(key).or_else(|| lookup(label))?;
|
||||
match field_kind(field).as_str()? {
|
||||
"text" if value.is_number() => Some(json!(value.to_string())),
|
||||
"text" if value.is_string() => Some(value),
|
||||
"text" if value.is_array() => Some(json!(value.as_array()?.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("\n"))),
|
||||
"text" if value.is_object() => dimension_text(&value).map(Value::String),
|
||||
"number" if value.is_number() || value.as_str().is_some_and(|s| s.parse::<f64>().is_ok_and(f64::is_finite)) => Some(value),
|
||||
"select" if field["options"].as_array().is_some_and(|options| options.contains(&value)) => Some(value),
|
||||
"boolean" if value.is_boolean() => Some(value),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn dimension_text(dimensions: &Value) -> Option<String> {
|
||||
let axes = [("length", "长"), ("width", "宽"), ("height", "高")].into_iter()
|
||||
.filter_map(|(axis, label)| dimensions[axis].as_number().map(|value| format!("{label} {value}")))
|
||||
.collect::<Vec<_>>();
|
||||
(!axes.is_empty()).then(|| match dimensions["unit"].as_str() {
|
||||
Some(unit) => format!("{} {unit}", axes.join(" × ")),
|
||||
None => axes.join(" × "),
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn fill_platform_intake(brief: &mut Value) {
|
||||
if brief["intake"]["schema"]["version"] != 1 { return; }
|
||||
let fill = |fields: &Value, facts: &Value| -> serde_json::Map<String, Value> {
|
||||
fields.as_array().into_iter().flatten().filter_map(|field|
|
||||
Some((field_key(field).as_str()?.to_owned(), field_fact(field, facts)?))).collect()
|
||||
};
|
||||
let fill_missing = |answers: &mut Value, values: serde_json::Map<String, Value>| {
|
||||
for (key, value) in values {
|
||||
if answers.get(&key).is_none() { answers[&key] = value; }
|
||||
}
|
||||
};
|
||||
if brief["normalizedProduct"].is_object() {
|
||||
let np = &brief["normalizedProduct"];
|
||||
let mut shared = json!({
|
||||
"productName": brief["name"].clone(),
|
||||
"dimensions": np["specs"]["dimensions"].clone(),
|
||||
"description": np["copy"]["summary"].clone(),
|
||||
"sellingPoints": np["copy"]["sellingPoints"].clone(),
|
||||
});
|
||||
let mats = dedupe_strings(string_list(&np["specs"]["materials"]));
|
||||
if !mats.is_empty() {
|
||||
shared["material"] = json!(mats.join("、"));
|
||||
}
|
||||
let mut attr_map = serde_json::Map::new();
|
||||
for attr in np["specs"]["attributes"].as_array().into_iter().flatten() {
|
||||
if let (Some(k), Some(v)) = (non_empty_str(&attr["label"]).or_else(|| non_empty_str(&attr["key"])), non_empty_str(&attr["value"])) {
|
||||
attr_map.insert(k.to_owned(), json!(v));
|
||||
}
|
||||
}
|
||||
shared["attributes"] = Value::Object(attr_map);
|
||||
let mut barcodes = std::collections::BTreeMap::new();
|
||||
for variant in np["variants"].as_array().into_iter().flatten() {
|
||||
let color = variant["colorName"].clone();
|
||||
for row in variant["barcodes"].as_array().into_iter().flatten() {
|
||||
let Some(code) = non_empty_str(&row["barcode"]) else { continue };
|
||||
let mut facts = row.clone();
|
||||
facts["barcode"] = json!(code);
|
||||
facts["colorName"] = color.clone();
|
||||
barcodes.insert(code.to_owned(), fill(&brief["intake"]["schema"]["barcodeFields"], &facts));
|
||||
}
|
||||
}
|
||||
let shared_values = fill(&brief["intake"]["schema"]["productFields"], &shared);
|
||||
fill_missing(&mut brief["intake"]["productValues"], shared_values);
|
||||
for (code, values) in barcodes {
|
||||
fill_missing(&mut brief["intake"]["barcodeValues"][code], values);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if brief["platformFacts"]["spu"] != brief["identifier"] { return; }
|
||||
let mut shared = brief["platformFacts"]["shared"].clone();
|
||||
if !shared.is_object() { return; }
|
||||
shared["productName"] = brief["name"].clone();
|
||||
let mut barcodes = std::collections::BTreeMap::new();
|
||||
if let Some(rows) = brief["platformFacts"]["barcodes"].as_object() {
|
||||
for (code, row) in rows {
|
||||
let mut facts = row.clone();
|
||||
facts["barcode"] = json!(code);
|
||||
barcodes.insert(code.clone(), fill(&brief["intake"]["schema"]["barcodeFields"], &facts));
|
||||
}
|
||||
}
|
||||
let shared_values = fill(&brief["intake"]["schema"]["productFields"], &shared);
|
||||
fill_missing(&mut brief["intake"]["productValues"], shared_values);
|
||||
for (code, values) in barcodes {
|
||||
fill_missing(&mut brief["intake"]["barcodeValues"][code], values);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn set_intake(brief: &mut Value, template_id: &Value, schema: &Value) {
|
||||
if schema["version"] != 1 {
|
||||
if let Some(fields) = brief.as_object_mut() {
|
||||
fields.remove("intake");
|
||||
}
|
||||
} 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}));
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) const BARCODE_HINT: &str = "如 DNZ030516N717V01";
|
||||
pub(in crate::jiansun) const BARCODE_SEPARATORS: [char; 7] = ['\r', '\n', ',', ',', '、', ';', ';'];
|
||||
|
||||
@ -0,0 +1,188 @@
|
||||
use super::super::{PhotocraftApp, Tokens, Ui, Workspace, json, stitch_kit, stitch_state::Tone, stitch_ui};
|
||||
use super::form_widgets_ui::{edit, field_group, section_break, section_heading};
|
||||
use crate::theme::agent_scale::{Type, space};
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn points_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
let field_scope = self.creation_field_scope(app);
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
ui.label(egui::RichText::new("产品事实与卖点").font(Type::Display.semibold()).color(t.text));
|
||||
ui.add_space(space::MD);
|
||||
section_heading(ui, "产品事实", "结合产品资料核对,避免生成未确认的产品信息");
|
||||
ui.add_space(space::SM);
|
||||
let facts = self.creation["facts"]["items"].as_array().cloned().unwrap_or_default();
|
||||
if facts.is_empty() {
|
||||
stitch_kit::caption(ui, "还没有分析结果,产品原始资料会继续保留");
|
||||
}
|
||||
for fact in facts {
|
||||
ui.label(egui::RichText::new(fact["text"].as_str().unwrap_or("")).font(Type::Body.font_id())).on_hover_text(fact["source"].as_str().unwrap_or(""));
|
||||
}
|
||||
let missing = self.creation["facts"]["missing"].as_array().cloned().unwrap_or_default();
|
||||
if !missing.is_empty() {
|
||||
ui.add_space(space::SM);
|
||||
stitch_ui::disclosure(ui, egui::Id::unique("creation-missing"), &format!("待确认 · {}", missing.len()), false, self.reduce_motion, |ui| {
|
||||
for item in missing {
|
||||
ui.label(item.as_str().unwrap_or(""));
|
||||
}
|
||||
});
|
||||
}
|
||||
section_break(ui);
|
||||
let batches = self.creation["sellingPoints"]["batches"].as_array().cloned().unwrap_or_default();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
stitch_kit::label(ui, "选择卖点", Type::Heading, Tone::Active);
|
||||
stitch_kit::label(ui, format!("已选 {} / 20", self.creation_selected.len()), Type::Meta, Tone::Quiet);
|
||||
stitch_kit::label(ui, format!("{} / 12 批", batches.len()), Type::Meta, Tone::Quiet);
|
||||
});
|
||||
ui.add_space(space::SM);
|
||||
if batches.is_empty() {
|
||||
stitch_kit::caption(ui, "生成一批卖点,再选择适合这款产品的表达");
|
||||
}
|
||||
for (batch_index, batch) in batches.iter().enumerate() {
|
||||
let id = batch["id"].as_str().unwrap_or("");
|
||||
if batches.len() > 1 {
|
||||
stitch_kit::label(ui, format!("第 {} 批", batch_index + 1), Type::Meta, Tone::Quiet);
|
||||
}
|
||||
for (index, item) in batch["items"].as_array().cloned().unwrap_or_default().iter().enumerate() {
|
||||
let key = format!("{id}:{index}");
|
||||
let selected = self.creation_selected.contains(&key);
|
||||
let label = item.as_str().or_else(|| item["text"].as_str()).unwrap_or("");
|
||||
let response = stitch_ui::toggle_option(ui, label, selected, selected || self.creation_selected.len() < 20);
|
||||
self.control_geometry(&format!("selling-point-{batch_index}-{index}"), response.rect);
|
||||
if response.clicked() {
|
||||
if selected {
|
||||
self.creation_selected.retain(|s| s != &key);
|
||||
} else {
|
||||
self.creation_selected.push(key);
|
||||
}
|
||||
self.creation_submit(app, "creation-select", json!({}));
|
||||
}
|
||||
}
|
||||
ui.add_space(space::SM);
|
||||
}
|
||||
ui.add_space(space::MD);
|
||||
let direction_width = ui.available_width();
|
||||
field_group(ui, direction_width, "下一批表达方向(可选)", |ui| {
|
||||
let id = field_scope.with("creation-direction");
|
||||
ui.data_mut(|data| data.get_temp_mut_or_default::<Vec<egui::Id>>(egui::Id::unique("creation-active-editors")).push(id.with("editor")));
|
||||
let reduced = ui.style().animation_time == 0.0;
|
||||
if stitch_ui::halo_field(ui, id, None, reduced, |ui| {
|
||||
ui.add(stitch_ui::text_input(&mut self.creation_direction, "例如:更突出木材质感与空间搭配", false)
|
||||
.id(id.with("editor")).desired_width(ui.available_width().max(0.0)).frame(egui::Frame::NONE))
|
||||
})
|
||||
.changed()
|
||||
{
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
});
|
||||
ui.add_space(space::MD);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let generate =
|
||||
ui.add_enabled_ui(batches.len() < 12, |ui| stitch_ui::button(ui, if batches.is_empty() { "生成一批卖点" } else { "再生成一批" }, false)).inner;
|
||||
self.control_geometry("points-generate", generate.rect);
|
||||
if generate.clicked() {
|
||||
self.creation_submit(app, "creation-points", json!({}));
|
||||
}
|
||||
let plan = ui.add_enabled_ui(!self.creation_selected.is_empty(), |ui| stitch_ui::button(ui, "生成页面方案", true)).inner;
|
||||
self.control_geometry("points-plan", plan.rect);
|
||||
if plan.clicked() {
|
||||
self.creation_submit(app, "creation-plan", json!({}));
|
||||
}
|
||||
});
|
||||
}
|
||||
pub(in crate::jiansun) fn plan_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
let field_scope = self.creation_field_scope(app);
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let status = self.creation["plan"]["status"].as_str().unwrap_or("idle").to_owned();
|
||||
let mut screens = self.creation_plan.as_array().cloned().unwrap_or_default();
|
||||
ui.label(egui::RichText::new("页面方案").font(Type::Display.semibold()).color(t.text));
|
||||
stitch_kit::caption(ui, "调整页面文案与画面要求,修改后保存并重新确认");
|
||||
ui.add_space(space::MD);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if let Some(count) = self.creation_template_screen_count() {
|
||||
ui.label(format!("{count} 屏"));
|
||||
}
|
||||
let generate = stitch_ui::button(ui, if screens.is_empty() { "生成页面方案" } else { "重新生成方案" }, false);
|
||||
self.control_geometry("plan-generate", generate.rect);
|
||||
if generate.clicked() {
|
||||
self.creation_submit(app, "creation-plan", json!({}));
|
||||
}
|
||||
let label = match status.as_str() {
|
||||
"confirmed" => "已确认",
|
||||
"needs-confirm" => "待确认",
|
||||
"stale" => "需要重新确认",
|
||||
_ => "尚未确认",
|
||||
};
|
||||
stitch_kit::label(ui, label, Type::Meta, Tone::Quiet);
|
||||
});
|
||||
if status == "stale" || self.creation_dirty {
|
||||
ui.add_space(space::SM);
|
||||
stitch_kit::inline_notice(
|
||||
ui,
|
||||
"triangle-alert",
|
||||
Tone::Warning,
|
||||
self.creation["plan"]["invalidReason"].as_str().filter(|s| !s.is_empty()).unwrap_or("资料已变更,请重新确认方案"),
|
||||
|_| {},
|
||||
);
|
||||
}
|
||||
section_break(ui);
|
||||
if screens.is_empty() {
|
||||
stitch_kit::label(ui, "还没有页面方案,生成后可以逐页调整", Type::Body, Tone::Quiet);
|
||||
}
|
||||
let mut changed = false;
|
||||
let screen_count = screens.len();
|
||||
for (i, screen) in screens.iter_mut().enumerate() {
|
||||
let screen_id = screen["id"].as_str().filter(|id| !id.is_empty()).map(str::to_owned);
|
||||
let screen_key = (screen_id.as_deref(), screen_id.is_none().then_some(i));
|
||||
stitch_ui::disclosure(ui, egui::Id::unique(("creation-plan-screen", screen_key)), &format!("{} · {}", i + 1, screen["name"].as_str().unwrap_or("页面")), i == 0, self.reduce_motion, |ui| {
|
||||
let width = ui.available_width();
|
||||
field_group(ui, width, "标题", |ui| {
|
||||
changed |= edit(ui, (field_scope, screen_key, "title"), &mut screen["title"], width, false, "标题");
|
||||
});
|
||||
ui.add_space(space::SM);
|
||||
field_group(ui, width, "正文", |ui| {
|
||||
changed |= edit(ui, (field_scope, screen_key, "body"), &mut screen["body"], width, true, "正文");
|
||||
});
|
||||
ui.add_space(space::SM);
|
||||
stitch_ui::disclosure(ui, egui::Id::unique(("creation-image-prompt", screen_key)), "画面要求", false, self.reduce_motion, |ui| {
|
||||
let width = ui.available_width();
|
||||
changed |= edit(ui, (field_scope, screen_key, "imagePrompt"), &mut screen["imagePrompt"], width, true, "画面要求");
|
||||
});
|
||||
});
|
||||
ui.add_space(space::SM);
|
||||
if i + 1 < screen_count {
|
||||
stitch_ui::divider(ui);
|
||||
}
|
||||
}
|
||||
self.creation_plan = json!(screens);
|
||||
if changed {
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
section_break(ui);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if self.creation_dirty {
|
||||
let save = stitch_ui::button(ui, "保存方案修改", false);
|
||||
self.control_geometry("plan-save", save.rect);
|
||||
if save.clicked() {
|
||||
self.creation_submit(app, "creation-plan-edit", json!({}));
|
||||
}
|
||||
}
|
||||
let confirm = ui.add_enabled_ui(status == "needs-confirm" && !self.creation_dirty, |ui| stitch_ui::button(ui, "确认方案", false)).inner;
|
||||
self.control_geometry("plan-confirm", confirm.rect);
|
||||
if confirm.clicked() {
|
||||
self.creation_submit(app, "creation-confirm", json!({}));
|
||||
}
|
||||
let slots = ui.add_enabled_ui(status == "confirmed" && !self.creation_dirty, |ui| stitch_ui::button(ui, "制作图位", true)).inner;
|
||||
self.control_geometry("plan-slots", slots.rect);
|
||||
if slots.clicked() {
|
||||
self.creation_step = 4;
|
||||
}
|
||||
if self.creation_pending.is_some() {
|
||||
let load = stitch_ui::button(ui, "载入生成结果", false);
|
||||
self.control_geometry("plan-load", load.rect);
|
||||
if load.clicked() {
|
||||
self.creation_submit(app, "creation-load", json!({}));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,511 @@
|
||||
use super::super::{Duration, Instant, PhotocraftApp, Request, Value, Workspace, json};
|
||||
use super::super::creation_reads::wizard::CreationStage;
|
||||
use super::barcode::update_detail_barcode;
|
||||
use super::brief::{brief_variants, empty_brief, incomplete_brief_stage, non_empty_str, normalized_color_groups, selected_template, set_brief_variants, template_identity};
|
||||
use super::review_hints::ReviewHintItem;
|
||||
|
||||
pub(in crate::jiansun) const DELIVERY_DIR_PREF_KEY: &str = "jiansun.deliveryDir";
|
||||
|
||||
pub(in crate::jiansun) fn remembered_delivery_dir(app: &PhotocraftApp) -> Option<String> {
|
||||
app.session.prefs().dialogs.get(DELIVERY_DIR_PREF_KEY)
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|path| !path.is_empty())
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn remember_delivery_dir(app: &mut PhotocraftApp, path: &str) {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.is_empty() {
|
||||
return;
|
||||
}
|
||||
app.session.prefs.edit(|prefs| {
|
||||
prefs.dialogs.insert(DELIVERY_DIR_PREF_KEY.into(), json!(trimmed));
|
||||
});
|
||||
let _ = crate::prefs_ui::save_preferences(app);
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn default_delivery_dir_for_home(home: &std::path::Path) -> Option<String> {
|
||||
let desktop = home.join("Desktop");
|
||||
let onedrive_desktop = home.join("OneDrive").join("Desktop");
|
||||
let documents = home.join("Documents");
|
||||
let base = if desktop.is_dir() {
|
||||
desktop
|
||||
} else if onedrive_desktop.is_dir() {
|
||||
onedrive_desktop
|
||||
} else if documents.is_dir() {
|
||||
documents
|
||||
} else {
|
||||
desktop
|
||||
};
|
||||
base.join("小壹成品").to_str().map(str::to_owned)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn default_delivery_dir() -> Option<String> {
|
||||
let home = std::env::var_os("USERPROFILE")
|
||||
.or_else(|| std::env::var_os("HOME"))
|
||||
.map(std::path::PathBuf::from)?;
|
||||
default_delivery_dir_for_home(&home)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn preferred_delivery_dir(app: &PhotocraftApp) -> Option<String> {
|
||||
remembered_delivery_dir(app).or_else(default_delivery_dir)
|
||||
}
|
||||
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn creation_field_scope(&self, app: &PhotocraftApp) -> egui::Id {
|
||||
self.creation_field_scope_for(self.creation_doc, app.session.active().map(|s| s.doc.id.0))
|
||||
}
|
||||
pub(in crate::jiansun) fn creation_field_scope_for(&self, creation_doc: Option<u64>, active_doc: Option<u64>) -> egui::Id {
|
||||
egui::Id::unique(("creation-fields", &self.origin, self.account["id"].as_str(), creation_doc, active_doc))
|
||||
}
|
||||
pub(in crate::jiansun) fn resume_project_brief(&mut self, app: &PhotocraftApp, project: &Value) {
|
||||
let Some(state) = app.session.active() else { return };
|
||||
let Ok(saved_stage) = serde_json::from_value::<CreationStage>(project["briefResumeStage"].clone()) else { return };
|
||||
if project["briefIncomplete"] != true
|
||||
|| super::canvas_workspace::document_mapping(&state.doc).is_some_and(|mapping| mapping["canvasFirst"] == true)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let doc = Some(state.doc.id.0);
|
||||
let dirty_brief = if self.creation_doc == doc && self.creation_dirty {
|
||||
Some(&self.creation_brief)
|
||||
} else {
|
||||
self.current_creation_ui_scope(app).and_then(|scope| self.retained_creation_ui.get(&scope))
|
||||
.map(|retained| &retained.draft["brief"])
|
||||
};
|
||||
let stage = dirty_brief.map_or(saved_stage, |brief| {
|
||||
incomplete_brief_stage(brief, &Value::Null, |_| true).unwrap_or(CreationStage::Details)
|
||||
});
|
||||
self.creation_reads.staged_new_project = false;
|
||||
self.creation_reads.staged_prior_draft = None;
|
||||
self.creation_reads.new_project_doc = None;
|
||||
self.creation_reads.wizard_stage = Some((self.creation_field_scope_for(doc, doc), stage));
|
||||
self.set_creation_destination(0);
|
||||
}
|
||||
pub(in crate::jiansun) fn template_binding(&self, doc: Option<u64>) -> String {
|
||||
format!("{}|{}|{:?}", self.account["id"], self.origin, doc)
|
||||
}
|
||||
pub(in crate::jiansun) fn brief_with_manual_fields(&self) -> Value {
|
||||
let mut brief = self.creation_brief.clone();
|
||||
if !self.creation_reads.manual_edited_fields.is_empty() {
|
||||
let mut edited: std::collections::BTreeSet<_> = brief["manualFields"].as_array().into_iter().flatten()
|
||||
.filter_map(Value::as_str).collect();
|
||||
edited.extend(self.creation_reads.manual_edited_fields.iter().map(String::as_str));
|
||||
brief["manualFields"] = json!(edited);
|
||||
}
|
||||
brief
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) 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();
|
||||
}
|
||||
let mut draft = json!({"revision":self.creation["revision"],"brief":self.brief_with_manual_fields(),"width":self.creation_draft_width(),
|
||||
"screens":self.creation_plan,"direction":self.creation_direction,"selected":self.creation_selected});
|
||||
if let Some(path) = &self.creation_delivery_dir {
|
||||
draft["deliveryDir"] = json!(path);
|
||||
}
|
||||
draft
|
||||
}
|
||||
pub(in crate::jiansun) fn can_save_creation(&self) -> bool {
|
||||
self.busy.is_none() && (!self.unknown || self.scoped_production_pending())
|
||||
}
|
||||
pub(in crate::jiansun) fn creation_autosave(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
if self.creation_doc != app.session.active().map(|s| s.doc.id.0) || self.creation_doc.is_none() {
|
||||
return;
|
||||
}
|
||||
let signature = self.creation_draft().to_string();
|
||||
if self.restored_creation_signature.as_deref() == Some(signature.as_str()) {
|
||||
return;
|
||||
}
|
||||
if signature != self.creation_edit_signature {
|
||||
self.creation_edit_signature = signature;
|
||||
self.creation_touched = Instant::now();
|
||||
if self.creation_dirty {
|
||||
self.draft_changed = true;
|
||||
self.sync_dirty = true;
|
||||
}
|
||||
}
|
||||
if !self.creation_dirty || !self.can_save_creation() || self.creation_failed_signature == self.creation_edit_signature {
|
||||
return;
|
||||
}
|
||||
if self.creation_touched.elapsed() < Duration::from_millis(900) {
|
||||
ctx.request_repaint_after(Duration::from_millis(150));
|
||||
return;
|
||||
}
|
||||
let brief_changed = self.creation_brief != self.creation["brief"]
|
||||
|| self.creation["width"].as_u64() != self.creation_draft_width()
|
||||
|| super::product_production::delivery_dir(&self.creation) != self.creation_delivery_dir;
|
||||
let plan_changed = self.creation_plan != self.creation["plan"]["screens"];
|
||||
let method = if brief_changed {
|
||||
"creation-save"
|
||||
} else if plan_changed {
|
||||
"creation-plan-edit"
|
||||
} else {
|
||||
"creation-select"
|
||||
};
|
||||
if method == "creation-save" || !self.unknown {
|
||||
self.creation_submit(app, method, json!({}));
|
||||
}
|
||||
}
|
||||
pub(in crate::jiansun) fn sync_signature(&self) -> String {
|
||||
json!({"composer":self.composer,"messages":self.messages,"creation":self.creation,"draft":self.creation_draft(),"templateWorkflow":self.template_workflow}).to_string()
|
||||
}
|
||||
pub(in crate::jiansun) fn sync_action(&mut self, app: &PhotocraftApp, method: &str, mut input: Value) {
|
||||
if self.busy.is_some() || self.saving.is_some() || self.project_operation_pending() {
|
||||
self.error = "请等待当前操作完成".into();
|
||||
return;
|
||||
}
|
||||
let Some(st) = app.session.active() else {
|
||||
self.error = "请先打开项目".into();
|
||||
return;
|
||||
};
|
||||
if input["status"] == "completed" && (self.creation_dirty || self.unknown) {
|
||||
self.error = "请先保存资料与方案,并核查原请求后再完结".into();
|
||||
return;
|
||||
}
|
||||
input["doc"] = json!(st.doc.id.0);
|
||||
input["revision"] = json!(st.revision);
|
||||
if input["status"].is_null() {
|
||||
input["status"] = json!("draft");
|
||||
}
|
||||
let meta = json!({"composer":self.composer,"messages":self.messages,"project":self.project_context,"syncDirty":self.sync_dirty,"creationDraft":self.creation_draft()});
|
||||
self.sync_request_meta = self.sync_signature();
|
||||
self.draft_changed = false;
|
||||
let _ = self.tx.send(Request::Save(st.doc.clone(), st.revision, meta));
|
||||
self.saving = Some((st.doc.id.0, st.revision));
|
||||
self.send(method, input);
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn jump_to_review_hint(&mut self, app: &PhotocraftApp, hint: &ReviewHintItem) {
|
||||
let output_id = hint
|
||||
.output_id
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| {
|
||||
if self.canvas_workspace.output.is_empty() { "detail" } else { self.canvas_workspace.output.as_str() }
|
||||
})
|
||||
.to_owned();
|
||||
self.template_ui.navigate(&output_id, hint.slot_id.as_deref());
|
||||
let mut request = json!({ "outputId": output_id });
|
||||
if let Some(variant_id) = hint.variant_id.as_deref() {
|
||||
request["variantId"] = json!(variant_id);
|
||||
}
|
||||
if let Some(slot_id) = hint.slot_id.as_deref() {
|
||||
request["slotId"] = json!(slot_id);
|
||||
}
|
||||
if let Some(layer_id) = hint.layer_id.as_deref() {
|
||||
request["layerId"] = json!(layer_id);
|
||||
}
|
||||
if let Err(error) = self.slot_action(app, "slot-skeleton", request) {
|
||||
self.product_views.view_error = Some(error.clone());
|
||||
self.error = error;
|
||||
}
|
||||
self.sync_confirm = false;
|
||||
self.show_center(super::CenterView::Canvas, true);
|
||||
self.creation_open = false;
|
||||
}
|
||||
pub(in crate::jiansun) 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.new_project_doc = None;
|
||||
self.reset_test_presets();
|
||||
self.creation_reads.wizard_stage = None;
|
||||
self.library = false;
|
||||
self.material = false;
|
||||
self.creation_open = true;
|
||||
self.creation_step = 0;
|
||||
self.creation_doc = None;
|
||||
self.creation_brief = empty_brief();
|
||||
self.creation = json!({"brief": self.creation_brief.clone()});
|
||||
self.creation_dirty = false;
|
||||
self.creation_read_failed = false;
|
||||
self.creation_width = 0;
|
||||
self.creation_delivery_dir = preferred_delivery_dir(app);
|
||||
self.creation_selected.clear();
|
||||
self.creation_direction.clear();
|
||||
self.creation_plan = json!([]);
|
||||
self.creation_progress.clear();
|
||||
self.creation_reads.inline_errors.clear();
|
||||
self.creation_reads.scroll_to_field = None;
|
||||
self.creation_reads.manual_edited_fields.clear();
|
||||
self.creation_reads.visual_asset_filter = 0;
|
||||
self.creation_reads.expanded_colors.clear();
|
||||
self.creation_reads.expanded_skus.clear();
|
||||
self.creation_reads.platform_message.clear();
|
||||
self.creation_reads.platform_sync_note.clear();
|
||||
self.creation_reads.reference_import_error.clear();
|
||||
self.creation_reads.resource_set = Value::Null;
|
||||
self.creation_reads.resource_component.clear();
|
||||
self.creation_reads.resource_image = None;
|
||||
self.template_workflow = Value::Null;
|
||||
self.error.clear();
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn ensure_creation_document(&mut self, app: &mut PhotocraftApp) -> Result<(), String> {
|
||||
if !self.creation_reads.staged_new_project {
|
||||
return Ok(());
|
||||
}
|
||||
if self.busy.is_some() {
|
||||
return Err("请等待当前操作完成".into());
|
||||
}
|
||||
let doc_name = non_empty_str(&self.creation_brief["name"]).unwrap_or("未命名详情页").to_owned();
|
||||
app.run("file.new", json!({"name": doc_name, "width": 1440, "height": 1800}))?;
|
||||
let doc_id = app.session.active().map(|state| state.doc.id.0);
|
||||
self.creation_doc = doc_id;
|
||||
self.creation_reads.new_project_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(in crate::jiansun) 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:")
|
||||
&& let Some((code, _)) = rest.split_once(':')
|
||||
{
|
||||
self.creation_reads.expanded_skus.remove(&format!("!{code}"));
|
||||
self.creation_reads.expanded_skus.insert(code.to_owned());
|
||||
for group in normalized_color_groups(&self.creation_brief) {
|
||||
if group.skus.iter().any(|sku| sku.barcode == code) {
|
||||
self.creation_reads.expanded_colors.insert(group.id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn creation_action(&mut self, app: &mut PhotocraftApp, method: &str, mut input: Value) -> Result<Value, String> {
|
||||
let mut method = method;
|
||||
if matches!(method, "creation-catalog" | "creation-thumbnail") {
|
||||
let expected_doc = self.creation_read_doc(app);
|
||||
if input["doc"].as_u64().is_some_and(|id| Some(id) != expected_doc) {
|
||||
return Err("项目已切换".into());
|
||||
}
|
||||
if method == "creation-catalog" {
|
||||
let kind = input["kind"].as_str().ok_or("目录类型无效")?;
|
||||
self.request_creation_catalog(app, kind, input["query"].as_str().unwrap_or("").into(), input["refresh"] == true);
|
||||
} else {
|
||||
let id = input["id"].as_str().filter(|id| !id.is_empty()).ok_or("材质编号无效")?;
|
||||
self.queue_creation_thumbnail(app, id);
|
||||
}
|
||||
return Ok(json!({"submitted":true,"readOnly":true}));
|
||||
}
|
||||
if method == "creation-new" {
|
||||
if self.busy.is_some() {
|
||||
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;
|
||||
self.creation_step = 0;
|
||||
self.library = false;
|
||||
self.material = false;
|
||||
return Ok(json!({"created":true}));
|
||||
}
|
||||
if method == "creation-view" {
|
||||
self.show_creation_step(input["step"].as_u64().unwrap_or(0).min(4) as usize, app.session.active().is_some() || self.creation_reads.staged_new_project);
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
if self.busy.is_some() {
|
||||
return Err("请等待当前操作完成".into());
|
||||
}
|
||||
if method == "creation-product-platform" && !self.account["id"].is_string() {
|
||||
return Err("请先登录素材库账号".into());
|
||||
}
|
||||
if self.unknown && !matches!(method, "creation-recover" | "creation-read" | "creation-load")
|
||||
&& !(method == "creation-save" && self.scoped_production_pending())
|
||||
{
|
||||
return Err("原请求结果待核查,不会重发".into());
|
||||
}
|
||||
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("请先新建项目")?;
|
||||
if input["doc"].as_u64().is_some_and(|id| id != st.doc.id.0) {
|
||||
return Err("项目已切换".into());
|
||||
}
|
||||
input["doc"] = json!(st.doc.id.0);
|
||||
input["baseRevision"] = json!(st.revision);
|
||||
if method == "creation-import" {
|
||||
self.creation_read_scope(app);
|
||||
}
|
||||
if method == "creation-import" && app.session.authorize.is_some() {
|
||||
use base64::Engine as _;
|
||||
let paths = input["paths"].as_array().filter(|a| !a.is_empty() && a.len() <= 8).ok_or("每次最多8张图片")?;
|
||||
let paths = paths.iter().map(|path| path.as_str().filter(|path| !path.is_empty()).map(str::to_owned).ok_or("图片路径无效"))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let read = app.services.automation_read_limited.as_mut().ok_or("自动化导入尚未提供有界读取")?;
|
||||
let mut images = Vec::new();
|
||||
let mut total = 0usize;
|
||||
for path in paths {
|
||||
let limit = (24usize * 1024 * 1024).saturating_sub(total).min(20 * 1024 * 1024);
|
||||
if limit == 0 { return Err("本次产品图片总量超过24MiB".into()); }
|
||||
let (name, bytes) = read(&path, limit)?;
|
||||
if bytes.is_empty() || bytes.len() > limit { return Err("产品图片为空或超过读取上限".into()); }
|
||||
total += bytes.len();
|
||||
images.push(json!({"name":name,"data":base64::engine::general_purpose::STANDARD.encode(bytes)}));
|
||||
}
|
||||
input["images"] = json!(images);
|
||||
input.as_object_mut().ok_or("导入参数无效")?.remove("paths");
|
||||
method = "creation-import-data";
|
||||
}
|
||||
if input["revision"].is_null() {
|
||||
input["revision"] = self.creation["revision"].clone();
|
||||
}
|
||||
if input["brief"].is_null() {
|
||||
input["brief"] = self.brief_with_manual_fields();
|
||||
}
|
||||
if input["width"].is_null() {
|
||||
input["width"] = json!(self.creation_draft_width());
|
||||
}
|
||||
if input["selected"].is_null() {
|
||||
input["selected"] = json!(self.creation_selected);
|
||||
}
|
||||
if input["direction"].is_null() {
|
||||
input["direction"] = json!(self.creation_direction);
|
||||
}
|
||||
if input["screens"].is_null() {
|
||||
input["screens"] = self.creation_plan.clone();
|
||||
}
|
||||
if method == "creation-save" && input.get("deliveryDir").is_none() {
|
||||
input["deliveryDir"] = json!(self.creation_delivery_dir);
|
||||
}
|
||||
if matches!(method, "creation-save" | "creation-facts") {
|
||||
update_detail_barcode(&mut input["brief"]);
|
||||
}
|
||||
input["model"] = json!(self.model);
|
||||
input["imageModel"] = json!(self.image_model);
|
||||
if matches!(method, "creation-generate" | "creation-load") {
|
||||
self.owner_doc = Some(st.doc.id.0);
|
||||
self.expected_revision = st.revision;
|
||||
self.creation_base_revision = st.revision;
|
||||
self.creation_run = None;
|
||||
self.allow_apply = true;
|
||||
self.creation_pending = None;
|
||||
}
|
||||
if matches!(method, "creation-save" | "creation-select" | "creation-plan-edit") {
|
||||
self.creation_submitted_draft = Some(self.creation_draft());
|
||||
}
|
||||
self.send(method, input);
|
||||
Ok(json!({"submitted":self.busy.as_deref()==Some(method)}))
|
||||
}
|
||||
pub(in crate::jiansun) fn creation_submit(&mut self, app: &mut PhotocraftApp, method: &str, input: Value) {
|
||||
if let Err(e) = self.creation_action(app, method, input) {
|
||||
self.error = e;
|
||||
}
|
||||
}
|
||||
pub(in crate::jiansun) fn catalog(&mut self, app: &mut PhotocraftApp, kind: &str, query: String) {
|
||||
self.request_creation_catalog(app, kind, query, false);
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn brief_setup_warning(&self) -> Option<(&'static str, &'static str, &'static str)> {
|
||||
if !self.key_saved {
|
||||
Some(("尚未连接个人 Key,请先配置个人 Key", "个人 Key 未连接", "配置个人 Key"))
|
||||
} else if !(self.model_ready && self.image_ready) {
|
||||
Some(("尚未配置对话或生图模型", "模型未配置", "选择模型"))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn open_brief_setup_settings(&mut self) {
|
||||
self.open_model_settings();
|
||||
if !self.key_saved {
|
||||
self.key_settings = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn save_sku_colors(&mut self, variants: Vec<Value>) {
|
||||
for field in ["skuBindings", "barcodeBindings"] {
|
||||
if let Some(bindings) = self.creation_brief.get_mut(field).and_then(Value::as_object_mut) {
|
||||
if field == "barcodeBindings" && variants.len() == 1 {
|
||||
if let Some(default) = bindings.remove("default") {
|
||||
if let Some(id) = variants[0]["id"].as_str() {
|
||||
bindings.entry(id.to_owned()).or_insert(default);
|
||||
}
|
||||
}
|
||||
}
|
||||
bindings.retain(|id, _| id == "default" || variants.iter().any(|variant| variant["id"] == *id));
|
||||
}
|
||||
}
|
||||
set_brief_variants(&mut self.creation_brief, variants);
|
||||
if !self.creation_brief["outputVariantIds"].is_object() {
|
||||
self.creation_brief["outputVariantIds"] = json!({});
|
||||
}
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn sku_color_removable(&self, variant: &Value) -> bool {
|
||||
variant["images"].as_array().is_none_or(Vec::is_empty)
|
||||
&& !self.template_workflow["variants"].as_array().into_iter().flatten().any(|saved| saved["id"] == variant["id"])
|
||||
&& !["detail", "main_images"].into_iter().any(|key| {
|
||||
self.creation_brief["outputVariantIds"][key].as_array().into_iter().flatten().any(|id| *id == variant["id"])
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn enter_creation_canvas(&mut self, app: &mut PhotocraftApp, template: &Value, generate: bool, refinement: Option<bool>) {
|
||||
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;
|
||||
} else {
|
||||
self.creation_reads.new_project_doc = None;
|
||||
self.creation_open = false;
|
||||
self.creation_step = 3;
|
||||
self.library = false;
|
||||
self.material = false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,312 @@
|
||||
use super::super::{Document, PhotocraftApp, Request, Value, Workspace, json, stitch_ui};
|
||||
use super::brief::{image_rows, merge_platform_barcode_cards, merge_platform_brief_preserving_manual_edits, non_empty_str, saved_creation_draft_brief};
|
||||
use super::form_widgets_ui::spu_field;
|
||||
use super::intake::{add_slot_images, assign_platform_images, fill_platform_intake};
|
||||
|
||||
pub(in crate::jiansun) fn form_editable(busy: Option<&str>, unknown: bool) -> bool {
|
||||
!unknown && (busy.is_none() || matches!(busy, Some("creation-save" | "creation-select" | "creation-plan-edit" | "pi-rules")))
|
||||
}
|
||||
pub(in crate::jiansun) fn bound(w: &Workspace, app: &PhotocraftApp, value: &Value) -> bool {
|
||||
value["accountId"] == w.account["id"] && value["origin"] == w.origin && value["doc"].as_u64() == app.session.active().map(|s| s.doc.id.0)
|
||||
}
|
||||
pub(in crate::jiansun) fn allowed(w: &mut Workspace, app: &PhotocraftApp, value: &Value) -> Result<Value, String> {
|
||||
let run = value["run"].as_str().filter(|s| s.len() == 36).ok_or("生成会话无效")?;
|
||||
let same = bound(w, app, value)
|
||||
&& value["baseRevision"].as_u64() == Some(w.creation_base_revision)
|
||||
&& w.allow_apply
|
||||
&& !w.unknown
|
||||
&& w.busy.as_deref() == Some("creation-generate")
|
||||
&& app.session.active().is_some_and(|s| Some(s.doc.id.0) == w.owner_doc && s.revision == w.expected_revision);
|
||||
if same && w.creation_run.is_none() {
|
||||
w.creation_run = Some(run.into());
|
||||
}
|
||||
Ok(json!({"allowed":same && w.creation_run.as_deref()==Some(run),"revision":w.expected_revision}))
|
||||
}
|
||||
pub(in crate::jiansun) fn canvas_received(w: &mut Workspace, app: &mut PhotocraftApp, mut doc: Box<Document>, value: Value) {
|
||||
if !bound(w, app, &value) {
|
||||
return;
|
||||
}
|
||||
let explicit = value["explicit"] == true;
|
||||
let permitted = w.allow_apply
|
||||
&& app.session.active().is_some_and(|s| Some(s.doc.id.0) == w.owner_doc && s.revision == w.expected_revision)
|
||||
&& (explicit || (value["baseRevision"].as_u64() == Some(w.creation_base_revision) && value["run"].as_str() == w.creation_run.as_deref()));
|
||||
if !permitted {
|
||||
w.creation_pending = Some((doc, value));
|
||||
w.creation_progress = "生成结果已保留,点击载入后继续编辑".into();
|
||||
return;
|
||||
}
|
||||
let Some(id) = app.session.active().map(|s| s.doc.id) else {
|
||||
return;
|
||||
};
|
||||
doc.id = id;
|
||||
let label = if explicit { "载入生成结果".into() } else { format!("生成第 {} 屏", value["sequence"].as_u64().unwrap_or(0) + 1) };
|
||||
match app.session.edit(&label, move |current, selected| {
|
||||
*current = *doc;
|
||||
*selected = None;
|
||||
Ok(())
|
||||
}) {
|
||||
Ok(()) => {
|
||||
app.sync_views();
|
||||
w.expected_revision = app.session.active().map_or(0, |s| s.revision);
|
||||
w.creation = value["creation"].clone();
|
||||
w.creation_pending = None;
|
||||
w.creation_open = false;
|
||||
w.creation_step = 3;
|
||||
w.library = false;
|
||||
w.material = false;
|
||||
w.draft_changed = true;
|
||||
w.sync_dirty = true;
|
||||
if explicit {
|
||||
w.allow_apply = false;
|
||||
}
|
||||
}
|
||||
Err(e) => w.error = e.to_string(),
|
||||
}
|
||||
}
|
||||
pub(in crate::jiansun) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, value: &Value) {
|
||||
if bound(w, app, value) {
|
||||
w.receive_template_snapshot(&value["templateWorkflow"], false);
|
||||
}
|
||||
if !bound(w, app, value) {
|
||||
return;
|
||||
}
|
||||
if method == "creation-progress" {
|
||||
w.creation_progress = value["text"].as_str().unwrap_or("").chars().take(4000).collect();
|
||||
return;
|
||||
}
|
||||
if method == "creation-product-platform" && value["platformBrief"].is_object() {
|
||||
w.creation_read_scope(app);
|
||||
let current = w.brief_with_manual_fields();
|
||||
let incoming = &value["platformBrief"];
|
||||
let current_spu = non_empty_str(¤t["platformFacts"]["spu"])
|
||||
.or_else(|| non_empty_str(¤t["normalizedProduct"]["identity"]["spu"]))
|
||||
.or_else(|| non_empty_str(¤t[spu_field(¤t)]));
|
||||
let merge_existing = current_spu.is_none_or(|spu| incoming["identifier"] == spu);
|
||||
let mut next_brief = incoming.clone();
|
||||
let mut preserved = 0;
|
||||
if merge_existing {
|
||||
let edited = current["manualFields"].as_array().into_iter().flatten()
|
||||
.filter_map(Value::as_str).map(str::to_owned).collect();
|
||||
(next_brief, preserved) = merge_platform_brief_preserving_manual_edits(¤t, incoming, &edited);
|
||||
if let Some(markers) = current.get("manualFields") {
|
||||
next_brief["manualFields"] = markers.clone();
|
||||
}
|
||||
fill_platform_intake(&mut next_brief);
|
||||
merge_platform_barcode_cards(¤t, &mut next_brief, &edited);
|
||||
} else {
|
||||
w.creation_reads.manual_edited_fields.clear();
|
||||
fill_platform_intake(&mut next_brief);
|
||||
}
|
||||
assign_platform_images(&mut next_brief);
|
||||
w.creation_brief = next_brief;
|
||||
w.creation_dirty = true;
|
||||
w.sync_dirty = true;
|
||||
w.draft_changed = true;
|
||||
w.creation_reads.platform_message = value["message"].as_str().unwrap_or("").into();
|
||||
w.creation_reads.platform_sync_note = if preserved > 0 {
|
||||
format!("已重新拉取平台资料,保留了你手动修改的 {preserved} 项字段")
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
return;
|
||||
}
|
||||
if let Some(images) = value["images"].as_array() {
|
||||
if method == "creation-import" {
|
||||
w.match_imported_reference_paths(app, images);
|
||||
}
|
||||
if value["imageSlot"].is_object() {
|
||||
match add_slot_images(&mut w.creation_brief, &value["imageSlot"], images) {
|
||||
Ok(()) => {
|
||||
w.creation_dirty = true;
|
||||
w.sync_dirty = true;
|
||||
}
|
||||
Err(error) => w.creation_reads.reference_import_error = error,
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut current = w.creation_brief["images"].as_array().cloned().unwrap_or_default();
|
||||
let references = image_rows(&w.creation_brief);
|
||||
for image in images {
|
||||
if !references.iter().any(|(existing, _)| existing["source"] == image["source"]) && !current.iter().any(|v| v["source"] == image["source"]) {
|
||||
current.push(image.clone());
|
||||
}
|
||||
}
|
||||
w.creation_brief["images"] = json!(current);
|
||||
w.creation_dirty = true;
|
||||
w.sync_dirty = true;
|
||||
}
|
||||
if value["creation"].is_object() {
|
||||
let newer_draft = if matches!(method, "creation-save" | "creation-select" | "creation-plan-edit") {
|
||||
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);
|
||||
w.creation_read_failed = false;
|
||||
if !w.creation_dirty || !matches!(method, "creation-read" | "creation-import" | "creation-import-data" | "creation-import-library" | "creation-rules") {
|
||||
w.creation_brief = w.creation["brief"].clone();
|
||||
w.creation_dirty = false;
|
||||
w.creation_selected =
|
||||
w.creation["sellingPoints"]["selected"].as_array().map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect()).unwrap_or_default();
|
||||
w.creation_direction = w.creation["sellingPoints"]["direction"].as_str().unwrap_or("").into();
|
||||
w.creation_plan = w.creation["plan"]["screens"].clone();
|
||||
w.creation_width = w.creation["width"].as_u64().unwrap_or_default() as u32;
|
||||
w.creation_delivery_dir = super::product_production::delivery_dir(&w.creation);
|
||||
if method == "creation-save"
|
||||
&& let Some(plan) = edited_plan
|
||||
{
|
||||
w.creation_plan = plan;
|
||||
w.creation_dirty = true;
|
||||
}
|
||||
}
|
||||
if let Some(draft) = newer_draft {
|
||||
w.creation_brief = draft["brief"].clone();
|
||||
w.creation_width = draft["width"].as_u64().unwrap_or_default() as u32;
|
||||
w.creation_delivery_dir = super::product_production::delivery_dir(&draft);
|
||||
w.creation_plan = draft["screens"].clone();
|
||||
w.creation_direction = draft["direction"].as_str().unwrap_or("").into();
|
||||
w.creation_selected = draft["selected"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect();
|
||||
w.creation_dirty = true;
|
||||
}
|
||||
if method == "creation-read" && w.creation_restore_draft.is_object() {
|
||||
let draft = std::mem::take(&mut w.creation_restore_draft);
|
||||
if let Some(brief) = saved_creation_draft_brief(&w.creation, &draft) {
|
||||
w.creation_brief = brief.clone();
|
||||
w.creation_width = draft["width"].as_u64().unwrap_or_default() as u32;
|
||||
if draft["screens"].is_array() {
|
||||
w.creation_plan = draft["screens"].clone();
|
||||
}
|
||||
if let Some(direction) = draft["direction"].as_str() {
|
||||
w.creation_direction = direction.into();
|
||||
}
|
||||
if let Some(selected) = draft["selected"].as_array() {
|
||||
w.creation_selected = selected.iter().filter_map(Value::as_str).take(20).map(str::to_owned).collect();
|
||||
}
|
||||
w.creation_delivery_dir = super::product_production::delivery_dir(&draft);
|
||||
w.creation_dirty = w.creation_brief != w.creation["brief"]
|
||||
|| w.creation_plan != w.creation["plan"]["screens"]
|
||||
|| w.creation_direction != w.creation["sellingPoints"]["direction"].as_str().unwrap_or("")
|
||||
|| w.creation_delivery_dir != super::product_production::delivery_dir(&w.creation);
|
||||
w.restored_creation_signature = w.creation_dirty.then(|| w.creation_draft().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
if method == "creation-read" && !w.creation_dirty && !w.unknown && w.busy.is_none() && value["pending"] != true
|
||||
&& let Some(revision) = value["resumeMaterialDelivery"].as_u64()
|
||||
{
|
||||
w.send("project-sync", json!({"doc":value["doc"],"revision":revision,"status":"completed","resume":true}));
|
||||
}
|
||||
if method == "creation-facts" && value["pending"] != true {
|
||||
w.creation_step = 1;
|
||||
}
|
||||
if method == "creation-plan" && value["pending"] != true {
|
||||
w.creation_step = 2;
|
||||
}
|
||||
if value["pending"] == true {
|
||||
w.unknown = true;
|
||||
w.creation_progress = "原请求待核查".into();
|
||||
} else if method == "creation-recover" {
|
||||
w.unknown = false;
|
||||
}
|
||||
if let Some(message) = value["message"].as_str() {
|
||||
w.creation_progress = message.into();
|
||||
}
|
||||
if method != "creation-read" {
|
||||
w.sync_dirty = true;
|
||||
}
|
||||
if method == "creation-save" {
|
||||
let _ = w.tx.send(Request::Action("pi-rules".into(), json!({"doc":value["doc"]})));
|
||||
}
|
||||
}
|
||||
pub(in crate::jiansun) fn sync_received(w: &mut Workspace, app: &PhotocraftApp, value: &Value) {
|
||||
if !bound(w, app, value) {
|
||||
return;
|
||||
}
|
||||
for key in ["cloudLink", "syncedRevision", "status"] {
|
||||
if !value[key].is_null() {
|
||||
w.project_context[key] = value[key].clone();
|
||||
}
|
||||
}
|
||||
let same = app.session.active().is_some_and(|s| value["revision"].as_u64() == Some(s.revision));
|
||||
w.sync_dirty = !(same && value["syncDirty"] != true && w.sync_request_meta == w.sync_signature());
|
||||
if let Some(items) = value["projects"].as_array() {
|
||||
w.merge_project_receipt(app, items);
|
||||
}
|
||||
if let Some(id) = value["materialDelivery"]["materialId"].as_str() {
|
||||
w.project_context["materialDelivery"] = value["materialDelivery"].clone();
|
||||
w.note(format!("成品已提交素材库,素材 ID:{id}"));
|
||||
w.delivery_completion = true;
|
||||
w.sync_confirm = true;
|
||||
w.listing_read_at = None;
|
||||
w.listing_read_error = None;
|
||||
w.finished_web_error = None;
|
||||
}
|
||||
w.project_refresh_requested = true;
|
||||
w.creation_progress = if value["materialDelivery"]["materialId"].is_string() {
|
||||
"成品已提交素材库"
|
||||
} else if w.sync_dirty { "云端已保存该版本,当前仍有新修改" } else { "已同步" }.into();
|
||||
}
|
||||
pub(in crate::jiansun) fn listing_status_received(w: &mut Workspace, app: &PhotocraftApp, value: &Value) {
|
||||
if !bound(w, app, value) {
|
||||
return;
|
||||
}
|
||||
w.listing_read_error = value["error"].as_str().map(str::to_owned);
|
||||
if let Some(receipt) = value["delivery"].as_object() {
|
||||
if receipt.get("materialId").and_then(Value::as_str).is_none() {
|
||||
return;
|
||||
}
|
||||
let current = &mut w.project_context["materialDelivery"];
|
||||
if current["materialId"] != value["delivery"]["materialId"] {
|
||||
*current = Value::Object(receipt.clone());
|
||||
} else if current["state"] != "removed"
|
||||
&& (value["delivery"]["state"] == "removed"
|
||||
|| value["delivery"]["listingStatus"]["sequence"].as_u64() >= current["listingStatus"]["sequence"].as_u64())
|
||||
{
|
||||
current["state"] = value["delivery"]["state"].clone();
|
||||
current["listingStatus"] = value["delivery"]["listingStatus"].clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn finished_web_received(w: &mut Workspace, app: &PhotocraftApp, value: &Value) {
|
||||
if bound(w, app, value) {
|
||||
w.finished_web_pending = false;
|
||||
w.finished_web_error = value["error"].as_str().map(str::to_owned);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn listing_status_text(receipt: &Value) -> (&'static str, stitch_ui::StatusTone) {
|
||||
use stitch_ui::StatusTone::{Error, Neutral};
|
||||
if receipt["state"] == "removed" {
|
||||
return ("素材已撤回", Neutral);
|
||||
}
|
||||
match receipt["listingStatus"]["state"].as_str() {
|
||||
Some("pending") => ("等待上架", Neutral),
|
||||
Some("listing") => ("上架中", Neutral),
|
||||
Some("listed") => ("已上架", Neutral),
|
||||
Some("failed") => ("上架失败", Error),
|
||||
_ if receipt["state"] == "completed" => ("暂无上架状态", Neutral),
|
||||
_ => ("正在查询上架状态", Neutral),
|
||||
}
|
||||
}
|
||||
|
||||
// The import worker reports a final receipt rather than intermediate bytes;
|
||||
// expose activity only and never manufacture an upload percentage.
|
||||
pub(in crate::jiansun) fn reference_import_activity(busy: Option<&str>) -> Option<&'static str> {
|
||||
match busy {
|
||||
Some("creation-import" | "creation-import-data") => Some("正在导入参考图"),
|
||||
Some("creation-import-library") => Some("正在读取素材库参考图"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,253 @@
|
||||
use super::super::{PhotocraftApp, Ui, Value, Workspace, agent_panel::rect_value, json, stitch_kit, stitch_state::Tone, stitch_ui};
|
||||
use super::REFERENCE_DROP_HINT;
|
||||
use super::form_widgets_ui::{IntakeScope, edit_named_with_error, image_slot, in_image_slot, intake_fields_with_errors, intake_hint, intake_label, material_thumbnail};
|
||||
use super::reducers::form_editable;
|
||||
use super::structure_preview_ui::{reference_folder_paths, reference_image_path};
|
||||
use crate::theme::agent_scale::Type;
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn add_reference_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) -> egui::Rect {
|
||||
self.reference_picker(app, ui, width, egui::Id::unique("creation-reference-drop"), None, Value::Null)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn reference_picker(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32,
|
||||
id: egui::Id, labels: Option<(&str, &str)>, slot: Value,
|
||||
) -> egui::Rect {
|
||||
let supported = ui.input(|input| {
|
||||
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) || (slot.is_null() && files.len() == 1 && path.is_dir())
|
||||
} else {
|
||||
matches!(file.mime.as_str(), "image/png" | "image/jpeg" | "image/webp")
|
||||
}
|
||||
})
|
||||
});
|
||||
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()))
|
||||
.map(|point| to_local * point).filter(|point| ui.clip_rect().contains(*point))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let add_reference = if let Some((label, placeholder)) = labels {
|
||||
stitch_ui::labeled_file_drop_zone(ui, id, width, drop_pointer, enabled, self.reduce_motion, label, Some(placeholder))
|
||||
} else {
|
||||
stitch_ui::file_drop_zone(ui, id, width, drop_pointer, enabled, self.reduce_motion)
|
||||
}
|
||||
.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() {
|
||||
self.open_reference_dialog(app, slot, false);
|
||||
}
|
||||
add_reference.rect
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) 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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn platform_spu_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32, has_synced: bool) {
|
||||
let query_id = scope.with("platform-spu-query");
|
||||
let seed = if self.creation_brief["identifierType"] == "spu" { &self.creation_brief["identifier"] }
|
||||
else { &self.creation_brief["deliverySpu"] };
|
||||
let mut query = ui.data(|data| data.get_temp::<Value>(query_id)).unwrap_or_else(|| seed.clone());
|
||||
let loading = self.busy.as_deref() == Some("creation-product-platform");
|
||||
let logged_in = self.account["id"].is_string();
|
||||
let error = self.creation_reads.inline_errors.get("identifier").cloned();
|
||||
let scroll = self.creation_reads.scroll_to_field.as_deref() == Some("identifier");
|
||||
if scroll {
|
||||
self.creation_reads.scroll_to_field = None;
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let btn_reserve = 128.0;
|
||||
let input_w = if width >= 340.0 { (width - btn_reserve).max(140.0) } else { width };
|
||||
let (edited, resp) = edit_named_with_error(
|
||||
ui,
|
||||
query_id,
|
||||
&mut query,
|
||||
input_w,
|
||||
false,
|
||||
"输入 SPU 型号或条码",
|
||||
"SPU 型号",
|
||||
error.as_deref(),
|
||||
scroll,
|
||||
);
|
||||
if edited {
|
||||
self.creation_reads.inline_errors.remove("identifier");
|
||||
}
|
||||
self.control_geometry("identifier", resp.rect);
|
||||
let spu = query.as_str().unwrap_or("").trim();
|
||||
let btn_label = if loading { "拉取中…" } else if has_synced { "重新拉取" } else { "拉取资料" };
|
||||
let fetch = stitch_ui::action_button(
|
||||
ui,
|
||||
btn_label,
|
||||
stitch_ui::ButtonRole::Secondary,
|
||||
logged_in && form_editable(self.busy.as_deref(), self.unknown) && !spu.is_empty(),
|
||||
);
|
||||
self.control_geometry("platform-fetch", fetch.rect);
|
||||
if loading {
|
||||
stitch_ui::ai_loader(ui, scope.with("platform-fetch-loader"), true, self.reduce_motion);
|
||||
}
|
||||
if fetch.clicked() {
|
||||
self.creation_reads.platform_message.clear();
|
||||
self.creation_reads.platform_sync_note.clear();
|
||||
if let Err(error) = self.creation_action(app, "creation-product-platform", json!({"spu":spu})) {
|
||||
self.creation_reads.platform_message = error;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.data_mut(|data| data.insert_temp(query_id, query));
|
||||
let message = if logged_in { self.creation_reads.platform_message.as_str() } else { "请先登录素材库账号后再拉取产品平台资料" };
|
||||
if !message.is_empty() {
|
||||
stitch_kit::inline_notice(ui, "triangle-alert", Tone::Warning, message, |_| {});
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in crate::jiansun) fn barcode_intake_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, scope: egui::Id, width: f32,
|
||||
code: &str, fields: &[&Value], images: &[&Value],
|
||||
) {
|
||||
let mut values = self.creation_brief["intake"]["barcodeValues"][code].clone();
|
||||
if !values.is_object() { values = json!({}); }
|
||||
if !fields.is_empty() && intake_fields_with_errors(
|
||||
ui, scope, width, fields, IntakeScope::Barcode, &mut values, self.reduce_motion, Some(code),
|
||||
&mut self.creation_reads.inline_errors, &mut self.creation_reads.scroll_to_field,
|
||||
&mut self.creation_reads.manual_edited_fields,
|
||||
) {
|
||||
self.creation_brief["intake"]["barcodeValues"][code] = values;
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
for field in images {
|
||||
self.image_slot_ui(app, ui, width, field, Some(code));
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) 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);
|
||||
self.image_slot_control_ui(app, ui, width, &intake_label(field), intake_hint(field), slot);
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) 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 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);
|
||||
target["placeholder"] = json!(placeholder);
|
||||
self.creation_view_geometry["imageSlots"][key.value().to_string()] = target;
|
||||
}
|
||||
let rows = self.creation_brief["images"].as_array().cloned().unwrap_or_default();
|
||||
let mut remove = None;
|
||||
for (index, image) in rows.iter().enumerate().filter(|(_, image)| in_image_slot(image, &slot)) {
|
||||
let Some(source) = image["source"].as_str() else { continue };
|
||||
self.queue_creation_reference(app, source);
|
||||
let preview_key = super::creation_reads::reference_key(source);
|
||||
ui.horizontal(|ui| {
|
||||
material_thumbnail(ui, self.creation_thumbs.get(&preview_key), self.creation_thumbnail_loading(&preview_key),
|
||||
self.creation_thumbnail_error(&preview_key).is_some());
|
||||
let response = stitch_ui::icon_button(ui, "trash", 28.0, false, "删除图片");
|
||||
if response.clicked() { remove = Some(index); }
|
||||
let name = image["name"].as_str().unwrap_or("图片");
|
||||
ui.add(egui::Label::new(egui::RichText::new(name).font(Type::Meta.font_id())).truncate()).on_hover_text(name);
|
||||
});
|
||||
}
|
||||
if let Some(index) = remove {
|
||||
self.creation_brief["images"] = json!(rows.into_iter().enumerate()
|
||||
.filter_map(|(position, image)| (position != index).then_some(image)).collect::<Vec<_>>());
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn source_picker(&mut self, ui: &mut Ui) {
|
||||
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;
|
||||
}
|
||||
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":[]});
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn reference_drop_geometry(&self, app: &PhotocraftApp, ui: &Ui, rect: egui::Rect) -> Option<Value> {
|
||||
let visible = rect.intersect(ui.clip_rect());
|
||||
if !visible.is_positive() || !visible.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let layer = ui.layer_id();
|
||||
let global = ui.ctx().layer_transform_to_global(layer).unwrap_or_default() * visible;
|
||||
Some(json!({
|
||||
"doc":app.session.active().map(|state| state.doc.id.0),
|
||||
"accountId":self.account["id"],"origin":self.origin,"rect":rect_value(global),
|
||||
"viewport":ui.ctx().viewport_id().0.value(),"layer":layer.id.value(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn references_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) {
|
||||
let gallery = ui.scope(|ui| self.visual_assets_gallery_ui(app, ui, width));
|
||||
if gallery.inner {
|
||||
if let Some(target) = self.reference_drop_geometry(app, ui, gallery.response.rect) {
|
||||
self.creation_view_geometry["referenceDrop"] = target;
|
||||
}
|
||||
} else {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,87 @@
|
||||
use super::super::Value;
|
||||
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(in crate::jiansun) struct ReviewHintItem {
|
||||
pub(in crate::jiansun) message: String,
|
||||
pub(in crate::jiansun) output_id: Option<String>,
|
||||
pub(in crate::jiansun) variant_id: Option<String>,
|
||||
pub(in crate::jiansun) slot_id: Option<String>,
|
||||
pub(in crate::jiansun) layer_id: Option<String>,
|
||||
}
|
||||
|
||||
impl ReviewHintItem {
|
||||
pub(in crate::jiansun) fn has_target(&self) -> bool {
|
||||
self.output_id.is_some() || self.slot_id.is_some() || self.layer_id.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn infer_review_hint_output_id(message: &str) -> Option<String> {
|
||||
if message.starts_with("详情页:") {
|
||||
Some("detail".to_owned())
|
||||
} else if message.starts_with("主图:") {
|
||||
Some("main_images".to_owned())
|
||||
} else if message.starts_with("SKU 图:") || message.starts_with("SKU:") {
|
||||
Some("sku_images".to_owned())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn parse_review_hints(value: &Value, out: &mut Vec<ReviewHintItem>) {
|
||||
let Some(items) = value.as_array() else { return };
|
||||
for entry in items {
|
||||
let item = if let Some(text) = entry.as_str().map(str::trim).filter(|s| !s.is_empty()) {
|
||||
ReviewHintItem {
|
||||
message: text.to_owned(),
|
||||
output_id: infer_review_hint_output_id(text),
|
||||
variant_id: None,
|
||||
slot_id: None,
|
||||
layer_id: None,
|
||||
}
|
||||
} else if let Some(obj) = entry.as_object() {
|
||||
let Some(message) = obj
|
||||
.get("message")
|
||||
.or_else(|| obj.get("text"))
|
||||
.or_else(|| obj.get("hint"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let output_id = obj
|
||||
.get("outputId")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| infer_review_hint_output_id(message));
|
||||
let slot_id = obj
|
||||
.get("slotId")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned);
|
||||
let layer_id = obj
|
||||
.get("layerId")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned);
|
||||
ReviewHintItem {
|
||||
message: message.to_owned(),
|
||||
output_id,
|
||||
variant_id: obj.get("variantId").and_then(Value::as_str).map(str::to_owned),
|
||||
slot_id,
|
||||
layer_id,
|
||||
}
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if !out.contains(&item) {
|
||||
out.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,276 @@
|
||||
use super::super::{PhotocraftApp, Tokens, Ui, Value, json, stitch_kit, stitch_state::Tone};
|
||||
use super::{REFERENCE_DROP_HINT, WIZARD_WIDTH};
|
||||
use super::brief::template_identity;
|
||||
use super::form_widgets_ui::{current_image_slot, preview_size};
|
||||
use crate::theme::{AGENT_SEMANTIC, agent_scale::{Type, icon, radius, space}};
|
||||
use egui::vec2;
|
||||
|
||||
pub(in crate::jiansun) 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);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) fn preview_frame(value: &Value, width: f64, height: f64, line: bool) -> Option<[f32; 4]> {
|
||||
let (x, y, w, h) = (value["x"].as_f64()?, value["y"].as_f64()?, value["width"].as_f64()?, value["height"].as_f64()?);
|
||||
if ![x, y, w, h].iter().all(|n| n.is_finite()) || x < 0.0 || y < 0.0 || w <= 0.0 || h < 0.0 || (!line && h == 0.0)
|
||||
|| x + w > width + 0.01 || y + h > height + 0.01 { return None; }
|
||||
Some([x as f32, y as f32, w as f32, h as f32])
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn preview_color(value: &Value) -> Option<egui::Color32> {
|
||||
let value = value.as_str()?;
|
||||
if value.len() != 7 || !value.starts_with('#') || !value[1..].bytes().all(|b| b.is_ascii_hexdigit()) { return None; }
|
||||
let n = u32::from_str_radix(&value[1..], 16).ok()?;
|
||||
Some(egui::Color32::from_rgb((n >> 16) as u8, (n >> 8) as u8, n as u8))
|
||||
}
|
||||
|
||||
/// Only accept a geometry preview attached to the exact selected immutable
|
||||
/// package and current brand/category. It is never a product photograph.
|
||||
pub(in crate::jiansun) fn verified_structure_preview<'a>(row: &'a Value, selected: &Value, brand: &str, category: &str) -> Option<&'a Value> {
|
||||
if brand.is_empty() || category.is_empty() || row["brandId"] != brand || row["categoryId"] != category
|
||||
|| row["id"] != selected["id"] || row["version"] != selected["version"] || row["contentHash"] != selected["contentHash"]
|
||||
|| !template_identity(row) { return None; }
|
||||
let preview = &row["structurePreview"];
|
||||
if preview["contentHash"] != row["contentHash"] || preview["outputId"].as_str().is_none_or(str::is_empty) { return None; }
|
||||
let width = preview["width"].as_f64()?;
|
||||
let height = preview["height"].as_f64()?;
|
||||
if !matches!(preview["width"].as_u64(), Some(750 | 1440)) || !height.is_finite() || !(1.0..=30_000.0).contains(&height)
|
||||
|| (!preview["background"].is_null() && preview_color(&preview["background"]).is_none()) { return None; }
|
||||
let slots = preview["slots"].as_array().filter(|items| !items.is_empty() && items.len() <= 120)?;
|
||||
if slots.iter().any(|slot| !matches!(slot["kind"].as_str(), Some("image" | "text")) || preview_frame(&slot["frame"], width, height, false).is_none()) { return None; }
|
||||
let decorations = preview["decorations"].as_array().filter(|items| items.len() <= 120)?;
|
||||
if decorations.iter().any(|item| {
|
||||
let kind = item["kind"].as_str();
|
||||
!matches!(kind, Some("rect" | "line")) || preview_frame(&item["frame"], width, height, kind == Some("line")).is_none()
|
||||
|| preview_color(&item["color"]).is_none() || !item["opacity"].as_f64().is_some_and(|n| n.is_finite() && (0.0..=1.0).contains(&n))
|
||||
}) { return None; }
|
||||
Some(preview)
|
||||
}
|
||||
|
||||
/// Paint only validated template geometry. This is a structural diagram,
|
||||
/// never a substitute for an authorized template cover photograph.
|
||||
pub(in crate::jiansun) fn paint_template_structure(ui: &Ui, preview: &Value, area: egui::Rect) {
|
||||
let width = preview["width"].as_f64().unwrap_or(1.0) as f32;
|
||||
let height = preview["height"].as_f64().unwrap_or(1.0) as f32;
|
||||
let scale = (area.width() / width).min(area.height() / height);
|
||||
let page = egui::Rect::from_center_size(area.center(), vec2(width * scale, height * scale));
|
||||
let painter = ui.painter().with_clip_rect(page);
|
||||
painter.rect_filled(page, 2.0, preview_color(&preview["background"]).unwrap_or(egui::Color32::WHITE));
|
||||
let paint_frame = |frame: [f32; 4]| egui::Rect::from_min_size(page.min + vec2(frame[0] * scale, frame[1] * scale), vec2(frame[2] * scale, frame[3] * scale));
|
||||
let decorations = |above: bool| {
|
||||
for item in preview["decorations"].as_array().into_iter().flatten().filter(|item| (item["aboveImages"] == true) == above) {
|
||||
if let (Some(frame), Some(color), Some(opacity)) = (preview_frame(&item["frame"], width as f64, height as f64, item["kind"] == "line"), preview_color(&item["color"]), item["opacity"].as_f64()) {
|
||||
let rect = paint_frame(frame);
|
||||
let color = color.gamma_multiply(opacity as f32);
|
||||
if item["kind"] == "line" { painter.line_segment([rect.left_top(), rect.right_bottom()], egui::Stroke::new(1.0, color)); }
|
||||
else { painter.rect_filled(rect, 0, color); }
|
||||
}
|
||||
}
|
||||
};
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
decorations(false);
|
||||
for slot in preview["slots"].as_array().into_iter().flatten().filter(|slot| slot["kind"] == "image") {
|
||||
if let Some(frame) = preview_frame(&slot["frame"], width as f64, height as f64, false) { painter.rect_filled(paint_frame(frame), 0, t.text_dim); }
|
||||
}
|
||||
decorations(true);
|
||||
for slot in preview["slots"].as_array().into_iter().flatten().filter(|slot| slot["kind"] == "text") {
|
||||
if let Some(frame) = preview_frame(&slot["frame"], width as f64, height as f64, false) {
|
||||
let rect = paint_frame(frame);
|
||||
painter.rect_stroke(rect, 0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn structure_preview_card(
|
||||
ui: &mut Ui,
|
||||
preview: Option<&Value>,
|
||||
cover: Option<&egui::TextureHandle>,
|
||||
name: &str,
|
||||
version: &str,
|
||||
screen_count: Option<usize>,
|
||||
canvas_width: u32,
|
||||
status: Option<&str>,
|
||||
) {
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = space::MD;
|
||||
let thumb_size = if cover.is_some() || preview.is_some() { vec2(136.0, 184.0) } else { vec2(96.0, 128.0) };
|
||||
let (area, _) = ui.allocate_exact_size(thumb_size, egui::Sense::hover());
|
||||
ui.painter().rect_filled(area, radius::CONTROL, t.dock);
|
||||
ui.painter().rect_stroke(area, radius::CONTROL, 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(4.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(4.0));
|
||||
} else {
|
||||
crate::icons::paint(ui, area.translate(vec2(0.0, -10.0)), "layers", icon::LG, t.text_dim);
|
||||
ui.painter().text(
|
||||
egui::pos2(area.center().x, area.center().y + 18.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
"暂无预览图",
|
||||
Type::Meta.font_id(),
|
||||
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, "首屏结构示意");
|
||||
} else {
|
||||
stitch_kit::caption(ui, "模板已就绪(当前组件未附带预览图)");
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn drop_contains(value: &Value, point: egui::Pos2) -> bool {
|
||||
let Some(values) = value.as_array()
|
||||
.filter(|rect| rect.len() == 4)
|
||||
.and_then(|rect| rect.iter().map(Value::as_f64).collect::<Option<Vec<_>>>()) else { return false };
|
||||
values.iter().all(|value| value.is_finite()) && values[2] > 0.0 && values[3] > 0.0
|
||||
&& egui::Rect::from_min_size(
|
||||
egui::pos2(values[0] as f32, values[1] as f32),
|
||||
vec2(values[2] as f32, values[3] as f32),
|
||||
).contains(point)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn reference_image_path(path: &std::path::Path) -> bool {
|
||||
path.extension().and_then(|ext| ext.to_str())
|
||||
.is_some_and(|ext| ["png", "jpg", "jpeg", "webp"].iter().any(|allowed| ext.eq_ignore_ascii_case(allowed)))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn reference_folder_paths(folder: &std::path::Path) -> Result<Vec<String>, 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<egui::Pos2>,
|
||||
) -> bool {
|
||||
if self.file_dialog_open() {
|
||||
return false;
|
||||
}
|
||||
let product_form_open = super::product_form_open(self);
|
||||
let Some(w) = self.jiansun.as_mut() else { return false };
|
||||
let staged = w.creation_reads.staged_new_project && w.creation_open
|
||||
&& w.creation_step == 0 && !w.library && !w.material;
|
||||
if !product_form_open && !staged {
|
||||
return false;
|
||||
}
|
||||
let doc = self.session.active().map(|state| state.doc.id.0);
|
||||
let target = at.and_then(|at| {
|
||||
let layer = ctx.layer_id_at(at);
|
||||
w.creation_view_geometry["imageSlots"].as_object().into_iter().flat_map(|slots| slots.values())
|
||||
.chain(std::iter::once(&w.creation_view_geometry["referenceDrop"]))
|
||||
.find(|target| target["doc"] == json!(doc) && target["accountId"] == w.account["id"]
|
||||
&& target["origin"] == w.origin && target["viewport"].as_u64() == Some(ctx.viewport_id().0.value())
|
||||
&& drop_contains(&target["rect"], at)
|
||||
&& layer.is_none_or(|layer| layer.order == egui::Order::Background
|
||||
|| target["layer"].as_u64() == Some(layer.id.value())))
|
||||
});
|
||||
let Some(target) = target else {
|
||||
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();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
let slot = target["slot"].clone();
|
||||
let reject = if (!staged && w.creation_doc != doc) || w.busy.is_some() {
|
||||
Some("请等待当前操作完成,再添加参考图")
|
||||
} else if w.unknown {
|
||||
Some("原请求结果待核查,请先核查后再添加参考图")
|
||||
} else if slot["multiple"] == false && files.len() != 1 {
|
||||
Some("此图片框一次只能添加一张图片")
|
||||
} else if files.is_empty() || files.len() > 8 {
|
||||
Some("每次请选择 1 至 8 张参考图片")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(error) = reject {
|
||||
w.creation_reads.reference_import_error = error.into();
|
||||
return true;
|
||||
}
|
||||
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::<Option<Vec<_>>>().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()
|
||||
{
|
||||
w.creation_reads.reference_import_error = error;
|
||||
}
|
||||
true
|
||||
}
|
||||
pub(in crate::jiansun) fn import_reference_paths(&mut self, paths: Vec<String>, slot: Value) -> Result<Value, String> {
|
||||
let native = self.session.authorize.is_none();
|
||||
if slot.is_object() && self.jiansun.as_ref().is_none_or(|w| !current_image_slot(&w.creation_brief, &slot)) {
|
||||
return Err("图片框已变化,请重新选择".into());
|
||||
}
|
||||
let result = super::action(self, "creation-import", json!({"paths":paths,"imageSlot":slot}))?;
|
||||
if let Some(w) = self.jiansun.as_mut() {
|
||||
w.creation_reads.reference_import_error.clear();
|
||||
if native && result["submitted"] == true {
|
||||
w.creation_reads.reference_import_paths = Some(paths);
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,265 @@
|
||||
use super::super::{Duration, PhotocraftApp, Ui, Value, Workspace, agent_panel::rect_value, json, stitch_ui};
|
||||
use super::PICKER_HEIGHT;
|
||||
use super::brief::{brief_variants, variant_identity};
|
||||
use super::form_widgets_ui::{MaterialSearchPending, material_search_due, material_thumbnail, picker, picker_height, picker_notice, picker_row, picker_toggle_row};
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn brand_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) {
|
||||
let rows = self.creation_catalog.get("brands").cloned().unwrap_or_default();
|
||||
let selected = self.creation_brief["brandName"].as_str().filter(|s| !s.is_empty()).unwrap_or("选择品牌").to_owned();
|
||||
let mut geometry = Vec::new();
|
||||
let result = picker(ui, "creation-brand", width, &selected, |ui| {
|
||||
if !self.creation_catalog.contains_key("brands") && !self.creation_catalog_loading("brands") && self.creation_catalog_error("brands").is_none() {
|
||||
self.catalog(app, "brands", String::new());
|
||||
}
|
||||
let error = self.creation_catalog_error("brands").map(str::to_owned);
|
||||
if picker_notice(ui, self.creation_catalog_loading("brands"), error.as_deref(), rows.is_empty(), "暂无品牌") {
|
||||
self.catalog(app, "brands", String::new());
|
||||
}
|
||||
for row in &rows {
|
||||
let ready = row["ready"] == true;
|
||||
let suffix = if !ready { " · 待配置" } else if row["templateCount"].as_u64() == Some(0) { " · 暂无可用模板" } else { "" };
|
||||
let label = format!("{}{suffix}", row["name"].as_str().unwrap_or(""));
|
||||
let response = picker_row(ui, self.creation_brief["brandName"] == row["name"], &label, ready);
|
||||
geometry.push(json!({"id":row["id"],"label":label,"ready":ready,"rect":rect_value(response.rect)}));
|
||||
if response.clicked() {
|
||||
if self.creation_brief["brandName"] == row["name"] {
|
||||
ui.close();
|
||||
continue;
|
||||
}
|
||||
self.creation_brief["brandId"] = row["id"].clone();
|
||||
self.creation_brief["brandName"] = row["name"].clone();
|
||||
self.creation_brief["categoryId"] = json!("");
|
||||
self.creation_brief["categoryName"] = json!("");
|
||||
self.agent_rule = Value::Null;
|
||||
self.agent_rule_state = Value::Null;
|
||||
if let Some(fields) = self.creation_brief.as_object_mut() { fields.remove("intake"); }
|
||||
self.creation_brief["templateSelection"] = Value::Null;
|
||||
self.creation_catalog.remove("templates");
|
||||
self.creation_catalog.remove("categories");
|
||||
self.catalog(app, "categories", String::new());
|
||||
self.creation_reads.inline_errors.remove("brand");
|
||||
self.creation_reads.manual_edited_fields.insert("brand".into());
|
||||
self.creation_dirty = true;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
if result.response.clicked() && result.inner.is_some() {
|
||||
self.catalog(app, "brands", String::new());
|
||||
}
|
||||
if self.creation_reads.scroll_to_field.as_deref() == Some("brand") {
|
||||
self.creation_reads.scroll_to_field = None;
|
||||
result.response.scroll_to_me(Some(egui::Align::Center));
|
||||
result.response.request_focus();
|
||||
}
|
||||
let loading = self.creation_catalog_loading("brands");
|
||||
self.picker_geometry(ui, "brand", &result.response, loading, !rows.is_empty() && !loading && self.creation_catalog_error("brands").is_none(), geometry);
|
||||
if let Some(err) = self.creation_reads.inline_errors.get("brand") {
|
||||
stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error);
|
||||
}
|
||||
}
|
||||
pub(in crate::jiansun) fn category_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) {
|
||||
let brand = self.creation_brief["brandId"].as_str().unwrap_or("").to_owned();
|
||||
let rows = self.creation_catalog.get("categories").cloned().unwrap_or_default().into_iter().filter(|row| row["brandId"] == brand).collect::<Vec<_>>();
|
||||
let selected = self.creation_brief["categoryName"]
|
||||
.as_str()
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or(if brand.is_empty() { "先选择品牌" } else { "选择品类" })
|
||||
.to_owned();
|
||||
let mut geometry = Vec::new();
|
||||
let loading = self.creation_catalog_loading("categories");
|
||||
let result = picker(ui, "creation-category", width, &selected, |ui| {
|
||||
if brand.is_empty() {
|
||||
ui.weak("先选择品牌");
|
||||
} else {
|
||||
if !self.creation_catalog.contains_key("categories") && !loading && self.creation_catalog_error("categories").is_none() {
|
||||
self.catalog(app, "categories", String::new());
|
||||
}
|
||||
let error = self.creation_catalog_error("categories").map(str::to_owned);
|
||||
if picker_notice(ui, loading, error.as_deref(), rows.is_empty(), "暂无已登记的产品品类") {
|
||||
self.catalog(app, "categories", String::new());
|
||||
}
|
||||
}
|
||||
for row in &rows {
|
||||
let ready = row["ready"] == true;
|
||||
let name = row["name"].as_str().unwrap_or("");
|
||||
let label = if ready { name.to_owned() } else { format!("{name} · 待配置") };
|
||||
let response = picker_row(ui, self.creation_brief["categoryName"] == row["name"], &label, ready).on_hover_text(if ready {
|
||||
if row["templateCount"].as_u64() == Some(0) { "知识库已有此品类资料,当前暂无可用模板" } else { "使用该品牌与品类的项目模板" }
|
||||
} else {
|
||||
"此品牌尚未配置该品类模板"
|
||||
});
|
||||
geometry.push(json!({"id":row["id"],"label":label,"ready":ready,"rect":rect_value(response.rect)}));
|
||||
if response.clicked() {
|
||||
if self.creation_brief["categoryName"] == row["name"] {
|
||||
ui.close();
|
||||
continue;
|
||||
}
|
||||
self.creation_brief["categoryId"] = row["id"].clone();
|
||||
self.creation_brief["categoryName"] = row["name"].clone();
|
||||
self.agent_rule = Value::Null;
|
||||
self.agent_rule_state = Value::Null;
|
||||
if let Some(fields) = self.creation_brief.as_object_mut() { fields.remove("intake"); }
|
||||
self.creation_brief["templateSelection"] = Value::Null;
|
||||
self.creation_catalog.remove("templates");
|
||||
self.creation_reads.inline_errors.remove("category");
|
||||
self.creation_reads.manual_edited_fields.insert("category".into());
|
||||
self.creation_dirty = true;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
if result.response.clicked() && result.inner.is_some() && !brand.is_empty() {
|
||||
self.catalog(app, "categories", String::new());
|
||||
}
|
||||
if self.creation_reads.scroll_to_field.as_deref() == Some("category") {
|
||||
self.creation_reads.scroll_to_field = None;
|
||||
result.response.scroll_to_me(Some(egui::Align::Center));
|
||||
result.response.request_focus();
|
||||
}
|
||||
self.picker_geometry(ui, "category", &result.response, loading, !rows.is_empty() && !loading, geometry);
|
||||
if let Some(err) = self.creation_reads.inline_errors.get("category") {
|
||||
stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error);
|
||||
}
|
||||
}
|
||||
pub(in crate::jiansun) fn material_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) {
|
||||
let rows = self.creation_catalog.get("materials").cloned().unwrap_or_default();
|
||||
let mut variants = brief_variants(&self.creation_brief);
|
||||
let selected = match variants.as_slice() {
|
||||
[] => "从材质库选择,可多选".to_owned(),
|
||||
[only] => only["name"].as_str().unwrap_or("花色").to_owned(),
|
||||
rows => format!("已选 {} 个花色", rows.len()),
|
||||
};
|
||||
let mut geometry = Vec::new();
|
||||
let mut material_rows = Vec::new();
|
||||
let result = picker_height(ui, "creation-material", width, PICKER_HEIGHT, &selected, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| {
|
||||
if !self.creation_catalog.contains_key("materials")
|
||||
&& !self.creation_catalog_loading("materials")
|
||||
&& self.creation_catalog_error("materials").is_none()
|
||||
{
|
||||
self.catalog(app, "materials", String::new());
|
||||
}
|
||||
let search = stitch_ui::search_field(ui, ui.scope_id().with("creation-material-search"), &mut self.creation_material_query, "搜索材质");
|
||||
let now = ui.input(|input| input.time);
|
||||
let enter = search.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)
|
||||
&& !input.events.iter().any(|event| matches!(event, egui::Event::Ime(_))));
|
||||
let state_id = ui.scope_id().with("creation-material-search-pending");
|
||||
let (due, pending) = ui.data_mut(|data| {
|
||||
let state = data.get_temp_mut_or_default::<MaterialSearchPending>(state_id);
|
||||
let due = material_search_due(state, &self.creation_material_query, search.changed(), enter, now);
|
||||
(due, state.pending)
|
||||
});
|
||||
if pending { ui.ctx().request_repaint_after(Duration::from_millis(50)); }
|
||||
if due {
|
||||
self.catalog(app, "materials", self.creation_material_query.clone());
|
||||
}
|
||||
let error = self.creation_catalog_error("materials").map(str::to_owned);
|
||||
if picker_notice(ui, self.creation_catalog_loading("materials"), error.as_deref(), rows.is_empty(), "暂无匹配材质") {
|
||||
self.catalog(app, "materials", self.creation_material_query.clone());
|
||||
}
|
||||
let removable = variants.iter().all(|variant| self.sku_color_removable(variant));
|
||||
if picker_row(ui, variants.is_empty(), "未指定", removable).on_hover_text("已用于详情图、主图或已有画布的颜色会保留").clicked() {
|
||||
variants.clear();
|
||||
self.save_sku_colors(variants.clone());
|
||||
ui.close();
|
||||
}
|
||||
for row in &rows {
|
||||
let Some(id) = row["id"].as_str().filter(|id| !id.is_empty()) else { continue };
|
||||
let label = row["name"].as_str().unwrap_or("");
|
||||
let image = self.creation_thumbs.get(id).cloned();
|
||||
let error = self.creation_thumbnail_error(id).map(str::to_owned);
|
||||
let loading = self.creation_thumbnail_loading(id);
|
||||
let mut image_rect = egui::Rect::NOTHING;
|
||||
let mut visible = false;
|
||||
let line = ui.horizontal(|ui| {
|
||||
let thumbnail = material_thumbnail(ui, image.as_ref(), loading, error.is_some());
|
||||
image_rect = thumbnail.rect;
|
||||
visible = ui.is_rect_visible(image_rect);
|
||||
if visible && image.is_none() && !loading && error.is_none() {
|
||||
self.queue_creation_thumbnail(app, id);
|
||||
}
|
||||
if let Some(error) = error.as_deref() {
|
||||
let msg = crate::client_brand::user_error(error, "缩略图读取失败");
|
||||
if thumbnail.on_hover_text(format!("{msg}\n点击重新读取")).clicked() {
|
||||
self.retry_creation_thumbnail(app, id);
|
||||
}
|
||||
} else if let Some(image) = image.as_ref() {
|
||||
self.material_preview(thumbnail, id, label, image);
|
||||
}
|
||||
let selected = variants.iter().find(|variant| variant["colorMaterialId"] == row["id"]);
|
||||
let removable = selected.is_none_or(|variant| self.sku_color_removable(variant));
|
||||
let selected = selected.is_some();
|
||||
let can_select = removable && (selected || variants.len() < 64);
|
||||
let response = picker_toggle_row(ui, selected, label, can_select);
|
||||
let response = if !selected && variants.len() >= 64 {
|
||||
response.on_hover_text("最多选择 64 个花色")
|
||||
} else if !removable {
|
||||
response.on_hover_text("已用于出图、画布或专属参考的颜色会保留")
|
||||
} else { response };
|
||||
if response.clicked() {
|
||||
if selected {
|
||||
variants.retain(|variant| variant["colorMaterialId"] != row["id"]);
|
||||
} else {
|
||||
variants
|
||||
.push(json!({"id":variant_identity(id),"name":row["name"],"colorMaterialId":row["id"],"colorName":row["name"],"images":[]}));
|
||||
}
|
||||
self.save_sku_colors(variants.clone());
|
||||
}
|
||||
if let Some(image) = image.as_ref() {
|
||||
self.material_preview(response, id, label, image);
|
||||
}
|
||||
});
|
||||
let status = if image.is_some() {
|
||||
"ready"
|
||||
} else if self.creation_thumbnail_error(id).is_some() {
|
||||
"failed"
|
||||
} else if self.creation_thumbnail_loading(id) {
|
||||
"loading"
|
||||
} else {
|
||||
"queued"
|
||||
};
|
||||
geometry.push(json!({"id":id,"label":label,"ready":true,"rect":rect_value(line.response.rect)}));
|
||||
material_rows.push(
|
||||
json!({"id":id,"label":label,"rect":rect_value(line.response.rect),"imageRect":rect_value(image_rect),"status":status,"visible":visible}),
|
||||
);
|
||||
}
|
||||
});
|
||||
self.creation_view_geometry["materialRows"] = json!(material_rows);
|
||||
let loading = self.creation_catalog_loading("materials");
|
||||
self.picker_geometry(
|
||||
ui,
|
||||
"material",
|
||||
&result.response,
|
||||
loading,
|
||||
!rows.is_empty() && !loading && self.creation_catalog_error("materials").is_none(),
|
||||
geometry,
|
||||
);
|
||||
}
|
||||
pub(in crate::jiansun) fn product_search_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
let identifier = self.creation_brief["identifier"].as_str().unwrap_or_default();
|
||||
let label = if self.creation_brief["identifierType"] == "spu" { "按 SPU 查找" } else { "查找原项目产品" };
|
||||
let search = stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Secondary, !identifier.trim().is_empty());
|
||||
if search.clicked() {
|
||||
self.catalog(app, "products", identifier.to_owned());
|
||||
}
|
||||
self.control_geometry("source-search", search.rect);
|
||||
}
|
||||
pub(in crate::jiansun) fn product_select_results(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
let rows = self.creation_catalog.get("products").cloned().unwrap_or_default();
|
||||
let error = self.creation_catalog_error("products").map(str::to_owned);
|
||||
if (self.creation_catalog.contains_key("products") || self.creation_catalog_loading("products") || error.is_some())
|
||||
&& picker_notice(ui, self.creation_catalog_loading("products"), error.as_deref(), rows.is_empty(), "未找到匹配产品,请核对产品编号")
|
||||
{
|
||||
self.catalog(app, "products", self.creation_brief["identifier"].as_str().unwrap_or("").into());
|
||||
}
|
||||
for (index, row) in rows.into_iter().enumerate() {
|
||||
let title = row["productModel"].as_str().or_else(|| row["name"].as_str()).unwrap_or("产品资料");
|
||||
let result = stitch_ui::button(ui, title, false);
|
||||
self.control_geometry(&format!("source-result-{index}"), result.rect);
|
||||
if result.clicked() {
|
||||
self.creation_submit(app, "creation-product", json!({"item":row}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,461 @@
|
||||
use super::super::{PhotocraftApp, Request, Ui, Value, Workspace, agent_panel::rect_value, json, stitch_kit, stitch_ui};
|
||||
use super::super::creation_reads::wizard;
|
||||
use super::PICKER_HEIGHT;
|
||||
use super::brief::{default_resource_component, selected_template, template_compatibility_warnings, template_identity};
|
||||
use super::form_widgets_ui::{picker, picker_height, picker_notice, template_picker_row};
|
||||
use super::intake::set_intake;
|
||||
use super::structure_preview_ui::{structure_preview_card, verified_structure_preview};
|
||||
use crate::theme::agent_scale::{control, space};
|
||||
use egui::vec2;
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn resource_template_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, selected: &Value, brand: &str, category: &str) {
|
||||
let bound = |row: &Value| row["brandId"] == brand && row["categoryId"] == category;
|
||||
if !bound(&self.creation_reads.resource_set) {
|
||||
self.creation_reads.resource_set = Value::Null;
|
||||
self.creation_reads.resource_component.clear();
|
||||
self.creation_catalog.remove("resource-set");
|
||||
self.creation_catalog.remove("resource-component");
|
||||
}
|
||||
let rows = self.creation_catalog.get("templates").into_iter().flatten().filter(|row| bound(row)).cloned().collect::<Vec<_>>();
|
||||
if !brand.is_empty() && !category.is_empty()
|
||||
&& !self.creation_catalog.contains_key("templates") && !self.creation_catalog_loading("templates") && self.creation_catalog_error("templates").is_none()
|
||||
{
|
||||
self.catalog(app, "templates", String::new());
|
||||
}
|
||||
let label = self.creation_reads.resource_set["name"].as_str().or(selected["name"].as_str()).unwrap_or("选择模板").to_owned();
|
||||
let mut geometry = Vec::new();
|
||||
let response = picker_height(ui, "creation-template", width, PICKER_HEIGHT,
|
||||
&label, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| {
|
||||
if brand.is_empty() || category.is_empty() {
|
||||
ui.weak("先选择品牌与品类");
|
||||
return;
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let query = ui.add_sized([(ui.available_width() - 68.0).max(80.0), 28.0],
|
||||
egui::TextEdit::singleline(&mut self.creation_reads.resource_query).hint_text("模板名称或编号").char_limit(120));
|
||||
if stitch_ui::button(ui, "搜索", false).clicked() || query.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
|
||||
self.creation_catalog.remove("templates");
|
||||
self.catalog(app, "templates", self.creation_reads.resource_query.clone());
|
||||
}
|
||||
});
|
||||
let error = self.creation_catalog_error("templates").map(str::to_owned);
|
||||
if picker_notice(ui, self.creation_catalog_loading("templates"), error.as_deref(), rows.is_empty(), "当前筛选没有模板") {
|
||||
self.catalog(app, "templates", self.creation_reads.resource_query.clone());
|
||||
}
|
||||
for row in &rows {
|
||||
let active = self.creation_reads.resource_set["id"] == row["id"];
|
||||
let text = format!("{} · {}", row["name"].as_str().unwrap_or("模板"), row["key"].as_str().unwrap_or(""));
|
||||
let ready = !self.creation_catalog_loading("templates");
|
||||
let item = template_picker_row(ui, active, &text, ready, None);
|
||||
geometry.push(json!({"id":row["id"],"key":row["key"],"ready":ready,"rect":rect_value(item.rect)}));
|
||||
if item.clicked() {
|
||||
ui.close();
|
||||
if active {
|
||||
continue;
|
||||
}
|
||||
set_intake(&mut self.creation_brief, &row["id"], &row["intake"]);
|
||||
self.creation_reads.resource_set = row.clone();
|
||||
self.creation_reads.resource_component.clear();
|
||||
self.creation_reads.resource_image = None;
|
||||
self.creation_brief["templateSelection"] = Value::Null;
|
||||
self.creation_reads.inline_errors.remove("template");
|
||||
self.creation_dirty = true;
|
||||
self.creation_catalog.remove("resource-set");
|
||||
self.creation_catalog.remove("resource-component");
|
||||
self.catalog(app, "resource-set", row["id"].as_str().unwrap_or("").into());
|
||||
}
|
||||
}
|
||||
}).response;
|
||||
if self.creation_reads.scroll_to_field.as_deref() == Some("template") {
|
||||
self.creation_reads.scroll_to_field = None;
|
||||
response.scroll_to_me(Some(egui::Align::Center));
|
||||
response.request_focus();
|
||||
}
|
||||
self.picker_geometry(ui, "template", &response, self.creation_catalog_loading("templates"), !rows.is_empty(), geometry);
|
||||
if let Some(err) = self.creation_reads.inline_errors.get("template") {
|
||||
stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error);
|
||||
}
|
||||
if let Some(error) = self.creation_catalog_error("templates") {
|
||||
stitch_ui::status_label(ui, error, stitch_ui::StatusTone::Error);
|
||||
}
|
||||
if let Some(progress) = self.resource_progress() {
|
||||
let wait = progress["retryAfterSeconds"].as_u64();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if let Some(seconds) = wait { ui.label(format!("知识库访问受限,约 {seconds} 秒后继续")); }
|
||||
let cancel = stitch_ui::button(ui, "取消读取", false);
|
||||
if cancel.clicked() {
|
||||
let _ = self.tx.send(Request::Action("knowledge-cancel".into(), json!({"jobId":progress["jobId"]})));
|
||||
}
|
||||
});
|
||||
}
|
||||
let Some(set) = self.creation_reads.resource_set["id"].as_str().map(str::to_owned) else { return; };
|
||||
let parts = self.creation_catalog.get("resource-set").cloned().unwrap_or_default();
|
||||
let error = self.creation_catalog_error("resource-set").map(str::to_owned);
|
||||
if picker_notice(ui, self.creation_catalog_loading("resource-set"), error.as_deref(), parts.is_empty(), "该资源组没有可用的模板组件") {
|
||||
self.catalog(app, "resource-set", set.clone());
|
||||
}
|
||||
if ui.is_enabled()
|
||||
&& self.creation_reads.resource_component.is_empty()
|
||||
&& !self.creation_catalog_loading("resource-set")
|
||||
&& let Some(part) = default_resource_component(&parts)
|
||||
{
|
||||
self.select_resource_component(app, &set, part);
|
||||
}
|
||||
if !parts.is_empty() {
|
||||
ui.add_space(space::XS);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for part in &parts {
|
||||
let Some(id) = part["id"].as_str() else { continue; };
|
||||
let name = part["name"].as_str().unwrap_or("模板组件");
|
||||
let selected = self.creation_reads.resource_component == id;
|
||||
let loading = self.creation_catalog_loading("resource-component");
|
||||
let action = stitch_ui::segmented_option_sized(ui, name, selected, !loading, vec2(0.0, control::DEFAULT));
|
||||
self.control_geometry(&format!("resource-component-{id}"), action.rect);
|
||||
if action.clicked() && (!selected || !template_identity(&self.creation_brief["templateSelection"])) {
|
||||
self.select_resource_component(app, &set, part);
|
||||
}
|
||||
if !selected || loading {
|
||||
for issue in part["issues"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||
stitch_ui::status_label(ui, issue, stitch_ui::StatusTone::Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if self.creation_catalog_loading("resource-component") {
|
||||
stitch_kit::caption(ui, "正在核对模板资料…");
|
||||
}
|
||||
if let Some(error) = self.creation_catalog_error("resource-component") {
|
||||
stitch_ui::status_label(ui, error, stitch_ui::StatusTone::Error);
|
||||
}
|
||||
let result = self.creation_catalog.get_mut("resource-component").and_then(|rows| rows.first_mut())
|
||||
.filter(|row| row["id"] == self.creation_reads.resource_component).map(|row| {
|
||||
let result = row.clone();
|
||||
if let Some(image) = row["image"].as_object_mut() { image.remove("rgba"); }
|
||||
result
|
||||
});
|
||||
if let Some(result) = result {
|
||||
self.resource_component_result(app, ui, width, &set, &result);
|
||||
} else {
|
||||
let selected_part = parts.iter().find(|part| part["id"] == self.creation_reads.resource_component);
|
||||
let warnings = template_compatibility_warnings(&[
|
||||
&self.creation_reads.resource_set,
|
||||
selected_part.unwrap_or(&Value::Null),
|
||||
&self.creation_brief["templateSelection"],
|
||||
]);
|
||||
for warning in warnings {
|
||||
stitch_ui::status_label(ui, &warning, stitch_ui::StatusTone::Warning);
|
||||
}
|
||||
}
|
||||
self.creation_view_geometry["resourceSet"] = self.creation_reads.resource_set.clone();
|
||||
self.creation_view_geometry["templateSelection"] = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]);
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn select_resource_component(&mut self, app: &mut PhotocraftApp, set: &str, part: &Value) {
|
||||
let Some(id) = part["id"].as_str() else { return; };
|
||||
let preview = part["previews"].as_array().and_then(|images| images.first()).map(|image| &image["id"]);
|
||||
self.creation_reads.resource_component = id.to_owned();
|
||||
self.creation_reads.resource_image = None;
|
||||
self.creation_catalog.remove("resource-component");
|
||||
self.creation_dirty |= !self.creation_brief["templateSelection"].is_null();
|
||||
self.creation_brief["templateSelection"] = Value::Null;
|
||||
self.catalog(app, "resource-component", json!({"resourceSetId":set,"componentId":id,"previewId":preview}).to_string());
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn resource_component_result(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, set: &str, result: &Value) {
|
||||
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)
|
||||
&& choice["enterprise"]["resourceSetId"] == set
|
||||
&& choice["enterprise"]["componentId"] == component
|
||||
&& choice["brandId"] == self.creation_brief["brandId"]
|
||||
&& choice["categoryId"] == self.creation_brief["categoryId"]
|
||||
{
|
||||
let mut choice = choice.clone();
|
||||
if let Some(width) = choice["width"].as_u64() {
|
||||
self.creation_width = width as u32;
|
||||
}
|
||||
if let Some(fields) = choice.as_object_mut() {
|
||||
fields.remove("width");
|
||||
if let Some(schema) = fields.remove("intake") {
|
||||
set_intake(&mut self.creation_brief, &fields["id"], &schema);
|
||||
}
|
||||
}
|
||||
self.creation_brief["templateSelection"] = choice;
|
||||
self.creation_reads.inline_errors.remove("template");
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
for issue in result["issues"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||
stitch_ui::status_label(ui, issue, stitch_ui::StatusTone::Error);
|
||||
}
|
||||
let selected_part = self.creation_catalog.get("resource-set")
|
||||
.and_then(|parts| parts.iter().find(|part| part["id"] == component))
|
||||
.cloned()
|
||||
.unwrap_or(Value::Null);
|
||||
for warning in template_compatibility_warnings(&[
|
||||
result,
|
||||
choice,
|
||||
&selected_part,
|
||||
&self.creation_reads.resource_set,
|
||||
&self.creation_brief["templateSelection"],
|
||||
]) {
|
||||
stitch_ui::status_label(ui, &warning, stitch_ui::StatusTone::Warning);
|
||||
}
|
||||
if let Some(error) = result["previewError"].as_str() {
|
||||
stitch_kit::caption(ui, error);
|
||||
}
|
||||
let preview_key = format!("{set}:{component}:{}", result["previewId"]);
|
||||
if self.creation_reads.resource_image.as_ref().is_none_or(|(key, _)| key != &preview_key)
|
||||
&& let (Some(w), Some(h), Some(rgba)) = (result["image"]["size"][0].as_u64(), result["image"]["size"][1].as_u64(), result["image"]["rgba"].as_str())
|
||||
&& (1..=320).contains(&w) && (1..=320).contains(&h)
|
||||
&& let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(rgba)
|
||||
&& bytes.len() as u64 == w * h * 4
|
||||
{
|
||||
let image = egui::ColorImage::from_rgba_premultiplied([w as usize, h as usize], &bytes);
|
||||
self.creation_reads.resource_image = Some((preview_key, ui.ctx().load_texture("resource-template-preview", image, egui::TextureOptions::LINEAR)));
|
||||
}
|
||||
let tpl_name = self.creation_reads.resource_set["name"].as_str().or(choice["name"].as_str()).unwrap_or("项目模板").to_owned();
|
||||
let tpl_width = result["choice"]["width"].as_u64().unwrap_or(self.creation_width as u64) as u32;
|
||||
let cover_img = self.creation_reads.resource_image.clone().map(|(_, tex)| tex);
|
||||
let fallback_structure = if cover_img.is_none() {
|
||||
choice.get("structurePreview").filter(|v| v.is_object())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if cover_img.is_some() || fallback_structure.is_some() || template_identity(choice) {
|
||||
ui.add_space(space::SM);
|
||||
let card = ui.scope(|ui| {
|
||||
structure_preview_card(
|
||||
ui,
|
||||
fallback_structure,
|
||||
cover_img.as_ref(),
|
||||
&tpl_name,
|
||||
"企业知识库",
|
||||
self.creation_template_screen_count(),
|
||||
tpl_width,
|
||||
Some("已就绪"),
|
||||
);
|
||||
});
|
||||
self.control_geometry("resource-preview", card.response.rect);
|
||||
}
|
||||
if let Some(previews) = result["previews"].as_array().filter(|images| images.len() > 1) {
|
||||
ui.add_space(space::XS);
|
||||
let label = result["previewName"].as_str().unwrap_or("切换预览页");
|
||||
picker(ui, "resource-preview-select", width.min(320.0), label, |ui| {
|
||||
for preview in previews {
|
||||
let Some(id) = preview["id"].as_str() else { continue; };
|
||||
if stitch_ui::select_option(ui, preview["name"].as_str().unwrap_or("预览"), result["previewId"] == id, true).clicked() {
|
||||
self.creation_reads.resource_image = None;
|
||||
self.catalog(app, "resource-component", json!({"resourceSetId":set,"componentId":component,"previewId":id,"previewOnly":true}).to_string());
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn template_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) {
|
||||
let brand = self.creation_brief["brandId"].as_str().unwrap_or("").to_owned();
|
||||
let category = self.creation_brief["categoryId"].as_str().unwrap_or("").to_owned();
|
||||
let selected = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]);
|
||||
if self.template_workflow["canvasFirst"] == true && template_identity(&selected) && selected["enterprise"]["sourceKind"] == "resource-map" {
|
||||
let name = selected["name"].as_str().unwrap_or("项目模板");
|
||||
let view = ui.label(format!("{name} · 已固定"));
|
||||
self.control_geometry("template", view.rect);
|
||||
self.creation_view_geometry["templateSelection"] = selected;
|
||||
return;
|
||||
}
|
||||
if brand.starts_with("ekb:brand:") || brand.is_empty() {
|
||||
if self.template_workflow["canvasFirst"] == true && template_identity(&selected) {
|
||||
let name = selected["name"].as_str().unwrap_or("项目模板");
|
||||
let view = ui.label(format!("{name} · 已固定"));
|
||||
self.control_geometry("template", view.rect);
|
||||
self.creation_view_geometry["templateSelection"] = selected;
|
||||
} else {
|
||||
self.resource_template_select(app, ui, width, &selected, &brand, &category);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let rows = self
|
||||
.creation_catalog
|
||||
.get("templates")
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|row| row["brandId"] == brand && row["categoryId"] == category && template_identity(row))
|
||||
.collect::<Vec<_>>();
|
||||
let fixed = self.template_workflow["canvasFirst"] == true && template_identity(&selected);
|
||||
let selected_row =
|
||||
rows.iter().find(|row| row["id"] == selected["id"] && row["version"] == selected["version"] && row["contentHash"] == selected["contentHash"]);
|
||||
let name = selected_row.and_then(|row| row["name"].as_str()).or_else(|| selected["name"].as_str()).unwrap_or("项目模板");
|
||||
let version_label = if selected["enterprise"].is_object() { "企业知识库" } else { selected["version"].as_str().unwrap_or("") };
|
||||
let label = if template_identity(&selected) { format!("{name} · {version_label}") } else { "选择模板".into() };
|
||||
if !brand.is_empty()
|
||||
&& !category.is_empty()
|
||||
&& !self.creation_catalog.contains_key("templates")
|
||||
&& !self.creation_catalog_loading("templates")
|
||||
&& self.creation_catalog_error("templates").is_none()
|
||||
{
|
||||
self.catalog(app, "templates", String::new());
|
||||
}
|
||||
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<Value>| {
|
||||
let response = picker(ui, "creation-template", p_width, &label, |ui| {
|
||||
if brand.is_empty() || category.is_empty() {
|
||||
ui.weak("先选择品牌与品类");
|
||||
} else {
|
||||
let error = this.creation_catalog_error("templates").map(str::to_owned);
|
||||
if picker_notice(ui, this.creation_catalog_loading("templates"), error.as_deref(), rows.is_empty(), "当前品类暂无可用模板") {
|
||||
this.catalog(app, "templates", String::new());
|
||||
}
|
||||
}
|
||||
if rows.iter().any(|row| verified_structure_preview(row, row, &brand, &category).is_some()) {
|
||||
stitch_kit::caption(ui, "首屏结构示意 · 不含图片");
|
||||
}
|
||||
for row in &rows {
|
||||
let mut choice = json!({"id":row["id"],"name":row["name"],"version":row["version"],"contentHash":row["contentHash"],"brandId":row["brandId"],"categoryId":row["categoryId"]});
|
||||
if row["enterprise"].is_object() { choice["enterprise"] = row["enterprise"].clone(); }
|
||||
let row_warnings = template_compatibility_warnings(&[row]);
|
||||
if !row_warnings.is_empty() {
|
||||
choice["compatibilityWarnings"] = json!(row_warnings);
|
||||
}
|
||||
let is_selected = selected["id"] == row["id"] && selected["version"] == row["version"] && selected["contentHash"] == row["contentHash"];
|
||||
let text = format!("{} · {}", row["name"].as_str().unwrap_or("模板"), if row["enterprise"].is_object() { "企业知识库" } else { row["version"].as_str().unwrap_or("") });
|
||||
let preview = verified_structure_preview(row, row, &brand, &category);
|
||||
let enabled = !fixed || is_selected;
|
||||
let item = template_picker_row(ui, is_selected, &text, enabled, preview);
|
||||
geometry.push(
|
||||
json!({"id":row["id"],"version":row["version"],"contentHash":row["contentHash"],"ready":enabled,"hasStructurePreview":preview.is_some(),"rect":rect_value(item.rect)}),
|
||||
);
|
||||
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");
|
||||
this.creation_dirty = true;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
if response.response.clicked() && response.inner.is_some() && !fixed && !brand.is_empty() && !category.is_empty() {
|
||||
this.catalog(app, "templates", String::new());
|
||||
}
|
||||
if this.creation_reads.scroll_to_field.as_deref() == Some("template") {
|
||||
this.creation_reads.scroll_to_field = None;
|
||||
response.response.scroll_to_me(Some(egui::Align::Center));
|
||||
response.response.request_focus();
|
||||
}
|
||||
this.picker_geometry(ui, "template", &response.response, this.creation_catalog_loading("templates"), !rows.is_empty(), geometry.clone());
|
||||
if let Some(err) = this.creation_reads.inline_errors.get("template") {
|
||||
stitch_ui::status_label(ui, err, stitch_ui::StatusTone::Error);
|
||||
}
|
||||
if let Some(error) = this.creation_catalog_error("templates") {
|
||||
let msg = crate::client_brand::user_error(error, "请检查网络或模板配置后重试");
|
||||
let notice = stitch_ui::status_label(ui, &format!("模板读取失败:{msg}。"), stitch_ui::StatusTone::Error);
|
||||
this.control_geometry("template-error", notice.rect);
|
||||
}
|
||||
ui.add_space(space::XS);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let chosen_now = selected_template(&this.creation_brief, &this.template_workflow, &this.creation["brief"]);
|
||||
let status = if template_identity(&chosen_now) {
|
||||
if rows.iter().any(|row| row["id"] == chosen_now["id"] && (row["version"] != chosen_now["version"] || row["contentHash"] != chosen_now["contentHash"])) {
|
||||
Some("可更新")
|
||||
} else if fixed {
|
||||
Some("已固定")
|
||||
} else if rows.iter().find(|row| row["id"] == chosen_now["id"] && row["version"] == chosen_now["version"] && row["contentHash"] == chosen_now["contentHash"]).is_some_and(|row| row["cached"] == true) {
|
||||
Some("已缓存")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(status) = status {
|
||||
let badge = ui.scope(|ui| stitch_ui::status_chip(ui, status, stitch_ui::StatusTone::Neutral));
|
||||
this.control_geometry("template-status", badge.response.rect);
|
||||
}
|
||||
let refresh = ui
|
||||
.add_enabled_ui(!brand.is_empty() && !category.is_empty() && !this.creation_catalog_loading("templates"), |ui| {
|
||||
stitch_ui::action_button(ui, "检查模板更新", stitch_ui::ButtonRole::Quiet, true)
|
||||
})
|
||||
.inner;
|
||||
this.control_geometry("template-update", refresh.rect);
|
||||
if refresh.clicked() {
|
||||
this.request_creation_catalog(app, "templates", String::new(), true);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if side_by_side {
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = space::MD;
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(picker_width);
|
||||
draw_picker(self, app, ui, picker_width, &mut geometry);
|
||||
});
|
||||
let chosen = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]);
|
||||
let preview = rows.iter().find_map(|row| verified_structure_preview(row, &chosen, &brand, &category));
|
||||
let card_w = (width - picker_width - space::MD).max(220.0);
|
||||
let card = ui.vertical(|ui| {
|
||||
ui.set_width(card_w);
|
||||
structure_preview_card(
|
||||
ui,
|
||||
preview,
|
||||
None,
|
||||
name,
|
||||
version_label,
|
||||
self.creation_template_screen_count(),
|
||||
self.creation_width,
|
||||
if fixed { Some("已固定") } else { None },
|
||||
);
|
||||
});
|
||||
self.control_geometry("template-preview-card", card.response.rect);
|
||||
});
|
||||
} else {
|
||||
draw_picker(self, app, ui, picker_width, &mut geometry);
|
||||
let chosen = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]);
|
||||
let preview = rows.iter().find_map(|row| verified_structure_preview(row, &chosen, &brand, &category));
|
||||
if preview.is_some() || template_identity(&chosen) {
|
||||
ui.add_space(space::SM);
|
||||
let card = ui.scope(|ui| {
|
||||
structure_preview_card(
|
||||
ui,
|
||||
preview,
|
||||
None,
|
||||
name,
|
||||
version_label,
|
||||
self.creation_template_screen_count(),
|
||||
self.creation_width,
|
||||
if fixed { Some("已固定") } else { None },
|
||||
);
|
||||
});
|
||||
self.control_geometry("template-preview-card", card.response.rect);
|
||||
}
|
||||
}
|
||||
self.creation_view_geometry["templateSelection"] = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]);
|
||||
let chosen_now = &self.creation_view_geometry["templateSelection"];
|
||||
let chosen_row = rows.iter().find(|row| {
|
||||
row["id"] == chosen_now["id"] && row["version"] == chosen_now["version"] && row["contentHash"] == chosen_now["contentHash"]
|
||||
});
|
||||
for warning in template_compatibility_warnings(&[chosen_row.unwrap_or(&Value::Null), chosen_now]) {
|
||||
stitch_ui::status_label(ui, &warning, stitch_ui::StatusTone::Warning);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,102 @@
|
||||
use super::super::{PhotocraftApp, Ui, Value, Workspace, json, stitch_ui};
|
||||
use super::super::creation_reads::{TEST_PRESETS, wizard::CreationStage};
|
||||
use super::brief::{empty_brief, template_identity};
|
||||
use crate::theme::agent_scale::space;
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn test_preset_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
if !self.can_use_test_presets(app) {
|
||||
return;
|
||||
}
|
||||
if !self.creation_catalog.contains_key(TEST_PRESETS)
|
||||
&& self.creation_catalog_error(TEST_PRESETS).is_none()
|
||||
&& !self.creation_catalog_loading(TEST_PRESETS)
|
||||
{
|
||||
self.request_creation_catalog(app, TEST_PRESETS, String::new(), false);
|
||||
}
|
||||
let Some(presets) = self.creation_catalog.get(TEST_PRESETS).filter(|rows| !rows.is_empty()) else {
|
||||
return;
|
||||
};
|
||||
let importing = self.test_preset_import_pending();
|
||||
let label = if importing { "正在填入测试商品…" } else { "一键填入测试商品(超管)" };
|
||||
let button = stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Secondary, !importing)
|
||||
.on_hover_text("选择后替换当前商品资料和参考图");
|
||||
let mut chosen = None;
|
||||
egui::Popup::menu(&button).style(stitch_ui::scoped_popup_style(ui))
|
||||
.frame(stitch_ui::command_menu_frame(ui.ctx())).show(|ui| {
|
||||
for preset in presets {
|
||||
if stitch_ui::action_button(ui, preset["label"].as_str().unwrap_or(""), stitch_ui::ButtonRole::Quiet, true).clicked() {
|
||||
chosen = Some(preset.clone());
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(preset) = chosen {
|
||||
self.select_test_preset(app, ui.ctx(), preset);
|
||||
}
|
||||
ui.add_space(space::SM);
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn select_test_preset(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, preset: Value) {
|
||||
if !self.can_use_test_presets(app) || self.test_preset_import_pending() {
|
||||
return;
|
||||
}
|
||||
let staged = self.creation_reads.staged_new_project;
|
||||
if self.ensure_creation_document(app).is_err() {
|
||||
return;
|
||||
}
|
||||
if staged {
|
||||
// Detach the old project before queuing the import. The new native
|
||||
// document has no saved draft to restore on the next frame.
|
||||
let doc = self.creation_doc;
|
||||
let brief = std::mem::take(&mut self.creation_brief);
|
||||
let dirty = self.creation_dirty;
|
||||
self.switch_project_projection(app, ctx, None);
|
||||
self.observed_doc = doc;
|
||||
self.loaded_draft = doc;
|
||||
self.creation_doc = doc;
|
||||
self.creation_ui_scope = self.current_creation_ui_scope(app);
|
||||
self.project_view_parked = false;
|
||||
self.creation_brief = brief;
|
||||
self.creation = json!({"brief":empty_brief()});
|
||||
self.creation_dirty = dirty;
|
||||
}
|
||||
// Carry the same picker across the staged draft's first image import.
|
||||
let presets = self.creation_catalog.remove(TEST_PRESETS);
|
||||
self.creation_read_scope(app);
|
||||
if let Some(presets) = presets {
|
||||
self.creation_catalog.insert(TEST_PRESETS.into(), presets);
|
||||
}
|
||||
self.request_test_preset_import(app, preset);
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn apply_test_preset(&mut self, app: &PhotocraftApp, mut brief: Value) {
|
||||
let selected = &self.creation_brief["templateSelection"];
|
||||
let taxonomy_changed = self.creation_brief["brandId"] != brief["brandId"]
|
||||
|| self.creation_brief["categoryId"] != brief["categoryId"];
|
||||
let keep_template = template_identity(selected)
|
||||
&& selected["id"] == brief["intake"]["templateId"]
|
||||
&& !taxonomy_changed;
|
||||
if keep_template {
|
||||
brief["templateSelection"] = selected.clone();
|
||||
} else if self.creation_reads.wizard_stage.is_some_and(|(_, stage)| stage == CreationStage::Details) {
|
||||
self.creation_reads.wizard_stage = Some((self.creation_field_scope(app), CreationStage::Template));
|
||||
}
|
||||
if taxonomy_changed {
|
||||
self.agent_rule = Value::Null;
|
||||
self.agent_rule_state = Value::Null;
|
||||
self.creation_catalog.remove("categories");
|
||||
self.creation_catalog.remove("templates");
|
||||
}
|
||||
self.creation_brief = brief;
|
||||
self.creation_reads.manual_edited_fields.clear();
|
||||
self.creation_reads.inline_errors.clear();
|
||||
self.creation_reads.reference_import_error.clear();
|
||||
self.creation_reads.scroll_to_field = None;
|
||||
self.creation_failed_signature.clear();
|
||||
self.creation_dirty = true;
|
||||
self.sync_dirty = true;
|
||||
self.draft_changed = true;
|
||||
}
|
||||
|
||||
}
|
||||
3974
apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/tests.rs
Normal file
3974
apps/detail-photocraft/crates/ui-egui/src/jiansun/creation/tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,431 @@
|
||||
use super::super::{PhotocraftApp, Tokens, Ui, Value, Workspace, json, stitch_kit, stitch_state::Tone, stitch_ui};
|
||||
use super::super::creation_reads::wizard::{self, CreationStage, WizardFooterOutcome, WizardFooterState};
|
||||
use super::REFERENCE_DROP_HINT;
|
||||
use super::barcode::{project_barcodes, replace_barcode, structured_barcode_field, write_legacy_barcode_fields};
|
||||
use super::brief::{non_empty_str, normalized_product_summary, selected_template, selected_visual_asset_count, template_identity};
|
||||
use super::form_widgets_ui::{brief_section_break, edit_named, field_key, field_kind, intake_hint, preview_size};
|
||||
use super::reducers::form_editable;
|
||||
use super::structure_preview_ui::wizard_column;
|
||||
use crate::theme::{AGENT_SEMANTIC, agent_scale::{Type, icon, radius, space}};
|
||||
use egui::vec2;
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) 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::<bool>(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, 7)))
|
||||
.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);
|
||||
let setup_warning = self.brief_setup_warning();
|
||||
let key_saved = self.key_saved;
|
||||
let mut open_settings = false;
|
||||
let mut cfg_rect = None;
|
||||
let action = wizard::wizard_footer_ui_with_status(
|
||||
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,
|
||||
|ui| {
|
||||
if let Some((message, _, action)) = setup_warning {
|
||||
let configure = stitch_ui::action_button(ui, action, stitch_ui::ButtonRole::Quiet, true).on_hover_text(message);
|
||||
cfg_rect = Some(configure.rect);
|
||||
if configure.clicked() {
|
||||
open_settings = true;
|
||||
}
|
||||
}
|
||||
},
|
||||
|_, _| {},
|
||||
);
|
||||
if let Some(rect) = cfg_rect {
|
||||
self.control_geometry(if key_saved { "select-model" } else { "configure-personal-key" }, rect);
|
||||
}
|
||||
if open_settings {
|
||||
self.open_brief_setup_settings();
|
||||
}
|
||||
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();
|
||||
if stage != CreationStage::Template {
|
||||
self.test_preset_ui(app, ui);
|
||||
}
|
||||
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()));
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) 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);
|
||||
self.creation_reads.new_project_doc = None;
|
||||
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 if self.template_workflow["canvasFirst"] != true {
|
||||
self.show_center(super::CenterView::Projects, app.session.active().is_some());
|
||||
} 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));
|
||||
}
|
||||
|
||||
|
||||
pub(in crate::jiansun) 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);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) 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);
|
||||
}
|
||||
_ => {
|
||||
self.poll_imported_reference_previews(app, ui.ctx());
|
||||
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;
|
||||
}
|
||||
ui.add_space(space::XS);
|
||||
let count = self.creation_brief["images"].as_array().map_or(0, Vec::len);
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = space::MD;
|
||||
if stitch_ui::action_button(ui, "选择文件夹", stitch_ui::ButtonRole::Quiet, true).clicked() {
|
||||
self.open_reference_dialog(app, Value::Null, true);
|
||||
}
|
||||
if count > 0 {
|
||||
stitch_kit::label(ui, format!("已添加 {count} 张图片"), Type::Meta, Tone::Success);
|
||||
}
|
||||
});
|
||||
if count > 0 {
|
||||
ui.add_space(space::XS);
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let images = self.creation_brief["images"].as_array().cloned().unwrap_or_default();
|
||||
let mut remove_idx = None;
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(space::SM, space::SM);
|
||||
for (idx, img) in images.iter().enumerate() {
|
||||
let src = img["source"].as_str().unwrap_or("");
|
||||
let name = img["name"].as_str().unwrap_or("产品图片");
|
||||
let key = super::creation_reads::reference_key(src);
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(76.0);
|
||||
ui.spacing_mut().item_spacing.y = 4.0;
|
||||
let (thumb_rect, thumb_resp) = ui.allocate_exact_size(vec2(76.0, 76.0), egui::Sense::hover());
|
||||
ui.painter().rect_filled(thumb_rect, radius::ROW, t.field);
|
||||
ui.painter().rect_stroke(thumb_rect, radius::ROW, egui::Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside);
|
||||
if ui.is_rect_visible(thumb_rect) && !src.is_empty() {
|
||||
self.queue_creation_reference(app, src);
|
||||
}
|
||||
if let Some(tex) = self.creation_thumbs.get(&key).cloned() {
|
||||
let size = preview_size(tex.size_vec2(), thumb_rect.shrink(3.0).size());
|
||||
let fit = egui::Align2::CENTER_CENTER.align_size_within_rect(size, thumb_rect);
|
||||
ui.painter().image(tex.id(), fit, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text);
|
||||
self.material_preview(thumb_resp, &key, name, &tex);
|
||||
} else {
|
||||
crate::icons::paint(ui, thumb_rect, "image", icon::MD, t.text_dim);
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
ui.add_sized(
|
||||
vec2(54.0, 18.0),
|
||||
egui::Label::new(egui::RichText::new(name).font(Type::Meta.font_id()).color(t.text_dim)).truncate(),
|
||||
).on_hover_text(name);
|
||||
if stitch_ui::icon_button(ui, "trash", 18.0, false, "移除此图片").clicked() {
|
||||
remove_idx = Some(idx);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
if let Some(idx) = remove_idx
|
||||
&& let Some(list) = self.creation_brief["images"].as_array_mut()
|
||||
&& idx < list.len()
|
||||
{
|
||||
list.remove(idx);
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) 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::<Vec<_>>();
|
||||
let images = schema.as_array().into_iter().flatten().filter(|field| field_kind(field) == "image").collect::<Vec<_>>();
|
||||
|
||||
self.poll_imported_reference_previews(app, ui.ctx());
|
||||
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 mut open_image_for_barcode: Option<String> = None;
|
||||
let action = wizard::barcode_cards_section_ui(
|
||||
ui,
|
||||
scope,
|
||||
&mut rows,
|
||||
self.reduce_motion,
|
||||
hint,
|
||||
|ui, id, slot| match slot {
|
||||
wizard::BarcodeSlotRender::Image { row, size, editable: editable_slot } => {
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let code = non_empty_str(&row["barcode"]);
|
||||
let matched_sources: Vec<(String, String)> = self.creation_brief["images"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|img| code.is_some() && img["barcode"].as_str() == code)
|
||||
.filter_map(|img| Some((img["source"].as_str()?.to_owned(), img["name"].as_str().unwrap_or("条码图片").to_owned())))
|
||||
.collect();
|
||||
let sense = if editable_slot && code.is_some() { egui::Sense::click() } else { egui::Sense::hover() };
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(size, size), sense);
|
||||
ui.painter().rect_filled(rect, radius::ROW, t.field);
|
||||
let stroke_color = if resp.hovered() && editable_slot && code.is_some() { t.primary_bg } else { t.card_border };
|
||||
ui.painter().rect_stroke(rect, radius::ROW, egui::Stroke::new(1.0, stroke_color), egui::StrokeKind::Inside);
|
||||
if let Some((first_src, first_name)) = matched_sources.first() {
|
||||
if ui.is_rect_visible(rect) {
|
||||
self.queue_creation_reference(app, first_src);
|
||||
}
|
||||
let key = super::creation_reads::reference_key(first_src);
|
||||
if let Some(tex) = self.creation_thumbs.get(&key).cloned() {
|
||||
let fit_sz = preview_size(tex.size_vec2(), rect.shrink(2.0).size());
|
||||
let fit = egui::Align2::CENTER_CENTER.align_size_within_rect(fit_sz, rect);
|
||||
ui.painter().image(tex.id(), fit, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), AGENT_SEMANTIC.on_image_text);
|
||||
} else {
|
||||
crate::icons::paint(ui, rect, "image", if size >= 48.0 { icon::MD } else { icon::SM }, t.text_dim);
|
||||
}
|
||||
if matched_sources.len() > 1 {
|
||||
let badge = egui::Rect::from_min_size(egui::pos2(rect.right() - 18.0, rect.bottom() - 15.0), vec2(17.0, 14.0));
|
||||
ui.painter().rect_filled(badge, 3.0, egui::Color32::from_rgba_unmultiplied(15, 16, 18, 210));
|
||||
ui.painter().text(badge.center(), egui::Align2::CENTER_CENTER, format!("{}", matched_sources.len()), Type::Meta.font_id(), t.text);
|
||||
}
|
||||
let tip = if editable_slot { format!("{first_name}(点击继续添加条码图)") } else { first_name.clone() };
|
||||
let resp = resp.on_hover_text(tip);
|
||||
if resp.clicked() && let Some(c) = code {
|
||||
open_image_for_barcode = Some(c.to_owned());
|
||||
}
|
||||
} else {
|
||||
crate::icons::paint(ui, rect, if editable_slot { "plus" } else { "image" }, if size >= 48.0 { icon::MD } else { icon::SM }, t.text_dim);
|
||||
let tip = if !editable_slot {
|
||||
"暂无条码专属图片"
|
||||
} else if code.is_some() {
|
||||
"点击为该条码添加图片"
|
||||
} else {
|
||||
"请先填写条码编码,再添加图片"
|
||||
};
|
||||
let resp = resp.on_hover_text(tip);
|
||||
if resp.clicked() && let Some(c) = code {
|
||||
open_image_for_barcode = Some(c.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
wizard::BarcodeSlotRender::Related { row } => {
|
||||
let Some(code) = non_empty_str(&row["barcode"]) else { return; };
|
||||
if !project_barcodes(&self.creation_brief).any(|existing| existing == code) { return; }
|
||||
if !fields.is_empty() || !images.is_empty() {
|
||||
self.barcode_intake_ui(app, ui, id, width, code, &fields, &images);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
if let Some(code) = open_image_for_barcode {
|
||||
self.open_reference_dialog(app, json!({"scope":"barcode","barcode":code,"purpose":"product","multiple":true}), false);
|
||||
}
|
||||
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 row in &rows {
|
||||
let Some(id) = row["id"].as_str() else { continue; };
|
||||
let Some(old) = previous.iter().find(|previous| previous["id"] == id) else { continue; };
|
||||
for field in ["material", "boardType", "colorName"] {
|
||||
if row[field] != old[field] {
|
||||
self.creation_reads.manual_edited_fields.insert(format!("barcode-card:{id}:{field}"));
|
||||
}
|
||||
}
|
||||
for axis in ["length", "width", "height", "depth", "secondaryHeight", "unit"] {
|
||||
if row["dimensions"][axis] != old["dimensions"][axis] {
|
||||
self.creation_reads.manual_edited_fields.insert(format!("barcode-card:{id}:dimensions.{axis}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
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) {
|
||||
self.creation_reads.manual_edited_fields.insert(format!("removed-barcode:{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_dirty = true;
|
||||
}
|
||||
if self.creation_brief["barcodeEntries"] != Value::Array(rows.clone()) {
|
||||
self.creation_brief["barcodeEntries"] = Value::Array(rows);
|
||||
}
|
||||
let codes: Vec<String> = 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
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) 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.delivery_directory_control(app, ui, editable);
|
||||
self.advanced_export_settings_ui(app, ui, scope, width, editable);
|
||||
pending
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user