Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 20b1fd63de | |||
| 105591bac5 | |||
| da44d66dc8 | |||
| 0a85c4f87e | |||
| efce7b102f | |||
| db5edc948c | |||
| 45c3780bf5 | |||
| 6fcf42e4ac | |||
| e0f9f811b7 | |||
| 03b5c1c9f4 | |||
| 58992330aa | |||
| 2c687b01a4 | |||
| c0e377f479 | |||
| 6001b87215 | |||
| b08ab6ee66 | |||
| 7f80012d7f | |||
| fbe95591d5 | |||
| d222aad2ec | |||
| 13b28ebbc7 | |||
| 30648e6b93 | |||
| 9dd1052374 | |||
| aec9568c39 | |||
| 0a1f0e0b26 | |||
| 5c31ae91ca | |||
| 3ba6168c6a | |||
| 2628b83d4b | |||
| a7b2b0e23b | |||
| ef982fdb78 | |||
| 91b65f94ca | |||
| 70513cf049 | |||
| 87aed0b765 | |||
| 733a7015af |
@@ -2566,11 +2566,18 @@ fn direct_taonier_art_asset_identity(
|
||||
.to_string(),
|
||||
reference_resource_ids: asset.source.reference_resource_ids.clone(),
|
||||
};
|
||||
// 参考集合先按该 kind 的请求合同收口:根素材(规范图)允许用户参考(icon-spec 没有
|
||||
// 规范前置,参考只是风格输入),派生素材仍必须按合同携带规范前置。
|
||||
let references_match_contract =
|
||||
crate::agent::platform_art_runtime_references_match_request_contract(
|
||||
&identity.reference_resource_ids,
|
||||
expected_kind,
|
||||
);
|
||||
let lineage_matches = match expected_reference_source {
|
||||
Some(source) => direct_taonier_reference_matches_local_source(root, source, &identity),
|
||||
None => identity.reference_resource_ids.is_empty(),
|
||||
None => true,
|
||||
};
|
||||
lineage_matches.then_some(identity)
|
||||
(references_match_contract && lineage_matches).then_some(identity)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2579,7 +2586,9 @@ fn direct_taonier_reference_matches_local_source(
|
||||
source: &DirectTaonierArtAssetIdentity,
|
||||
derived: &DirectTaonierArtAssetIdentity,
|
||||
) -> bool {
|
||||
let [remote_reference_id] = derived.reference_resource_ids.as_slice() else {
|
||||
// 派生素材的规范身份只由参考序列首项承担:用户参考按顺序追加在规范图之后,
|
||||
// 不能让它们顶替或淹没规范引用,也不能因为多出用户参考就判定派生关系不成立。
|
||||
let Some(remote_reference_id) = derived.reference_resource_ids.first() else {
|
||||
return false;
|
||||
};
|
||||
if derived.canvas_project_id == source.canvas_project_id
|
||||
@@ -3390,6 +3399,8 @@ async fn generate_direct_taonier_art_asset_at(
|
||||
slice_mode: (asset_kind == "art-spritesheet").then(|| "connected-components".to_string()),
|
||||
grid_x: None,
|
||||
grid_y: None,
|
||||
reference_asset_ids: Vec::new(),
|
||||
target_category: None,
|
||||
};
|
||||
let runtime_context =
|
||||
direct_taonier_art_generation_runtime_context(root, output_path, asset_kind)?;
|
||||
@@ -9802,6 +9813,78 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_taonier_art_package_accepts_manifest_user_references() {
|
||||
let root = tempfile::tempdir().expect("temp dir");
|
||||
init_local_game_project_at(root.path(), "direct-art-references", "直连美术参考")
|
||||
.expect("init project");
|
||||
register_direct_taonier_art_package_fixture(root.path());
|
||||
assert!(direct_taonier_art_package_is_valid(root.path()));
|
||||
|
||||
// 规范图与背景图带用户参考:参考只是风格输入,规范身份仍由参考序列首项承担。
|
||||
mutate_manifest_at(root.path(), |manifest| {
|
||||
let art_spec = manifest
|
||||
.assets
|
||||
.iter_mut()
|
||||
.find(|asset| asset.local_path == DIRECT_CODEX_ART_SPEC_ASSET_PATH)
|
||||
.expect("art spec asset");
|
||||
art_spec.source.reference_resource_ids = vec![
|
||||
"user-reference-1".to_string(),
|
||||
"user-reference-2".to_string(),
|
||||
];
|
||||
let background = manifest
|
||||
.assets
|
||||
.iter_mut()
|
||||
.find(|asset| asset.local_path == DIRECT_CODEX_BACKGROUND_ASSET_PATH)
|
||||
.expect("background asset");
|
||||
background
|
||||
.source
|
||||
.reference_resource_ids
|
||||
.push("user-reference-1".to_string());
|
||||
Ok(())
|
||||
})
|
||||
.expect("apply user references to the art base");
|
||||
assert!(
|
||||
direct_taonier_art_package_is_valid(root.path()),
|
||||
"user references must not invalidate the art package"
|
||||
);
|
||||
|
||||
// 图集仍只接受唯一规范引用:多一项用户参考必须失败关闭。
|
||||
mutate_manifest_at(root.path(), |manifest| {
|
||||
let spritesheet = manifest
|
||||
.assets
|
||||
.iter_mut()
|
||||
.find(|asset| asset.local_path == DIRECT_CODEX_SPRITESHEET_ASSET_PATH)
|
||||
.expect("spritesheet asset");
|
||||
spritesheet
|
||||
.source
|
||||
.reference_resource_ids
|
||||
.push("user-reference-1".to_string());
|
||||
Ok(())
|
||||
})
|
||||
.expect("add an extra spritesheet reference");
|
||||
assert!(
|
||||
!direct_taonier_art_package_is_valid(root.path()),
|
||||
"art spritesheet must reject extra user references"
|
||||
);
|
||||
|
||||
// 用户参考不能顶替图集的规范前置。
|
||||
mutate_manifest_at(root.path(), |manifest| {
|
||||
let spritesheet = manifest
|
||||
.assets
|
||||
.iter_mut()
|
||||
.find(|asset| asset.local_path == DIRECT_CODEX_SPRITESHEET_ASSET_PATH)
|
||||
.expect("spritesheet asset");
|
||||
spritesheet.source.reference_resource_ids = vec!["user-reference-1".to_string()];
|
||||
Ok(())
|
||||
})
|
||||
.expect("replace the spritesheet canonical reference");
|
||||
assert!(
|
||||
!direct_taonier_art_package_is_valid(root.path()),
|
||||
"a user reference must not replace the art spritesheet canonical spec"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_output_sync_accepts_a_complete_spritesheet_without_slices() {
|
||||
let root = tempfile::tempdir().expect("temp dir");
|
||||
|
||||
@@ -2341,6 +2341,8 @@ async fn bridge_generate_image(state: &DirectToolBridgeState, arguments: &Value)
|
||||
slice_mode,
|
||||
grid_x,
|
||||
grid_y,
|
||||
reference_asset_ids: Vec::new(),
|
||||
target_category: None,
|
||||
};
|
||||
let _generation_guard = state.image_generation_gate.lock().await;
|
||||
let generated = with_direct_editor_api_credentials(
|
||||
|
||||
@@ -67,10 +67,11 @@ pub(crate) use canvas_generation::{
|
||||
generate_platform_art_asset_with_options_at,
|
||||
generate_platform_art_asset_with_required_slices_at, maybe_generate_platform_art_asset_step,
|
||||
needs_platform_art_asset_generation, normalize_platform_art_asset_generation_kind,
|
||||
normalize_platform_art_reference_asset_ids, normalize_platform_art_target_category,
|
||||
platform_art_asset_art_spec, platform_art_asset_output_extension_matches,
|
||||
prepare_platform_art_asset_output_path, project_canvas_asset_media_types,
|
||||
role_has_canvas_assets, suggested_canvas_tool_call, PlatformArtAssetGenerationOptions,
|
||||
PLATFORM_ART_ASSET_GENERATION_KINDS,
|
||||
platform_art_runtime_references_match_request_contract, prepare_platform_art_asset_output_path,
|
||||
project_canvas_asset_media_types, role_has_canvas_assets, suggested_canvas_tool_call,
|
||||
PlatformArtAssetGenerationOptions, PLATFORM_ART_ASSET_GENERATION_KINDS,
|
||||
};
|
||||
#[allow(unused_imports)]
|
||||
pub(crate) use draft_validation::{
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -577,6 +577,8 @@ pub(in crate::agent) async fn observe_agent_runtime_platform_art_asset_generatio
|
||||
slice_mode: (!slice_mode.trim().is_empty()).then_some(slice_mode.clone()),
|
||||
grid_x,
|
||||
grid_y,
|
||||
reference_asset_ids: Vec::new(),
|
||||
target_category: None,
|
||||
};
|
||||
if let Some(pending) = pending_action {
|
||||
match recover_persisted_visual_generation_options(
|
||||
@@ -628,6 +630,9 @@ pub(in crate::agent) async fn observe_agent_runtime_platform_art_asset_generatio
|
||||
.or_else(|| (!slice_mode.trim().is_empty()).then_some(slice_mode)),
|
||||
grid_x,
|
||||
grid_y,
|
||||
reference_asset_ids: requested_options.reference_asset_ids,
|
||||
// Agent 运行时不会指定完成登记的目标栏目,保持调用方给的值(默认 `None`)。
|
||||
target_category: requested_options.target_category,
|
||||
}
|
||||
};
|
||||
options.replace_existing = replace_existing;
|
||||
|
||||
@@ -390,6 +390,12 @@ pub(crate) async fn start_local_project_asset_generation(
|
||||
image_size: Option<String>,
|
||||
asset_name: Option<String>,
|
||||
output_path: Option<String>,
|
||||
// 前端 IPC 字段 `referenceAssetIds`:当前项目 manifest 里的图片素材 id,只做参考输入,
|
||||
// 不进任务账本(重试由调用方继续用同一份引用提交,账本本身不新增字段)。
|
||||
reference_asset_ids: Option<Vec<String>>,
|
||||
// 前端 IPC 字段 `targetCategory`:完成登记时要落盘的正式栏目分类。同样不进任务账本:
|
||||
// 它与引用一样属于「同一次提交的本地落点」,重试由调用方继续用同一个栏目提交。
|
||||
target_category: Option<String>,
|
||||
) -> Result<AssetGenerationTaskRecord, String> {
|
||||
let task_id = asset_generation_task_id(&task_id)?;
|
||||
let request = prepare_local_project_asset_generation(
|
||||
@@ -400,6 +406,8 @@ pub(crate) async fn start_local_project_asset_generation(
|
||||
image_size.as_deref(),
|
||||
asset_name.as_deref(),
|
||||
output_path.as_deref(),
|
||||
reference_asset_ids.as_deref().unwrap_or_default(),
|
||||
target_category.as_deref(),
|
||||
)?;
|
||||
enforce_project_permission_policy(&request.root, "canvas.asset_generate")?;
|
||||
enforce_project_permission_policy(&request.root, "asset.register")?;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::*;
|
||||
use sha2::{Digest as _, Sha256};
|
||||
use shared_contracts::game_creation_app::GameCreationAppAssetCategory;
|
||||
use std::future::Future;
|
||||
|
||||
const PRIVATE_EXTERNAL_EDITOR_API_KEY_FILE_PREFIX: &str = "external-editor-api-";
|
||||
@@ -662,6 +663,7 @@ pub(crate) fn register_design_artifacts_at(root: &Path) -> Result<bool, String>
|
||||
generation_kind: None,
|
||||
reference_resource_ids: Vec::new(),
|
||||
},
|
||||
None,
|
||||
)?;
|
||||
changed |= asset_changed;
|
||||
}
|
||||
@@ -1876,8 +1878,56 @@ pub(crate) fn register_local_asset_entry(
|
||||
id_prefix: &str,
|
||||
source: GameCreationAppAssetSource,
|
||||
) -> Result<UploadLocalAssetResult, String> {
|
||||
register_local_asset_entry_with_change(root, local_path, kind, media_type, id_prefix, source)
|
||||
.map(|(result, _)| result)
|
||||
register_local_asset_entry_with_change(
|
||||
root, local_path, kind, media_type, id_prefix, source, None,
|
||||
)
|
||||
.map(|(result, _)| result)
|
||||
}
|
||||
|
||||
/// 带**显式目标分类**的登记入口:只给 GUI 生成完成路径用(前端 `targetCategory`)。
|
||||
///
|
||||
/// 入口栏目与生成 kind 不是同一套词汇(栏目 `character` / `scene` / `ui-interaction`,
|
||||
/// 生成 kind 的派生分类会把图片落到 `unclassified`、规范图落到 `document`),所以要落回
|
||||
/// 入口栏目只能由调用方把目标分类显式交进来。取值必须先过
|
||||
/// [`shared_contracts::game_creation_app::game_creation_app_asset_category_from_str`],
|
||||
/// 非法值失败关闭,绝不回退到 kind 派生;其它调用方继续走
|
||||
/// [`register_local_asset_entry`],行为不变。
|
||||
pub(crate) fn register_local_asset_entry_with_category(
|
||||
root: &Path,
|
||||
local_path: &str,
|
||||
kind: &str,
|
||||
media_type: &str,
|
||||
id_prefix: &str,
|
||||
source: GameCreationAppAssetSource,
|
||||
target_category: Option<&str>,
|
||||
) -> Result<UploadLocalAssetResult, String> {
|
||||
let target_category = normalize_asset_category_override(target_category)?;
|
||||
register_local_asset_entry_with_change(
|
||||
root,
|
||||
local_path,
|
||||
kind,
|
||||
media_type,
|
||||
id_prefix,
|
||||
source,
|
||||
target_category,
|
||||
)
|
||||
.map(|(result, _)| result)
|
||||
}
|
||||
|
||||
/// 归一显式目标分类:只接受合法枚举值,返回落盘字符串。
|
||||
fn normalize_asset_category_override(
|
||||
target_category: Option<&str>,
|
||||
) -> Result<Option<GameCreationAppAssetCategory>, String> {
|
||||
let Some(target_category) = target_category else {
|
||||
return Ok(None);
|
||||
};
|
||||
let target_category = target_category.trim();
|
||||
if target_category.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
game_creation_app_asset_category_from_str(target_category)
|
||||
.map(Some)
|
||||
.ok_or_else(|| format!("非法资源分类:{target_category}"))
|
||||
}
|
||||
|
||||
fn register_local_asset_entry_with_change(
|
||||
@@ -1887,6 +1937,7 @@ fn register_local_asset_entry_with_change(
|
||||
media_type: &str,
|
||||
id_prefix: &str,
|
||||
source: GameCreationAppAssetSource,
|
||||
target_category: Option<GameCreationAppAssetCategory>,
|
||||
) -> Result<(UploadLocalAssetResult, bool), String> {
|
||||
let normalized_path = normalize_relative_path(local_path)?;
|
||||
let absolute_path = resolve_local_project_path(root, &normalized_path)?;
|
||||
@@ -1912,11 +1963,17 @@ fn register_local_asset_entry_with_change(
|
||||
// kind 没变时刻意不动 category——落盘分类是权威值,同 kind 重登记不得抹掉它。
|
||||
let changed = existing.kind != kind
|
||||
|| existing.media_type != media_type
|
||||
|| existing.source != source;
|
||||
|| existing.source != source
|
||||
|| target_category.is_some_and(|category| existing.category != category);
|
||||
if existing.kind != kind {
|
||||
existing.kind = kind.to_string();
|
||||
existing.category = game_creation_app_asset_category_for_kind(kind);
|
||||
}
|
||||
// 调用方显式给出目标分类时它就是权威值:GUI 完成登记必须能落回入口栏目,
|
||||
// 这也是同路径重新生成时把资产从旧栏目(或 unclassified)原位接管过来的唯一入口。
|
||||
if let Some(category) = target_category {
|
||||
existing.category = category;
|
||||
}
|
||||
existing.media_type = media_type.to_string();
|
||||
existing.source = source;
|
||||
Ok((existing.id.clone(), "asset.update", changed))
|
||||
@@ -1933,7 +1990,8 @@ fn register_local_asset_entry_with_change(
|
||||
local_path: normalized_path.clone(),
|
||||
image_sequence_frames: None,
|
||||
image_sequence_duration_ms: None,
|
||||
category: game_creation_app_asset_category_for_kind(kind),
|
||||
category: target_category
|
||||
.unwrap_or_else(|| game_creation_app_asset_category_for_kind(kind)),
|
||||
tags: Vec::new(),
|
||||
source,
|
||||
});
|
||||
@@ -2153,6 +2211,7 @@ pub(crate) fn delete_manifest_asset_at(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use shared_contracts::game_creation_app::GameCreationAppAssetCategory;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
#[test]
|
||||
@@ -2176,6 +2235,121 @@ mod tests {
|
||||
assert!(!register_design_artifacts_at(root).expect("register idempotently"));
|
||||
}
|
||||
|
||||
/// GUI 完成登记可以显式指定目标栏目:新建条目与已登记条目都按显式值落盘。
|
||||
///
|
||||
/// 入口栏目(character / scene / ui-interaction)与生成 kind 不是同一套词汇,按 kind 派生
|
||||
/// 会把图片落到 unclassified,占位拿不回原位;非法值必须失败关闭,不传时保持 kind 派生。
|
||||
#[test]
|
||||
fn explicit_target_category_overrides_the_kind_derived_category() {
|
||||
fn canvas_source() -> GameCreationAppAssetSource {
|
||||
GameCreationAppAssetSource {
|
||||
kind: GameCreationAppAssetSourceKind::Canvas,
|
||||
canvas_project_id: None,
|
||||
resource_id: None,
|
||||
asset_object_id: None,
|
||||
task_id: None,
|
||||
prompt: None,
|
||||
model: None,
|
||||
generation_route: None,
|
||||
generation_kind: None,
|
||||
reference_resource_ids: Vec::new(),
|
||||
}
|
||||
}
|
||||
fn category_of(root: &Path, asset_id: &str) -> GameCreationAppAssetCategory {
|
||||
read_existing_manifest_for_project(root)
|
||||
.expect("read manifest")
|
||||
.assets
|
||||
.into_iter()
|
||||
.find(|asset| asset.id == asset_id)
|
||||
.expect("registered asset is present")
|
||||
.category
|
||||
}
|
||||
|
||||
let temporary = tempfile::tempdir().expect("tempdir");
|
||||
let root = temporary.path();
|
||||
crate::project::init_local_game_project_at(root, "target-category-test", "目标栏目登记")
|
||||
.expect("init project");
|
||||
fs::create_dir_all(root.join("assets")).expect("create assets dir");
|
||||
fs::write(root.join("assets/hero.png"), b"png-bytes").expect("write asset");
|
||||
|
||||
let registered = register_local_asset_entry_with_category(
|
||||
root,
|
||||
"assets/hero.png",
|
||||
"image",
|
||||
"image/png",
|
||||
"platform-art",
|
||||
canvas_source(),
|
||||
Some("character"),
|
||||
)
|
||||
.expect("register with a target category");
|
||||
assert_eq!(
|
||||
category_of(root, ®istered.id),
|
||||
GameCreationAppAssetCategory::Character
|
||||
);
|
||||
|
||||
// 同 kind 重新生成时显式目标分类仍是权威值:资产要能换栏目原位接管。
|
||||
register_local_asset_entry_with_category(
|
||||
root,
|
||||
"assets/hero.png",
|
||||
"image",
|
||||
"image/png",
|
||||
"platform-art",
|
||||
canvas_source(),
|
||||
Some("ui-interaction"),
|
||||
)
|
||||
.expect("re-register with another target category");
|
||||
assert_eq!(
|
||||
category_of(root, ®istered.id),
|
||||
GameCreationAppAssetCategory::UiInteraction
|
||||
);
|
||||
|
||||
// 非法值失败关闭,且不动已落盘的分类。
|
||||
assert!(register_local_asset_entry_with_category(
|
||||
root,
|
||||
"assets/hero.png",
|
||||
"image",
|
||||
"image/png",
|
||||
"platform-art",
|
||||
canvas_source(),
|
||||
Some("version"),
|
||||
)
|
||||
.is_err());
|
||||
assert_eq!(
|
||||
category_of(root, ®istered.id),
|
||||
GameCreationAppAssetCategory::UiInteraction
|
||||
);
|
||||
|
||||
// 不传目标分类时保持原有行为:新条目按 kind 派生(image → unclassified)。
|
||||
fs::write(root.join("assets/plain.png"), b"png-bytes").expect("write plain asset");
|
||||
let plain = register_local_asset_entry(
|
||||
root,
|
||||
"assets/plain.png",
|
||||
"image",
|
||||
"image/png",
|
||||
"platform-art",
|
||||
canvas_source(),
|
||||
)
|
||||
.expect("register without a target category");
|
||||
assert_eq!(
|
||||
category_of(root, &plain.id),
|
||||
GameCreationAppAssetCategory::Unclassified
|
||||
);
|
||||
// 已落盘的显式分类在 kind 未变时仍然是权威值:同 kind 重登记不得把它抹掉。
|
||||
register_local_asset_entry(
|
||||
root,
|
||||
"assets/hero.png",
|
||||
"image",
|
||||
"image/png",
|
||||
"platform-art",
|
||||
canvas_source(),
|
||||
)
|
||||
.expect("re-register without a target category");
|
||||
assert_eq!(
|
||||
category_of(root, ®istered.id),
|
||||
GameCreationAppAssetCategory::UiInteraction
|
||||
);
|
||||
}
|
||||
|
||||
/// 画板导出推断出的 kind 必须已经是 canonical 值。
|
||||
///
|
||||
/// 这个值会被原样写进 manifest 并据以派生落盘 `category`;一旦写出非 canonical 值
|
||||
|
||||
@@ -2320,6 +2320,27 @@ pub(crate) fn update_local_project_resource_classification(
|
||||
)
|
||||
}
|
||||
|
||||
/// 为一批已登记素材追加标签:整批一次校验、一次 manifest 写入、一次 revision 推进。
|
||||
///
|
||||
/// 权限位与单素材分类更新同口径取 `asset.register`(命令包装层只做权限门面,
|
||||
/// 身份 / 写锁 / CAS / 原子写与审计都在 `project/manifest.rs` 内完成)。
|
||||
/// 这里刻意**不**循环调用单素材命令:逐项调用会写出多份 manifest、推进多次 revision,
|
||||
/// 中途失败还会留下"前几个素材改了、后面的没改"的部分写入。
|
||||
#[tauri::command]
|
||||
pub(crate) fn add_local_project_resource_tags(
|
||||
input: AddLocalProjectResourceTagsInput,
|
||||
) -> Result<AddLocalProjectResourceTagsResult, String> {
|
||||
let root = Path::new(input.project_path.trim());
|
||||
enforce_project_permission_policy(root, "asset.register")?;
|
||||
add_manifest_asset_tags_at(
|
||||
root,
|
||||
&input.expected_project_id,
|
||||
input.expected_project_revision,
|
||||
input.asset_ids,
|
||||
input.tags,
|
||||
)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub(crate) async fn derive_local_project_resource(
|
||||
input: DeriveLocalProjectResourceInput,
|
||||
@@ -4871,6 +4892,8 @@ pub(crate) fn prepare_local_project_asset_generation(
|
||||
image_size: Option<&str>,
|
||||
asset_name: Option<&str>,
|
||||
output_path: Option<&str>,
|
||||
reference_asset_ids: &[String],
|
||||
target_category: Option<&str>,
|
||||
) -> Result<LocalProjectAssetGenerationRequest, String> {
|
||||
let project_path = project_path.trim();
|
||||
if project_path.is_empty() {
|
||||
@@ -4878,6 +4901,13 @@ pub(crate) fn prepare_local_project_asset_generation(
|
||||
}
|
||||
let asset_kind = normalize_platform_art_asset_generation_kind(kind)
|
||||
.ok_or_else(|| format!("素材类型不受支持:{}", kind.trim()))?;
|
||||
// 参考入参只接受当前项目 manifest 素材 id:路径、远端 resourceId 与超限在这里就被拒绝,
|
||||
// 不把校验推迟到远端(远端只该收到当前账号绑定下的 resource ID)。
|
||||
let reference_asset_ids =
|
||||
normalize_platform_art_reference_asset_ids(asset_kind, reference_asset_ids)?;
|
||||
// GUI 完成登记层参数:入口栏目与生成 kind 不是同一套词汇,只有调用方显式给出目标分类
|
||||
// 才能把产物原位落回入口栏目。非法值(含 `version` / `all` 这类栏目伪值)直接失败关闭。
|
||||
let target_category = normalize_platform_art_target_category(target_category)?;
|
||||
Ok(LocalProjectAssetGenerationRequest {
|
||||
root: PathBuf::from(project_path),
|
||||
prompt: local_project_asset_prompt(prompt)?,
|
||||
@@ -4914,6 +4944,8 @@ pub(crate) fn prepare_local_project_asset_generation(
|
||||
.then(|| "connected-components".to_string()),
|
||||
grid_x: None,
|
||||
grid_y: None,
|
||||
reference_asset_ids,
|
||||
target_category,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -4935,6 +4967,10 @@ pub(crate) async fn generate_local_project_asset(
|
||||
image_size: Option<String>,
|
||||
asset_name: Option<String>,
|
||||
output_path: Option<String>,
|
||||
reference_asset_ids: Option<Vec<String>>,
|
||||
// 前端 IPC 字段 `targetCategory`:本次生成完成登记时要落盘的正式栏目分类,
|
||||
// 只走 GUI 命令,取值必须是合法素材分类,Agent / Direct 路径不传。
|
||||
target_category: Option<String>,
|
||||
) -> Result<UploadLocalAssetResult, String> {
|
||||
let request = prepare_local_project_asset_generation(
|
||||
&project_path,
|
||||
@@ -4944,6 +4980,8 @@ pub(crate) async fn generate_local_project_asset(
|
||||
image_size.as_deref(),
|
||||
asset_name.as_deref(),
|
||||
output_path.as_deref(),
|
||||
reference_asset_ids.as_deref().unwrap_or_default(),
|
||||
target_category.as_deref(),
|
||||
)?;
|
||||
enforce_project_permission_policy(&request.root, "canvas.asset_generate")?;
|
||||
enforce_project_permission_policy(&request.root, "asset.register")?;
|
||||
@@ -4962,7 +5000,17 @@ mod local_project_asset_generation_tests {
|
||||
use super::*;
|
||||
|
||||
fn prepare(kind: &str, prompt: &str) -> Result<LocalProjectAssetGenerationRequest, String> {
|
||||
prepare_local_project_asset_generation("/tmp/project", kind, prompt, None, None, None, None)
|
||||
prepare_local_project_asset_generation(
|
||||
"/tmp/project",
|
||||
kind,
|
||||
prompt,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -5002,6 +5050,8 @@ mod local_project_asset_generation_tests {
|
||||
Some("2K"),
|
||||
Some(" 主角图集 "),
|
||||
Some(" assets/hero.png "),
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
.expect("explicit options");
|
||||
assert_eq!(explicit.root, PathBuf::from("/tmp/project"));
|
||||
@@ -5029,8 +5079,18 @@ mod local_project_asset_generation_tests {
|
||||
#[test]
|
||||
fn invalid_toolbar_arguments_are_rejected_before_any_generation() {
|
||||
assert_eq!(
|
||||
prepare_local_project_asset_generation("", "image", "要求", None, None, None, None)
|
||||
.expect_err("empty project path"),
|
||||
prepare_local_project_asset_generation(
|
||||
"",
|
||||
"image",
|
||||
"要求",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
.expect_err("empty project path"),
|
||||
"项目路径不能为空"
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -5041,6 +5101,60 @@ mod local_project_asset_generation_tests {
|
||||
prepare("game-art", "要求").expect_err("unverified kind"),
|
||||
"素材类型不受支持:game-art"
|
||||
);
|
||||
// 目标分类只接受合法素材分类枚举:栏目侧伪值 `version` / `all` 与任意其它值都失败关闭。
|
||||
for rejected in ["version", "all", "bogus", "UI"] {
|
||||
assert_eq!(
|
||||
prepare_local_project_asset_generation(
|
||||
"/tmp/project",
|
||||
"image",
|
||||
"要求",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
Some(rejected),
|
||||
)
|
||||
.expect_err("illegal target category"),
|
||||
format!("目标分类不是合法素材分类:{rejected}")
|
||||
);
|
||||
}
|
||||
// 合法值归一成落盘字符串(trim + kebab-case),供 manifest `category` 直接使用。
|
||||
assert_eq!(
|
||||
prepare_local_project_asset_generation(
|
||||
"/tmp/project",
|
||||
"image",
|
||||
"要求",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
Some(" ui-interaction "),
|
||||
)
|
||||
.expect("legal target category")
|
||||
.options
|
||||
.target_category
|
||||
.as_deref(),
|
||||
Some("ui-interaction")
|
||||
);
|
||||
assert_eq!(
|
||||
prepare_local_project_asset_generation(
|
||||
"/tmp/project",
|
||||
"image",
|
||||
"要求",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
.expect("omitted target category")
|
||||
.options
|
||||
.target_category,
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
prepare(
|
||||
"spec",
|
||||
@@ -5057,7 +5171,9 @@ mod local_project_asset_generation_tests {
|
||||
Some("4:3"),
|
||||
None,
|
||||
None,
|
||||
None
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
.expect_err("unsupported ratio"),
|
||||
"图片比例不受支持:4:3"
|
||||
@@ -5070,7 +5186,9 @@ mod local_project_asset_generation_tests {
|
||||
None,
|
||||
Some("4K"),
|
||||
None,
|
||||
None
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
.expect_err("unsupported size"),
|
||||
"图片尺寸不受支持:4K"
|
||||
@@ -5083,7 +5201,9 @@ mod local_project_asset_generation_tests {
|
||||
None,
|
||||
None,
|
||||
Some("坏\u{7}名字"),
|
||||
None
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
.expect_err("control character in asset name"),
|
||||
"素材名称超出安全边界"
|
||||
@@ -5096,7 +5216,9 @@ mod local_project_asset_generation_tests {
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some(&"a".repeat(LOCAL_PROJECT_ASSET_MAX_OUTPUT_PATH_CHARS + 1))
|
||||
Some(&"a".repeat(LOCAL_PROJECT_ASSET_MAX_OUTPUT_PATH_CHARS + 1)),
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
.expect_err("oversized output path"),
|
||||
"输出路径超出安全边界"
|
||||
|
||||
@@ -2589,6 +2589,7 @@ fn main() {
|
||||
register_local_asset,
|
||||
create_ui_design_resource,
|
||||
update_local_project_resource_classification,
|
||||
add_local_project_resource_tags,
|
||||
derive_local_project_resource,
|
||||
list_pending_local_project_resource_edits,
|
||||
resume_local_project_resource_edit,
|
||||
|
||||
@@ -1131,8 +1131,17 @@ pub(crate) fn validate_manifest_required_visual_asset(
|
||||
}
|
||||
|
||||
if task_id == "art-director" {
|
||||
if !asset.source.reference_resource_ids.is_empty() {
|
||||
return Err("统一视觉规范图不得声明派生资源引用".to_string());
|
||||
// 规范图是视觉来源链的根:它自身不派生任何视觉资产,但 icon-spec 生成允许用户参考
|
||||
// (没有规范前置,最多总上限),这些参考只是风格输入,不构成派生关系。这里改为验证
|
||||
// 参考集合仍符合 icon-spec 请求合同;route / generation kind / canvasProjectId /
|
||||
// resourceId / PNG 解码等身份判据全部保持不变。
|
||||
if !crate::agent::platform_art_runtime_references_match_request_contract(
|
||||
&asset.source.reference_resource_ids,
|
||||
expected_kind,
|
||||
) {
|
||||
return Err(format!(
|
||||
"统一视觉规范图的参考集合不符合请求合同:{expected_path}"
|
||||
));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
@@ -1157,11 +1166,17 @@ pub(crate) fn validate_manifest_required_visual_asset(
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| "统一视觉规范图缺少 resourceId".to_string())?;
|
||||
let [reference_resource_id] = asset.source.reference_resource_ids.as_slice() else {
|
||||
// 派生素材的参考合同是「规范图前置在最前,用户参考按顺序追加在后」,图集不接受用户参考:
|
||||
// 规范身份仍只由首项承担,用户参考不能顶替也不能冒充规范引用。
|
||||
if !crate::agent::platform_art_runtime_references_match_request_contract(
|
||||
&asset.source.reference_resource_ids,
|
||||
expected_kind,
|
||||
) {
|
||||
return Err(format!(
|
||||
"派生视觉资产未精确引用当前统一视觉规范图:{expected_path}"
|
||||
));
|
||||
};
|
||||
}
|
||||
let reference_resource_id = asset.source.reference_resource_ids[0].as_str();
|
||||
let original_provenance_matches =
|
||||
canvas_project_id == art_spec_project_id && reference_resource_id == art_spec_resource_id;
|
||||
let rebound_local_source_matches = if original_provenance_matches {
|
||||
@@ -1328,6 +1343,240 @@ pub(crate) fn update_manifest_asset_classification_at(
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub(crate) struct AddLocalProjectResourceTagsInput {
|
||||
pub(crate) project_path: String,
|
||||
pub(crate) expected_project_id: String,
|
||||
pub(crate) expected_project_revision: u64,
|
||||
pub(crate) asset_ids: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) tags: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct AddLocalProjectResourceTagsResult {
|
||||
pub(crate) assets: Vec<GameCreationAppAssetManifestEntry>,
|
||||
pub(crate) committed_project_revision: u64,
|
||||
}
|
||||
|
||||
/// 一次批量追加的素材上限:与主规范「每批最多 200 个不同素材」一致,按**去重后**数量计算。
|
||||
/// 批次越大,锁内要重算的合并结果越多,manifest 也越大;无界批次会把成本摊到之后每一次读写上。
|
||||
pub(crate) const ASSET_BATCH_TAG_MAX_ASSETS: usize = 200;
|
||||
|
||||
/// 批量追加标签的素材 ID 归一化:trim、按**首次出现顺序**去重,再在此处收口批次上下界。
|
||||
///
|
||||
/// 这里是"整句拒绝"的失败关闭口径,不做任何静默容忍:
|
||||
///
|
||||
/// - 空白 `assetId` 直接失败,不 `continue` 跳过。静默跳过会让"请求了 N 个素材"和"实际写了
|
||||
/// N-1 个"分叉,而调用方拿到的仍是成功——这正是本合同要排除的静默部分写;
|
||||
/// - 空批次失败;
|
||||
/// - 去重后超限立即失败(在扫描到第 201 个不同 ID 时就返回,不对剩余 ID 继续做去重扫描),
|
||||
/// 更不做"截断到 200 个":截断会让用户以为 250 个素材都加上了标签。
|
||||
fn normalize_manifest_batch_asset_ids(asset_ids: &[String]) -> Result<Vec<String>, String> {
|
||||
let mut normalized: Vec<String> = Vec::new();
|
||||
for asset_id in asset_ids {
|
||||
let asset_id = asset_id.trim();
|
||||
if asset_id.is_empty() {
|
||||
return Err("批量标签 assetId 不能为空".to_string());
|
||||
}
|
||||
if !normalized.iter().any(|existing| existing == asset_id) {
|
||||
normalized.push(asset_id.to_string());
|
||||
if normalized.len() > ASSET_BATCH_TAG_MAX_ASSETS {
|
||||
return Err(format!(
|
||||
"批量标签最多支持 {ASSET_BATCH_TAG_MAX_ASSETS} 个素材"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if normalized.is_empty() {
|
||||
return Err("批量标签至少需要一个素材".to_string());
|
||||
}
|
||||
Ok(normalized)
|
||||
}
|
||||
|
||||
/// 批量追加的标签归一化:沿用主规范的 trim / 去空 / 去重口径(复用
|
||||
/// [`normalize_manifest_asset_tags`],其中已含数量与单标签长度收口)。
|
||||
///
|
||||
/// 只有**归一后为空**才拒绝:请求里全是空白标签时,用户填的东西一个字都不会落盘,
|
||||
/// 此时若当成"成功且无变化"返回,界面会显示保存成功而素材上什么都没有。
|
||||
fn normalize_manifest_batch_tags(tags: &[String]) -> Result<Vec<String>, String> {
|
||||
let normalized = normalize_manifest_asset_tags(tags)?;
|
||||
if normalized.is_empty() {
|
||||
return Err("批量标签不能为空".to_string());
|
||||
}
|
||||
Ok(normalized)
|
||||
}
|
||||
|
||||
/// 追加语义:只把请求里**尚不存在**的标签按请求顺序补到原有标签之后。
|
||||
/// 原有标签的顺序、分类、类型、路径与来源都不参与改写——本命令没有删除或替换语义。
|
||||
fn merge_manifest_asset_tags(existing: &[String], incoming: &[String]) -> Vec<String> {
|
||||
let mut merged = existing.to_vec();
|
||||
for tag in incoming {
|
||||
if !merged.iter().any(|current| current == tag) {
|
||||
merged.push(tag.clone());
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
/// 锁内先算完的整批计划:任何一项缺失或超限都在这里失败,此时 manifest 一个字节都没动。
|
||||
struct ManifestAssetTagAppendPlan {
|
||||
/// 按请求顺序(去重后)返回的素材条目,标签为合并后的完整列表。
|
||||
assets: Vec<GameCreationAppAssetManifestEntry>,
|
||||
/// 真正需要落值的目标:`(assets 下标, 合并后的标签)`。
|
||||
updates: Vec<(usize, Vec<String>)>,
|
||||
/// 确实发生变化的素材 ID,供审计记录使用;空表示整批无变化。
|
||||
changed_asset_ids: Vec<String>,
|
||||
}
|
||||
|
||||
/// 先校验**全部**目标与**全部**合并结果,再决定是否写值。
|
||||
///
|
||||
/// 顺序是刻意的:第一阶段只读,任一目标不存在、任一合并结果超过标签上界都在写之前返回错误;
|
||||
/// 只有全部通过,第二阶段才逐项落值。这样"缺任一资产 / 超限"都不可能留下部分写入。
|
||||
fn plan_manifest_asset_tag_append(
|
||||
manifest: &GameCreationAppManifest,
|
||||
asset_ids: &[String],
|
||||
tags: &[String],
|
||||
) -> Result<ManifestAssetTagAppendPlan, String> {
|
||||
let mut assets = Vec::with_capacity(asset_ids.len());
|
||||
let mut updates: Vec<(usize, Vec<String>)> = Vec::with_capacity(asset_ids.len());
|
||||
let mut changed_asset_ids = Vec::new();
|
||||
for asset_id in asset_ids {
|
||||
let index = manifest
|
||||
.assets
|
||||
.iter()
|
||||
.position(|asset| &asset.id == asset_id)
|
||||
.ok_or_else(|| format!("项目资源不存在:{asset_id}"))?;
|
||||
let asset = &manifest.assets[index];
|
||||
// 合并结果复用同一个上界函数:已有标签已归一化,这里等价于对整份新列表再收口一次。
|
||||
// 上界函数只报"16 个"这种通用口径,200 个素材的批次里看不出是哪一项超了,所以在**调用点**
|
||||
// 补上目标身份(ID + 可读 localPath)并说明整批未写:用户要能直接定位到那一张素材。
|
||||
let merged = normalize_manifest_asset_tags(&merge_manifest_asset_tags(&asset.tags, tags))
|
||||
.map_err(|error| {
|
||||
format!(
|
||||
"素材 {}({})的标签合并结果不合法:{error};本次未写入任何素材",
|
||||
asset.id, asset.local_path
|
||||
)
|
||||
})?;
|
||||
if merged != asset.tags {
|
||||
changed_asset_ids.push(asset.id.clone());
|
||||
}
|
||||
updates.push((index, merged.clone()));
|
||||
assets.push(GameCreationAppAssetManifestEntry {
|
||||
tags: merged,
|
||||
..asset.clone()
|
||||
});
|
||||
}
|
||||
Ok(ManifestAssetTagAppendPlan {
|
||||
assets,
|
||||
updates,
|
||||
changed_asset_ids,
|
||||
})
|
||||
}
|
||||
|
||||
/// 为一批已登记素材追加标签:一次校验、一次 manifest 写入、一次 revision 推进。
|
||||
///
|
||||
/// 语义与 [`update_manifest_asset_classification_at`] 同源(`asset.register` 权限位、项目身份、
|
||||
/// 项目写锁、revision CAS、manifest 原子写、审计在 manifest 落盘之后 / revision 推进之前),
|
||||
/// 但作用域是**整批**:
|
||||
///
|
||||
/// - 项目身份校验两次(进入前与持锁后各一次),锁内按 `expectedProjectRevision` 做一次 CAS;
|
||||
/// - 锁内先算完整批计划,任一目标缺失或任一合并结果超限都**不写任何一项**;
|
||||
/// - 整批无变化时**不写盘、不审计、不推进 revision**,直接返回当前条目与当前 revision;
|
||||
/// - 真正有变化时才写一次 manifest、追加一条审计、推进一次 revision。
|
||||
///
|
||||
/// 已落盘之后的审计或 revision 失败照实报"整批已写入",不回滚、也不谎称回滚:manifest 是权威
|
||||
/// 真相且已经改变,把错误说成"没写"只会让用户拿错状态去重试。
|
||||
pub(crate) fn add_manifest_asset_tags_at(
|
||||
root: &Path,
|
||||
expected_project_id: &str,
|
||||
expected_project_revision: u64,
|
||||
asset_ids: Vec<String>,
|
||||
tags: Vec<String>,
|
||||
) -> Result<AddLocalProjectResourceTagsResult, String> {
|
||||
if expected_project_revision
|
||||
> shared_contracts::game_creation_app::GAME_CREATION_RESOURCE_LAYOUT_MAX_SAFE_REVISION
|
||||
{
|
||||
return Err("expectedProjectRevision 超出 JavaScript 安全整数范围".to_string());
|
||||
}
|
||||
let expected_project_id = expected_project_id.trim();
|
||||
if expected_project_id.is_empty() {
|
||||
return Err("批量标签 expectedProjectId 不能为空".to_string());
|
||||
}
|
||||
let asset_ids = normalize_manifest_batch_asset_ids(&asset_ids)?;
|
||||
let tags = normalize_manifest_batch_tags(&tags)?;
|
||||
|
||||
if read_existing_manifest_for_project(root)?.project_id != expected_project_id {
|
||||
return Err("project-identity-conflict".to_string());
|
||||
}
|
||||
// 锁的 commandId 用本命令自己的动作名(审计/排障时能区分是批量追加还是别的写路径);
|
||||
// 权限门面仍然是 `asset.register`,见 `commands.rs` 的命令包装层。
|
||||
let _lock = acquire_project_write_lock(root, ASSET_BATCH_TAG_AUDIT_RECORD_TYPE)?;
|
||||
if read_existing_manifest_for_project(root)?.project_id != expected_project_id {
|
||||
return Err("project-identity-conflict".to_string());
|
||||
}
|
||||
if read_game_creator_agent_runtime_project_revision(root)?.revision != expected_project_revision
|
||||
{
|
||||
return Err("project-revision-conflict".to_string());
|
||||
}
|
||||
|
||||
// no-op 判定发生在锁内、写盘之前:整批标签都已经存在时,连 manifest 都不必重写一次。
|
||||
// 这不是优化洁癖——重写会换掉文件 mtime 与内容字节,让"什么都没做"看起来像一次真实改动。
|
||||
let plan = plan_manifest_asset_tag_append(
|
||||
&read_existing_manifest_for_project(root)?,
|
||||
&asset_ids,
|
||||
&tags,
|
||||
)?;
|
||||
if plan.changed_asset_ids.is_empty() {
|
||||
return Ok(AddLocalProjectResourceTagsResult {
|
||||
assets: plan.assets,
|
||||
committed_project_revision: expected_project_revision,
|
||||
});
|
||||
}
|
||||
|
||||
let plan = mutate_manifest_at(root, |manifest| {
|
||||
// 锁内复核:`mutate_manifest_at` 自己重新读盘,所以这里按同一套规则重算一遍再落值。
|
||||
// 复核失败会在 `write_manifest_locked` 之前返回错误,仍然零写入;重算也保证不会拿
|
||||
// 锁外算出的绝对标签列表去覆盖这份 manifest 上刚出现的新标签。
|
||||
let plan = plan_manifest_asset_tag_append(manifest, &asset_ids, &tags)?;
|
||||
for (index, merged) in &plan.updates {
|
||||
manifest.assets[*index].tags = merged.clone();
|
||||
}
|
||||
Ok(plan)
|
||||
})?;
|
||||
|
||||
// 复核阶段才发现"锁外以为有变化、锁内其实已无变化"的极端竞态:这一次写盘写出的就是原内容,
|
||||
// 不能凭空补一条审计或推进 revision。正常路径不会走到这里——整批目标在此之前已经通过锁内 no-op 判定。
|
||||
if plan.changed_asset_ids.is_empty() {
|
||||
return Ok(AddLocalProjectResourceTagsResult {
|
||||
assets: plan.assets,
|
||||
committed_project_revision: expected_project_revision,
|
||||
});
|
||||
}
|
||||
|
||||
append_agent_db_record(
|
||||
root,
|
||||
serde_json::json!({
|
||||
"recordType": ASSET_BATCH_TAG_AUDIT_RECORD_TYPE,
|
||||
"assetIds": plan.changed_asset_ids,
|
||||
"expectedProjectRevision": expected_project_revision,
|
||||
"appendedTags": tags,
|
||||
}),
|
||||
)
|
||||
.map_err(|error| format!("批量标签已写入,但审计记录失败:{error}"))?;
|
||||
let committed_project_revision = advance_agent_runtime_project_revision_locked(root)
|
||||
.map_err(|error| format!("批量标签已写入,但项目 revision 未能推进:{error}"))?;
|
||||
Ok(AddLocalProjectResourceTagsResult {
|
||||
assets: plan.assets,
|
||||
committed_project_revision,
|
||||
})
|
||||
}
|
||||
|
||||
/// 批量标签写入的审计类型:一次批量追加只留一条记录,装的是"谁被追加了什么"。
|
||||
pub(crate) const ASSET_BATCH_TAG_AUDIT_RECORD_TYPE: &str = "asset.tags.append";
|
||||
|
||||
pub(crate) fn create_manifest_task_at(
|
||||
root: &Path,
|
||||
task_id: &str,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -6923,6 +6923,22 @@ fn agent_native_function_catalog_exposes_each_runtime_tool_with_core_schemas() {
|
||||
"sliceCount"
|
||||
])
|
||||
);
|
||||
let canvas_properties = &canvas_asset.parameters["properties"]["input"]["properties"];
|
||||
assert_eq!(
|
||||
canvas_properties["sliceMode"]["enum"],
|
||||
serde_json::json!(["connected-components", "grid", null])
|
||||
);
|
||||
for field in ["gridX", "gridY", "sliceCount"] {
|
||||
assert_eq!(
|
||||
canvas_properties[field]["type"],
|
||||
serde_json::json!(["integer", "null"])
|
||||
);
|
||||
assert_eq!(canvas_properties[field]["minimum"], 1);
|
||||
assert_eq!(
|
||||
canvas_properties[field]["maximum"],
|
||||
if field == "sliceCount" { 256 } else { 32 }
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
canvas_asset.parameters["properties"]["input"]["properties"]["aspectRatio"]["enum"],
|
||||
serde_json::json!(["1:1", "2:3", "3:2", "9:16", "16:9", null])
|
||||
|
||||
+40
-6
@@ -495,8 +495,9 @@ function ResourceReferenceEditor({
|
||||
useState<ResourceReferenceScope | null>(null);
|
||||
const [pickerPosition, setPickerPosition] = useState<{
|
||||
left: number;
|
||||
bottom: number;
|
||||
top: number;
|
||||
width: number;
|
||||
maxHeight: number;
|
||||
} | null>(null);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
@@ -960,18 +961,46 @@ function ResourceReferenceEditor({
|
||||
const updatePickerPosition = useCallback(() => {
|
||||
const rect = rootRef.current?.getBoundingClientRect();
|
||||
if (!rect) return;
|
||||
const viewportPadding = 12;
|
||||
const gap = 8;
|
||||
const width = Math.min(
|
||||
Math.max(rect.width, 360),
|
||||
Math.max(280, window.innerWidth - 24),
|
||||
Math.max(280, window.innerWidth - viewportPadding * 2),
|
||||
);
|
||||
const left = Math.min(
|
||||
Math.max(12, rect.left),
|
||||
Math.max(12, window.innerWidth - width - 12),
|
||||
Math.max(viewportPadding, rect.left),
|
||||
Math.max(viewportPadding, window.innerWidth - width - viewportPadding),
|
||||
);
|
||||
/**
|
||||
* 上边界钳制:面板高度**必须**由输入框上下实际可用的空间决定。
|
||||
*
|
||||
* 之前只把底边钉在输入框上方(`bottom: 视口高 - rect.top + 8`)却让高度自由取到 480px,
|
||||
* 输入框靠上时(居中弹层里的提示词输入、窄屏)整块面板的顶边会被顶出视口——顶部那一排
|
||||
* 搜索与筛选既看不见也点不到。这里与 `@` 候选菜单同一套口径:先算上下各有多少空间,
|
||||
* 空间不足就翻到下方,并把高度收在该侧可用空间内,再对 `top` 兜一次底。
|
||||
*/
|
||||
const availableAbove = Math.max(0, rect.top - viewportPadding - gap);
|
||||
const availableBelow = Math.max(
|
||||
0,
|
||||
window.innerHeight - rect.bottom - viewportPadding - gap,
|
||||
);
|
||||
const openAbove =
|
||||
availableAbove >= 200 || availableAbove >= availableBelow;
|
||||
const maxHeight = Math.max(
|
||||
160,
|
||||
Math.min(480, openAbove ? availableAbove : availableBelow),
|
||||
);
|
||||
const top = openAbove
|
||||
? Math.max(viewportPadding, rect.top - gap - maxHeight)
|
||||
: Math.min(
|
||||
Math.max(viewportPadding, window.innerHeight - viewportPadding - maxHeight),
|
||||
rect.bottom + gap,
|
||||
);
|
||||
setPickerPosition({
|
||||
left,
|
||||
bottom: Math.max(12, window.innerHeight - rect.top + 8),
|
||||
top,
|
||||
width,
|
||||
maxHeight,
|
||||
});
|
||||
}, []);
|
||||
|
||||
@@ -1096,10 +1125,15 @@ function ResourceReferenceEditor({
|
||||
aria-modal="false"
|
||||
aria-label="选择素材"
|
||||
style={{
|
||||
// 与 `@` 候选菜单同一坐标系(fixed + top + 高度钳制):底边锚点在
|
||||
// 输入框上方会被顶出视口,只有钉住顶边并收紧高度才能保证整块面板可见。
|
||||
position: 'fixed',
|
||||
top: `${pickerPosition.top}px`,
|
||||
left: `${pickerPosition.left}px`,
|
||||
bottom: `${pickerPosition.bottom}px`,
|
||||
right: 'auto',
|
||||
bottom: 'auto',
|
||||
width: `${pickerPosition.width}px`,
|
||||
maxHeight: `${pickerPosition.maxHeight}px`,
|
||||
}}
|
||||
>
|
||||
<header>
|
||||
|
||||
+208
-25
@@ -1,12 +1,31 @@
|
||||
import './resourceCanvasGenerationPanel.css';
|
||||
|
||||
import { Sparkles, X } from 'lucide-react';
|
||||
import { type FormEvent, useState } from 'react';
|
||||
import { type CSSProperties, type FormEvent, useState } from 'react';
|
||||
|
||||
import { PlatformActionButton } from '../../../../../packages/shared/src/components/PlatformActionButton';
|
||||
import { PlatformSegmentedTabs } from '../../../../../packages/shared/src/components/PlatformSegmentedTabs';
|
||||
import { PlatformTextField } from '../../../../../packages/shared/src/components/PlatformTextField';
|
||||
import type {
|
||||
GameCreationAppAssetManifestEntry,
|
||||
GameIterationVersion,
|
||||
} from '../../../../../packages/shared/src/contracts/gameCreationApp';
|
||||
import { resolveEditorImageSizeLabel } from '../../../../../src/components/image-editor/ImageCanvasGenerationModel';
|
||||
import { ThemedModal } from '../../components/modal/ThemedModal';
|
||||
import { resourceEditPromptMaxLength } from '../../view/project-development/resourceEditModel';
|
||||
import { ResourceReferenceInput } from '../project-workspace/ResourceReferenceInput';
|
||||
import type {
|
||||
ChatComposerDraft,
|
||||
ChatReference,
|
||||
} from '../project-workspace/resourceReferences';
|
||||
import {
|
||||
resourceCanvasAssetGenerationAcceptsReferences,
|
||||
resourceCanvasAssetGenerationReferenceAssets,
|
||||
resourceCanvasAssetGenerationReferenceError,
|
||||
resourceCanvasAssetGenerationReferenceIds,
|
||||
resourceCanvasAssetGenerationReferenceIssue,
|
||||
resourceCanvasAssetGenerationUserReferenceLimit,
|
||||
} from './resourceCanvasAssetGenerationReferenceModel';
|
||||
import {
|
||||
RESOURCE_CANVAS_ASSET_ASPECT_RATIOS,
|
||||
RESOURCE_CANVAS_ASSET_IMAGE_SIZES,
|
||||
@@ -20,6 +39,14 @@ export type ResourceCanvasAssetGenerationSubmitInput = {
|
||||
assetName: string;
|
||||
aspectRatio: string;
|
||||
imageSize: string;
|
||||
/**
|
||||
* 本次生成的参考图引用(面板草稿与重开草稿的同一种形状)。
|
||||
*
|
||||
* 宿主从这里取 `resourceId`(**当前项目 manifest 的资产 ID**,按选择顺序去重)交给原生侧;
|
||||
* 原生据此读本地正式文件并按当前账号重新建立远端绑定,不接受本地路径,也不复用 manifest 里
|
||||
* 历史账号的远端 ID。
|
||||
*/
|
||||
references: ChatReference[];
|
||||
};
|
||||
|
||||
/** 提交面板的草稿:点击即关闭之后,只有「即时失败」重开时才需要把这份草稿带回来。 */
|
||||
@@ -28,6 +55,8 @@ export type ResourceCanvasAssetGenerationPanelDraft = {
|
||||
assetName: string;
|
||||
aspectRatio: string;
|
||||
imageSize: string;
|
||||
/** 提示词里的 `@显示名` 引用节点;参考选择器的候选项与它们同源。 */
|
||||
references: ChatReference[];
|
||||
};
|
||||
|
||||
export type ResourceCanvasAssetGenerationPanelViewProps = {
|
||||
@@ -40,6 +69,25 @@ export type ResourceCanvasAssetGenerationPanelViewProps = {
|
||||
draft?: ResourceCanvasAssetGenerationPanelDraft;
|
||||
/** 上一次即时失败的原因;重开时直接以 `role="alert"` 呈现。 */
|
||||
error?: string | null;
|
||||
/** 当前项目的 manifest 资产:参考选择的候选集由它收口到本项目的已登记图片。 */
|
||||
assets?: readonly GameCreationAppAssetManifestEntry[];
|
||||
/** `@` 引用选择器需要项目路径来登记资源预览,与快速编辑走同一条链路。 */
|
||||
projectPath?: string;
|
||||
versions?: GameIterationVersion[];
|
||||
activeVersionId?: string | null;
|
||||
/**
|
||||
* 呈现形态。
|
||||
*
|
||||
* `modal`:既有居中弹层(`ThemedModal` + 焦点陷阱)。`floating`:挂在画布占位卡下沿的
|
||||
* **独立浮层**——工具点击先建占位,浮层只是它旁边的一块 UI。
|
||||
*
|
||||
* 生成浮层必须走 `floating`:`ThemedModal` 的焦点陷阱会把 `@` 引用选择器(portal 到 body 的
|
||||
* `resource-reference-picker`)挡在陷阱之外,候选项点了不生效。浮层不是模态,因此不受这条限制;
|
||||
* 「关闭浮层不等于取消后台任务」的语义也由浮层形态直接成立。
|
||||
*/
|
||||
variant?: 'modal' | 'floating';
|
||||
/** 浮层形态的定位样式(贴着占位卡下沿,与快速编辑 / 信息浮层同一条锚点口径)。 */
|
||||
style?: CSSProperties | null;
|
||||
/**
|
||||
* 提交回调:**同步返回**,面板不等它的结果。
|
||||
*
|
||||
@@ -47,7 +95,13 @@ export type ResourceCanvasAssetGenerationPanelViewProps = {
|
||||
* 面板自己不持有任何在途状态。
|
||||
*/
|
||||
onSubmit: (input: ResourceCanvasAssetGenerationSubmitInput) => void;
|
||||
onClose: () => void;
|
||||
/**
|
||||
* 收起浮层。
|
||||
*
|
||||
* 参数是当前草稿:宿主保存它,用户再点开占位卡时接着编辑(关闭 ≠ 丢弃输入,不是空表单)。
|
||||
* 提交后的关闭不带草稿——这次输入已经被任务接走,重试身份也在宿主的提交上下文里。
|
||||
*/
|
||||
onClose: (draft?: ResourceCanvasAssetGenerationPanelDraft) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -73,10 +127,19 @@ export function ResourceCanvasAssetGenerationPanelView({
|
||||
action,
|
||||
draft,
|
||||
error: initialError,
|
||||
assets,
|
||||
projectPath,
|
||||
versions,
|
||||
activeVersionId,
|
||||
variant = 'modal',
|
||||
style,
|
||||
onSubmit,
|
||||
onClose,
|
||||
}: ResourceCanvasAssetGenerationPanelViewProps) {
|
||||
const [prompt, setPrompt] = useState(draft?.prompt ?? '');
|
||||
const [references, setReferences] = useState<ChatReference[]>(
|
||||
draft?.references ?? [],
|
||||
);
|
||||
const [assetName, setAssetName] = useState(
|
||||
draft?.assetName ?? action.assetName,
|
||||
);
|
||||
@@ -90,13 +153,71 @@ export function ResourceCanvasAssetGenerationPanelView({
|
||||
// 提示词上限复用资源编辑模型的同一份口径:图片类入口默认 32000,与 Rust
|
||||
// `LOCAL_PROJECT_ASSET_MAX_PROMPT_CHARS` 一致,不在面板里另抄常量。
|
||||
const promptMaxLength = resourceEditPromptMaxLength('image-reference');
|
||||
const canSubmit = prompt.trim().length > 0 && assetName.trim().length > 0;
|
||||
/**
|
||||
* 参考选择只对有真实参考能力的入口呈现。
|
||||
*
|
||||
* 图集只接受单张规范引用、图标规范本身就是权威规范图产出方:这两类入口不给选择器,
|
||||
* 原生侧同样拒绝额外参考(不是静默丢弃)。
|
||||
*/
|
||||
const referenceEnabled = resourceCanvasAssetGenerationAcceptsReferences(action);
|
||||
const referenceLimit =
|
||||
resourceCanvasAssetGenerationUserReferenceLimit(action);
|
||||
const referenceAssets = resourceCanvasAssetGenerationReferenceAssets(
|
||||
assets ?? [],
|
||||
);
|
||||
const referenceAssetIds =
|
||||
resourceCanvasAssetGenerationReferenceIds(references);
|
||||
const referenceError = resourceCanvasAssetGenerationReferenceError({
|
||||
action,
|
||||
referenceCount: referenceAssetIds.length,
|
||||
});
|
||||
/*
|
||||
陈旧引用(素材被删 / 改了类型 / 没有本地文件)必须在提交前报出来:过滤掉再提交等于
|
||||
把「带参考」变成「无参考」的付费生成,用户还以为参考生效了。
|
||||
*/
|
||||
const referenceIssue = referenceEnabled
|
||||
? resourceCanvasAssetGenerationReferenceIssue({
|
||||
references,
|
||||
assets: assets ?? [],
|
||||
})
|
||||
: null;
|
||||
const promptTooLong = prompt.trim().length > promptMaxLength;
|
||||
const promptTooLongError = promptTooLong
|
||||
? `生成提示词最多 ${promptMaxLength} 个字符,当前 ${prompt.trim().length} 个`
|
||||
: null;
|
||||
const canSubmit =
|
||||
prompt.trim().length > 0 &&
|
||||
assetName.trim().length > 0 &&
|
||||
!referenceError &&
|
||||
!referenceIssue &&
|
||||
!promptTooLong;
|
||||
const shownError = error ?? referenceIssue ?? promptTooLongError ?? referenceError;
|
||||
const applyDraft = (next: ChatComposerDraft) => {
|
||||
setPrompt(next.text);
|
||||
setReferences(next.references);
|
||||
};
|
||||
/** 收起浮层:把当前草稿交给宿主保存,用户再点开占位卡时接着编辑。 */
|
||||
const closeWithDraft = () =>
|
||||
onClose({
|
||||
prompt,
|
||||
assetName,
|
||||
aspectRatio,
|
||||
imageSize,
|
||||
references,
|
||||
});
|
||||
|
||||
function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const normalizedPrompt = prompt.trim();
|
||||
const normalizedAssetName = assetName.trim();
|
||||
if (!normalizedPrompt || !normalizedAssetName) {
|
||||
// 超限与超长在提交入口再挡一次:按钮禁用只是表现,不能当唯一防线。
|
||||
if (
|
||||
!normalizedPrompt ||
|
||||
!normalizedAssetName ||
|
||||
referenceError ||
|
||||
referenceIssue ||
|
||||
promptTooLong
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
@@ -108,17 +229,14 @@ export function ResourceCanvasAssetGenerationPanelView({
|
||||
assetName: normalizedAssetName,
|
||||
aspectRatio,
|
||||
imageSize,
|
||||
references,
|
||||
});
|
||||
// 提交后的关闭不带草稿:这次输入已经被任务接走,重试身份在宿主的提交上下文里。
|
||||
onClose();
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemedModal
|
||||
open
|
||||
ariaLabel={action.label}
|
||||
onClose={onClose}
|
||||
panelClassName="game-approval-dialog game-resource-generation-dialog"
|
||||
>
|
||||
const panelBody = (
|
||||
<>
|
||||
<header>
|
||||
<div>
|
||||
<h2>{action.label}</h2>
|
||||
@@ -126,7 +244,7 @@ export function ResourceCanvasAssetGenerationPanelView({
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`关闭${action.label}`}
|
||||
onClick={onClose}
|
||||
onClick={closeWithDraft}
|
||||
>
|
||||
<X size={16} aria-hidden="true" />
|
||||
</button>
|
||||
@@ -143,16 +261,40 @@ export function ResourceCanvasAssetGenerationPanelView({
|
||||
</label>
|
||||
<label>
|
||||
<span>生成提示词</span>
|
||||
<PlatformTextField
|
||||
variant="textarea"
|
||||
aria-label="生成提示词"
|
||||
rows={6}
|
||||
autoFocus
|
||||
maxLength={promptMaxLength}
|
||||
placeholder={action.promptPlaceholder}
|
||||
value={prompt}
|
||||
onChange={(event) => setPrompt(event.currentTarget.value)}
|
||||
/>
|
||||
{referenceEnabled ? (
|
||||
/*
|
||||
与聊天输入区、资源快速编辑同一个 `@` 引用输入区:候选、`@显示名` 文本与引用模型都
|
||||
复用那一份,所以参考图带的是**稳定资源 ID**(进而出站到当前账号绑定下的远端资源),
|
||||
不是只有名字的纯提示词。候选集只放当前项目的已登记图片。
|
||||
*/
|
||||
<div className="resource-canvas-asset-generation-prompt-input">
|
||||
<ResourceReferenceInput
|
||||
ariaLabel="生成提示词"
|
||||
value={prompt}
|
||||
references={references}
|
||||
onChange={applyDraft}
|
||||
assets={referenceAssets}
|
||||
projectPath={projectPath ?? ''}
|
||||
versions={versions}
|
||||
activeVersionId={activeVersionId}
|
||||
multiline
|
||||
rows={6}
|
||||
placeholder={`${action.promptPlaceholder}(可用 @ 选择参考图)`}
|
||||
showPolishAction={false}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<PlatformTextField
|
||||
variant="textarea"
|
||||
aria-label="生成提示词"
|
||||
rows={6}
|
||||
autoFocus
|
||||
maxLength={promptMaxLength}
|
||||
placeholder={action.promptPlaceholder}
|
||||
value={prompt}
|
||||
onChange={(event) => setPrompt(event.currentTarget.value)}
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
{action.adjustableDimensions ? (
|
||||
<div className="resource-canvas-asset-generation-dimensions">
|
||||
@@ -197,16 +339,26 @@ export function ResourceCanvasAssetGenerationPanelView({
|
||||
prompt={prompt}
|
||||
applyPrompt={setPrompt}
|
||||
/>
|
||||
{error ? (
|
||||
{referenceEnabled && referenceLimit > 0 ? (
|
||||
<p
|
||||
className="resource-canvas-asset-generation-reference-hint"
|
||||
data-resource-canvas-generation-reference-count={
|
||||
referenceAssetIds.length
|
||||
}
|
||||
>
|
||||
{`参考图 ${referenceAssetIds.length}/${referenceLimit}`}
|
||||
</p>
|
||||
) : null}
|
||||
{shownError ? (
|
||||
<p className="game-resource-generation-error" role="alert">
|
||||
{error}
|
||||
{shownError}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="game-resource-generation-actions">
|
||||
<PlatformActionButton
|
||||
type="button"
|
||||
tone="secondary"
|
||||
onClick={onClose}
|
||||
onClick={closeWithDraft}
|
||||
>
|
||||
取消
|
||||
</PlatformActionButton>
|
||||
@@ -216,6 +368,37 @@ export function ResourceCanvasAssetGenerationPanelView({
|
||||
</PlatformActionButton>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
|
||||
if (variant === 'floating') {
|
||||
return (
|
||||
<section
|
||||
/*
|
||||
与模态共用同一套面板 chrome:`game-approval-dialog` 提供边框/圆角/底色/内边距与
|
||||
`> header` 排布,`game-resource-generation-dialog` 提供表单宽度口径。少任何一个,
|
||||
浮层就会退化成没有背景边框、标题挤在一起的一块裸容器(真实浏览器复现过)。
|
||||
*/
|
||||
className="game-approval-dialog game-resource-generation-dialog resource-canvas-generation-floating-panel"
|
||||
role="dialog"
|
||||
aria-label={action.label}
|
||||
data-resource-canvas-generation-floating-panel=""
|
||||
style={style ?? undefined}
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
>
|
||||
{panelBody}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemedModal
|
||||
open
|
||||
ariaLabel={action.label}
|
||||
onClose={closeWithDraft}
|
||||
panelClassName="game-approval-dialog game-resource-generation-dialog"
|
||||
>
|
||||
{panelBody}
|
||||
</ThemedModal>
|
||||
);
|
||||
}
|
||||
|
||||
+84
-14
@@ -1,5 +1,5 @@
|
||||
import { Sparkles, X } from 'lucide-react';
|
||||
import { type FormEvent, useRef, useState } from 'react';
|
||||
import { type CSSProperties, type FormEvent, useRef, useState } from 'react';
|
||||
|
||||
import { PlatformActionButton } from '../../../../../packages/shared/src/components/PlatformActionButton';
|
||||
import { PlatformSegmentedTabs } from '../../../../../packages/shared/src/components/PlatformSegmentedTabs';
|
||||
@@ -36,8 +36,45 @@ export type ResourceCanvasGenerationPanelViewProps = {
|
||||
*/
|
||||
kinds?: readonly ResourceCanvasGenerationKind[];
|
||||
initialKind?: ResourceCanvasGenerationKind;
|
||||
/**
|
||||
* 呈现形态。
|
||||
*
|
||||
* 面板底部栏目的音频入口(音效 / 背景音乐)与「生成素材」入口一样:工具点击先在当前栏目
|
||||
* 建占位卡,浮层挂在占位卡下沿。占位与浮层的归属由宿主按 `draftId` 维护,面板只负责这一份
|
||||
* 草稿与失败重试。
|
||||
*/
|
||||
variant?: 'modal' | 'floating';
|
||||
style?: CSSProperties | null;
|
||||
/**
|
||||
* 初始草稿(音频 / 背景音乐入口用)。
|
||||
*
|
||||
* 用户收起浮层后草稿由宿主保存,再点开占位卡时从这里灌回来——**不是**空表单,
|
||||
* 用户不必重打一遍提示词。
|
||||
*/
|
||||
initialDraft?: {
|
||||
kind: ResourceCanvasGenerationKind;
|
||||
prompt: string;
|
||||
assetName: string;
|
||||
} | null;
|
||||
/**
|
||||
* 已绑定的提交身份。
|
||||
*
|
||||
* 同一次草稿的重试必须复用同一对 `operationId` / 幂等键:原生按 operation 记账,换一对就是
|
||||
* 一次**新的**付费生成。宿主把首次提交铸造的身份记在占位上,收起来再点开时灌回来。
|
||||
*/
|
||||
request?: ResourceEditRequestIdentity | null;
|
||||
onSubmit: (input: ResourceCanvasGenerationSubmitInput) => Promise<void>;
|
||||
onClose: () => void;
|
||||
/**
|
||||
* 收起浮层。
|
||||
*
|
||||
* 参数是当前草稿:宿主把它存起来,用户再点开占位卡时能接着编辑(关闭 ≠ 丢弃输入)。
|
||||
* 提交成功后的关闭不带草稿(这次输入已经被任务接走)。
|
||||
*/
|
||||
onClose: (draft?: {
|
||||
kind: ResourceCanvasGenerationKind;
|
||||
prompt: string;
|
||||
assetName: string;
|
||||
}) => void;
|
||||
};
|
||||
|
||||
const RESOURCE_GENERATION_ALL_KIND_ITEMS =
|
||||
@@ -66,6 +103,10 @@ function resourceGenerationErrorMessage(error: unknown) {
|
||||
export function ResourceCanvasGenerationPanelView({
|
||||
kinds = RESOURCE_CANVAS_GENERATION_OPTIONS.map((option) => option.kind),
|
||||
initialKind,
|
||||
variant = 'modal',
|
||||
style,
|
||||
initialDraft,
|
||||
request: boundRequest,
|
||||
onSubmit,
|
||||
onClose,
|
||||
}: ResourceCanvasGenerationPanelViewProps) {
|
||||
@@ -83,16 +124,23 @@ export function ResourceCanvasGenerationPanelView({
|
||||
const option = resourceCanvasGenerationOption(kind);
|
||||
const panelTitle =
|
||||
allowedOptions.length === 1 ? option.generationLabel : '生成素材';
|
||||
const [prompt, setPrompt] = useState('');
|
||||
const [assetName, setAssetName] = useState(option.assetName);
|
||||
const [prompt, setPrompt] = useState(initialDraft?.prompt ?? '');
|
||||
const [assetName, setAssetName] = useState(
|
||||
initialDraft?.assetName ?? option.assetName,
|
||||
);
|
||||
const [attempted, setAttempted] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// 请求身份绑定到铸造时的那句提示词:失败重试命中同一 operation 账本,提示词变了就重铸
|
||||
// (Rust 的 request_fingerprint 含 prompt,复用旧身份会被拒)。面板在首次提交后锁定
|
||||
// 输入,正常路径下提示词不会漂移;这里按同一口径收口,不依赖「锁」这层间接保证。
|
||||
const requestRef = useRef<ResourceEditRequestIdentity | null>(null);
|
||||
const requestRef = useRef<ResourceEditRequestIdentity | null>(
|
||||
boundRequest ?? null,
|
||||
);
|
||||
const inputLocked = attempted || submitting;
|
||||
/** 收起浮层:把当前草稿交给宿主保存,用户再点开占位卡时接着编辑。 */
|
||||
const closeWithDraft = () =>
|
||||
onClose({ kind, prompt, assetName: assetName.trim() || option.assetName });
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
@@ -125,13 +173,8 @@ export function ResourceCanvasGenerationPanelView({
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemedModal
|
||||
open
|
||||
ariaLabel={panelTitle}
|
||||
onClose={onClose}
|
||||
panelClassName="game-approval-dialog game-resource-generation-dialog"
|
||||
>
|
||||
const panelBody = (
|
||||
<>
|
||||
<header>
|
||||
<div>
|
||||
<h2>{panelTitle}</h2>
|
||||
@@ -139,7 +182,7 @@ export function ResourceCanvasGenerationPanelView({
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`关闭${panelTitle}`}
|
||||
onClick={onClose}
|
||||
onClick={closeWithDraft}
|
||||
>
|
||||
<X size={16} aria-hidden="true" />
|
||||
</button>
|
||||
@@ -200,7 +243,7 @@ export function ResourceCanvasGenerationPanelView({
|
||||
<PlatformActionButton
|
||||
type="button"
|
||||
tone="secondary"
|
||||
onClick={onClose}
|
||||
onClick={closeWithDraft}
|
||||
>
|
||||
{submitting ? '后台运行并关闭' : '取消'}
|
||||
</PlatformActionButton>
|
||||
@@ -222,6 +265,33 @@ export function ResourceCanvasGenerationPanelView({
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
|
||||
if (variant === 'floating') {
|
||||
return (
|
||||
<section
|
||||
// 与模态共用面板 chrome(边框/圆角/底色/内边距 + `> header` 排布),浮层不另造外观。
|
||||
className="game-approval-dialog game-resource-generation-dialog resource-canvas-generation-floating-panel"
|
||||
role="dialog"
|
||||
aria-label={panelTitle}
|
||||
data-resource-canvas-generation-floating-panel=""
|
||||
style={style ?? undefined}
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
>
|
||||
{panelBody}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemedModal
|
||||
open
|
||||
ariaLabel={panelTitle}
|
||||
onClose={closeWithDraft}
|
||||
panelClassName="game-approval-dialog game-resource-generation-dialog"
|
||||
>
|
||||
{panelBody}
|
||||
</ThemedModal>
|
||||
);
|
||||
}
|
||||
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
import './resourceCanvasGenerationPanel.css';
|
||||
|
||||
import { Sparkles, X } from 'lucide-react';
|
||||
import type { PointerEvent as ReactPointerEvent } from 'react';
|
||||
|
||||
import {
|
||||
RESOURCE_CANVAS_GENERATION_PLACEHOLDER_STATUS_LABELS,
|
||||
type ResourceCanvasGenerationPlaceholder,
|
||||
} from './resourceCanvasGenerationPlaceholderModel';
|
||||
|
||||
export type ResourceCanvasGenerationPlaceholderCardViewProps = {
|
||||
placeholder: ResourceCanvasGenerationPlaceholder;
|
||||
/** 生成浮层是否正挂在这张占位下面:决定卡片的高亮与浮层开合。 */
|
||||
active: boolean;
|
||||
/** 拖动中:卡片只跟指针走,不参与任何过渡。 */
|
||||
dragging: boolean;
|
||||
onPointerDown: (event: ReactPointerEvent<HTMLDivElement>) => void;
|
||||
onPointerMove: (event: ReactPointerEvent<HTMLDivElement>) => void;
|
||||
onPointerUp: (event: ReactPointerEvent<HTMLDivElement>) => void;
|
||||
onPointerCancel: (event: ReactPointerEvent<HTMLDivElement>) => void;
|
||||
/** 点击卡片(不是删除按钮):打开 / 收起挂在它下面的生成浮层。 */
|
||||
onTogglePanel: () => void;
|
||||
/** 删除占位:只隐藏展示,不取消后台任务。 */
|
||||
onRemove: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* 画布上的生成占位卡。
|
||||
*
|
||||
* 它**不是**正式资源卡:没有 manifest 身份、没有预览、不参与资源投影与布局 sidecar,
|
||||
* 只在宿主临时状态里活到「提交成功落卡」或「用户删掉它」为止。点击它开 / 收挂在它下沿的
|
||||
* 独立生成浮层,拖动改的是宿主内存里的坐标(结果卡最终落在同一条最新位置)。
|
||||
*
|
||||
* 指针事件的接管只到本组件为止:`stopPropagation` 阻止画布的框选 / 平移当作空白处处理。
|
||||
*/
|
||||
export function ResourceCanvasGenerationPlaceholderCardView({
|
||||
placeholder,
|
||||
active,
|
||||
dragging,
|
||||
onPointerDown,
|
||||
onPointerMove,
|
||||
onPointerUp,
|
||||
onPointerCancel,
|
||||
onTogglePanel,
|
||||
onRemove,
|
||||
}: ResourceCanvasGenerationPlaceholderCardViewProps) {
|
||||
return (
|
||||
<div
|
||||
className={`game-resource-generation-placeholder${active ? ' is-active' : ''}${dragging ? ' is-dragging' : ''}`}
|
||||
data-resource-canvas-generation-placeholder={placeholder.draftId}
|
||||
data-resource-canvas-generation-placeholder-status={placeholder.status}
|
||||
style={{
|
||||
left: placeholder.x,
|
||||
top: placeholder.y,
|
||||
width: placeholder.width,
|
||||
height: placeholder.height,
|
||||
}}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={`${placeholder.assetName}(${RESOURCE_CANVAS_GENERATION_PLACEHOLDER_STATUS_LABELS[placeholder.status]})`}
|
||||
onPointerDown={onPointerDown}
|
||||
onPointerMove={onPointerMove}
|
||||
onPointerUp={onPointerUp}
|
||||
onPointerCancel={onPointerCancel}
|
||||
onLostPointerCapture={onPointerCancel}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onTogglePanel();
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== 'Enter' && event.key !== ' ') {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
onTogglePanel();
|
||||
}}
|
||||
>
|
||||
<Sparkles size={18} aria-hidden="true" />
|
||||
<strong>{placeholder.assetName}</strong>
|
||||
<small>
|
||||
{RESOURCE_CANVAS_GENERATION_PLACEHOLDER_STATUS_LABELS[placeholder.status]}
|
||||
</small>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`删除占位 ${placeholder.assetName}`}
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onRemove();
|
||||
}}
|
||||
>
|
||||
<X size={12} aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+36
-1
@@ -1,4 +1,4 @@
|
||||
import { Download, Upload, X } from 'lucide-react';
|
||||
import { Download, ListFilter, Upload, X } from 'lucide-react';
|
||||
import { useEffect, useId, useRef } from 'react';
|
||||
|
||||
import type { ResourceCanvasPanelEntry } from './resourceCanvasAssetTransferModel';
|
||||
@@ -20,6 +20,16 @@ export type ResourceCanvasPanelViewProps = {
|
||||
onToggleEntry: (resourceId: string) => void;
|
||||
onSelectAll: () => void;
|
||||
onClearSelection: () => void;
|
||||
/**
|
||||
* 批量追加标签入口。由宿主给出「当前完整选中集」解析出的实际目标数量与禁用原因:
|
||||
* 数量按去重后的已登记素材算(跨筛选保留的选择也算在内),不是只算面板可见项。
|
||||
* 未传时动作行不出现该入口。
|
||||
*/
|
||||
batchTags?: {
|
||||
targetCount: number;
|
||||
blockedReason: string | null;
|
||||
onOpen: () => void;
|
||||
};
|
||||
onUploadFiles: (files: FileList) => void;
|
||||
onDownloadSelection: () => void;
|
||||
isUploading: boolean;
|
||||
@@ -38,6 +48,7 @@ export function ResourceCanvasPanelView({
|
||||
onToggleEntry,
|
||||
onSelectAll,
|
||||
onClearSelection,
|
||||
batchTags,
|
||||
onUploadFiles,
|
||||
onDownloadSelection,
|
||||
isUploading,
|
||||
@@ -140,6 +151,23 @@ export function ResourceCanvasPanelView({
|
||||
>
|
||||
清空选择
|
||||
</button>
|
||||
{batchTags ? (
|
||||
<button
|
||||
type="button"
|
||||
className="game-resource-panel-batch-tags"
|
||||
// 禁用原因走 title + 下方可见提示:混合选择(版本 / 未登记附件 /
|
||||
// 已删除资源)或超限时不能只对其中一部分静默保存,
|
||||
// 所以入口直接禁用而不是点进去再失败。
|
||||
title={batchTags.blockedReason ?? undefined}
|
||||
disabled={batchTags.blockedReason !== null}
|
||||
onClick={batchTags.onOpen}
|
||||
>
|
||||
<ListFilter size={15} aria-hidden="true" />
|
||||
{batchTags.targetCount > 1
|
||||
? `批量标签(${batchTags.targetCount})`
|
||||
: '批量标签'}
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="game-resource-panel-download"
|
||||
@@ -155,6 +183,13 @@ export function ResourceCanvasPanelView({
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{batchTags?.blockedReason ? (
|
||||
<p
|
||||
className="game-resource-panel-batch-tag-reason"
|
||||
role="status"
|
||||
>{`批量标签不可用:${batchTags.blockedReason}`}</p>
|
||||
) : null}
|
||||
|
||||
{notice ? (
|
||||
<p className="game-resource-panel-notice" role="status">
|
||||
{notice}
|
||||
|
||||
+5
@@ -152,7 +152,12 @@ export function createResourceCanvasAssetGenerationQueue(
|
||||
aspectRatio: task.aspectRatio,
|
||||
imageSize: task.imageSize,
|
||||
assetName: task.assetName,
|
||||
referenceAssetIds: task.referenceAssetIds,
|
||||
outputPath: task.outputPath,
|
||||
// 入口栏目:原生支持时按它登记归类;不支持时后端忽略,落点仍按正式归类走。
|
||||
...(task.targetCategory
|
||||
? { targetCategory: task.targetCategory }
|
||||
: {}),
|
||||
})) as LocalProjectAssetGenerationTaskRecord;
|
||||
let started: LocalProjectAssetGenerationTaskRecord;
|
||||
try {
|
||||
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
import type { GameCreationAppAssetManifestEntry } from '../../../../../packages/shared/src/contracts/gameCreationApp';
|
||||
import type { ChatReference } from '../project-workspace/resourceReferences';
|
||||
import type { ResourceCanvasAssetToolAction } from './resourceCanvasBottomToolbarModel';
|
||||
|
||||
/**
|
||||
* 参考图上限:一次生成请求里 `referenceImageSrcs` 的总数,**含**规范图。
|
||||
*
|
||||
* 与 Rust `PLATFORM_ART_MAX_REFERENCE_IMAGES` 同口径:面板负责在提交前挡住超限,原生侧再挡一次,
|
||||
* 两侧都不做截断(截断就是静默丢弃用户的选择)。
|
||||
*/
|
||||
export const RESOURCE_CANVAS_ASSET_GENERATION_MAX_REFERENCES = 5;
|
||||
|
||||
/** 没有规范图前置时的用户参考上限。 */
|
||||
export const RESOURCE_CANVAS_ASSET_GENERATION_MAX_USER_REFERENCES = 5;
|
||||
|
||||
/** 有规范图前置时:权威规范图自己占掉一张,用户参考最多四张。 */
|
||||
export const RESOURCE_CANVAS_ASSET_GENERATION_MAX_USER_REFERENCES_WITH_SPEC = 4;
|
||||
|
||||
/**
|
||||
* 不接受用户参考的生成类型。
|
||||
*
|
||||
* 目前只有 `art-spritesheet`(图集)按合同只接受单张规范引用:这类入口不呈现用户参考选择器,
|
||||
* 原生提交也会显式拒绝额外参考(不是静默丢弃)。
|
||||
*
|
||||
* 其它入口一律支持用户参考,包括 `icon-spec`(图标规范):它虽然产出权威规范图,但生成时同样
|
||||
* 可以带参考图,上限与普通生成一致。
|
||||
*/
|
||||
const RESOURCE_CANVAS_ASSET_GENERATION_REFERENCE_FREE_KINDS: readonly string[] = [
|
||||
'art-spritesheet',
|
||||
];
|
||||
|
||||
export function resourceCanvasAssetGenerationAcceptsReferences(
|
||||
action: ResourceCanvasAssetToolAction,
|
||||
): boolean {
|
||||
return !RESOURCE_CANVAS_ASSET_GENERATION_REFERENCE_FREE_KINDS.includes(
|
||||
action.assetKind,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 该入口允许用户选几张参考。
|
||||
*
|
||||
* `0` 表示不呈现参考选择器;其余值与原生侧的用户参考上限一致。
|
||||
*/
|
||||
export function resourceCanvasAssetGenerationUserReferenceLimit(
|
||||
action: ResourceCanvasAssetToolAction,
|
||||
): number {
|
||||
if (!resourceCanvasAssetGenerationAcceptsReferences(action)) {
|
||||
return 0;
|
||||
}
|
||||
return action.requiresIconSpecReference
|
||||
? RESOURCE_CANVAS_ASSET_GENERATION_MAX_USER_REFERENCES_WITH_SPEC
|
||||
: RESOURCE_CANVAS_ASSET_GENERATION_MAX_USER_REFERENCES;
|
||||
}
|
||||
|
||||
/**
|
||||
* 参考选择的候选集:**当前项目**已登记的图片。
|
||||
*
|
||||
* 直接吃当前 manifest 的 `assets`,所以候选天然限定在同一项目内;再按媒体类型收口到图片,
|
||||
* 文档、音视频、字体、代码与未落盘的占位都不进候选。清单里没有 `localPath` 的记录(例如只存在于
|
||||
* 远端画布、本地还没有文件的条目)同样排除——原生侧要读本地正式文件才能按当前账号重新上传绑定。
|
||||
*/
|
||||
export function resourceCanvasAssetGenerationReferenceAssets(
|
||||
assets: readonly GameCreationAppAssetManifestEntry[],
|
||||
): GameCreationAppAssetManifestEntry[] {
|
||||
return assets.filter(
|
||||
(asset) =>
|
||||
resourceCanvasAssetGenerationReferenceMediaTypeSupported(asset.mediaType) &&
|
||||
asset.localPath.trim().length > 0 &&
|
||||
!asset.localPath.startsWith('.agent/'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 参考图只收**原生真的能读**的栅格图片。
|
||||
*
|
||||
* 原生侧按 `image::load_from_memory` 解码参考图,它不认识 SVG:把 `.svg` 放进候选,用户选中后
|
||||
* 提交必失败(而且是一次付费请求的失败)。所以这里显式排除 SVG,其余 `image/*` 一律放行——
|
||||
* 不做「只许 png/jpeg」这种凭空收窄,真实支持范围由原生解码器决定。
|
||||
*/
|
||||
export function resourceCanvasAssetGenerationReferenceMediaTypeSupported(
|
||||
mediaType: string,
|
||||
): boolean {
|
||||
const normalized = mediaType.trim().toLowerCase();
|
||||
if (!normalized.startsWith('image/')) {
|
||||
return false;
|
||||
}
|
||||
return normalized !== 'image/svg+xml' && normalized !== 'image/svg';
|
||||
}
|
||||
|
||||
/**
|
||||
* 从草稿里的引用列表取出本次生成的参考资源 ID。
|
||||
*
|
||||
* 只认资源引用(运行态区域引用不是素材);顺序即用户选择顺序,重复选择同一张按一次算。
|
||||
* 这些 ID 是**当前项目 manifest 的资产 ID**,不是本地路径,也不是历史远端 ID:原生侧据此读本地
|
||||
* 正式文件并按当前账号重新建立远端绑定。
|
||||
*/
|
||||
export function resourceCanvasAssetGenerationReferenceIds(
|
||||
references: readonly ChatReference[],
|
||||
): string[] {
|
||||
const ids: string[] = [];
|
||||
for (const reference of references) {
|
||||
if (reference.type !== 'resource') {
|
||||
continue;
|
||||
}
|
||||
const resourceId = reference.resourceId.trim();
|
||||
if (!resourceId || ids.includes(resourceId)) {
|
||||
continue;
|
||||
}
|
||||
ids.push(resourceId);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交前对参考数量的判据。
|
||||
*
|
||||
* 超限时给一条能照着做的原因,而不是把多出来的引用悄悄丢掉:面板据此禁用提交,
|
||||
* 原生侧仍按同一上限再校验一次。
|
||||
*/
|
||||
export function resourceCanvasAssetGenerationReferenceError({
|
||||
action,
|
||||
referenceCount,
|
||||
}: {
|
||||
action: ResourceCanvasAssetToolAction;
|
||||
referenceCount: number;
|
||||
}): string | null {
|
||||
if (!resourceCanvasAssetGenerationAcceptsReferences(action)) {
|
||||
return null;
|
||||
}
|
||||
const limit = resourceCanvasAssetGenerationUserReferenceLimit(action);
|
||||
if (referenceCount <= limit) {
|
||||
return null;
|
||||
}
|
||||
return action.requiresIconSpecReference
|
||||
? `已选 ${referenceCount} 张参考图;该入口会带上权威规范图,用户参考最多 ${limit} 张`
|
||||
: `已选 ${referenceCount} 张参考图;最多 ${limit} 张`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交前的**陈旧引用**判据:草稿里的引用必须仍然是当前项目已登记、有本地文件的图片。
|
||||
*
|
||||
* 这一步不能省、也不能用过滤糊过去:草稿可能是在素材被删掉 / 改了类型之后才提交的,
|
||||
* 静默过滤会让用户以为「带了那张参考」实际却发了一次无参考的付费生成。所以这里给出明确原因、
|
||||
* 挡住提交,草稿与 `@显示名` 正文都原样保留,由用户自己决定移除还是重选。
|
||||
*/
|
||||
export function resourceCanvasAssetGenerationReferenceIssue({
|
||||
references,
|
||||
assets,
|
||||
}: {
|
||||
references: readonly ChatReference[];
|
||||
assets: readonly GameCreationAppAssetManifestEntry[];
|
||||
}): string | null {
|
||||
for (const reference of references) {
|
||||
if (reference.type !== 'resource') {
|
||||
continue;
|
||||
}
|
||||
const resourceId = reference.resourceId.trim();
|
||||
if (!resourceId) {
|
||||
return '参考图引用缺少资源身份,请重新选择后再提交';
|
||||
}
|
||||
const asset = assets.find((item) => item.id === resourceId);
|
||||
if (!asset) {
|
||||
return `参考图「${reference.label}」已不在当前项目,请移除后再提交`;
|
||||
}
|
||||
if (!asset.mediaType.startsWith('image/')) {
|
||||
return `参考图「${reference.label}」不是图片,不能作为生成参考`;
|
||||
}
|
||||
if (
|
||||
!resourceCanvasAssetGenerationReferenceMediaTypeSupported(asset.mediaType)
|
||||
) {
|
||||
return `参考图「${reference.label}」是矢量图(${asset.mediaType}),暂不支持作为生成参考,请换栅格图片`;
|
||||
}
|
||||
if (
|
||||
!asset.localPath.trim() ||
|
||||
asset.localPath.startsWith('.agent/')
|
||||
) {
|
||||
return `参考图「${reference.label}」没有本地文件,无法作为参考传递`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
+41
@@ -1,3 +1,4 @@
|
||||
import type { ProjectResourceCanvasCategory } from '../../../../../packages/shared/src/contracts/gameCreationApp';
|
||||
import {
|
||||
resolveResourceCanvasBottomTools,
|
||||
type ResourceCanvasAssetToolAction,
|
||||
@@ -34,6 +35,13 @@ export type LocalProjectAssetGenerationTaskRecord = {
|
||||
export type ResourceCanvasAssetGenerationTask = {
|
||||
/** 本地任务 id,同时作为提交给后端的 taskId(重开项目后靠它对上账本记录)。 */
|
||||
taskId: string;
|
||||
/**
|
||||
* 这张任务是从哪个生成占位提交的。
|
||||
*
|
||||
* 成功落点要用**占位的最新位置**、失败重试也要回到同一张占位,所以这条归属必须跟着任务走;
|
||||
* 账本里没有它(后端不认占位),恢复出来的历史任务按 `null` 读。
|
||||
*/
|
||||
draftId: string | null;
|
||||
actionId: string;
|
||||
actionLabel: string;
|
||||
assetKind: string;
|
||||
@@ -41,6 +49,22 @@ export type ResourceCanvasAssetGenerationTask = {
|
||||
prompt: string;
|
||||
aspectRatio: string;
|
||||
imageSize: string;
|
||||
/**
|
||||
* 本次生成携带的参考图(当前项目 manifest 的资产 ID,按选择顺序去重)。
|
||||
*
|
||||
* 派发时随 `referenceAssetIds` 交给原生侧:它读本地正式文件并按当前账号重新建立远端绑定,
|
||||
* 前端不传本地路径,也不复用 manifest 里历史账号的远端资源 ID。恢复出来的历史任务(账本里
|
||||
* 没有这份本地草稿)按空列表读——账本不承诺回放当时的参考选择。
|
||||
*/
|
||||
referenceAssetIds: string[];
|
||||
/**
|
||||
* 这次的**入口栏目**:用户点工具时正在看的那个栏目。
|
||||
*
|
||||
* 原生侧按它把新素材直接登记进该栏目(`targetCategory`,可选入参);原生还没支持时它只是
|
||||
* 一条提示,落点仍按正式归类后的 section 走(见宿主落点 effect)。前端**不做**伪分类:
|
||||
* 归类真相只在 manifest 与原生命令里。
|
||||
*/
|
||||
targetCategory: ProjectResourceCanvasCategory | null;
|
||||
outputPath: string | null;
|
||||
projectId: string;
|
||||
/** 是否已经把这次提交交给后端。未派发的任务只活在本地队列里。 */
|
||||
@@ -143,17 +167,21 @@ export function resourceCanvasAssetGenerationTaskIsTerminal(
|
||||
/** 新提交的任务:先本地排队,派发之前不进后端账本。 */
|
||||
export function createResourceCanvasAssetGenerationTask(input: {
|
||||
taskId: string;
|
||||
draftId?: string | null;
|
||||
action: ResourceCanvasAssetToolAction;
|
||||
prompt: string;
|
||||
assetName: string;
|
||||
aspectRatio: string;
|
||||
imageSize: string;
|
||||
referenceAssetIds?: readonly string[];
|
||||
targetCategory?: ProjectResourceCanvasCategory | null;
|
||||
outputPath: string | null;
|
||||
projectId: string;
|
||||
nowMillis: number;
|
||||
}): ResourceCanvasAssetGenerationTask {
|
||||
return {
|
||||
taskId: input.taskId,
|
||||
draftId: input.draftId ?? null,
|
||||
actionId: input.action.id,
|
||||
actionLabel: input.action.label,
|
||||
assetKind: input.action.assetKind,
|
||||
@@ -161,6 +189,16 @@ export function createResourceCanvasAssetGenerationTask(input: {
|
||||
prompt: input.prompt,
|
||||
aspectRatio: input.aspectRatio,
|
||||
imageSize: input.imageSize,
|
||||
// 参考图去重(保持用户选择顺序):同一张素材在一份草稿里被选两次仍只算一次参考,
|
||||
// 底层工厂也按这条口径收口,不把重复项留给原生侧与远端。
|
||||
referenceAssetIds: [
|
||||
...new Set(
|
||||
(input.referenceAssetIds ?? [])
|
||||
.map((assetId) => assetId.trim())
|
||||
.filter((assetId) => assetId.length > 0),
|
||||
),
|
||||
],
|
||||
targetCategory: input.targetCategory ?? null,
|
||||
outputPath: input.outputPath,
|
||||
projectId: input.projectId,
|
||||
dispatched: false,
|
||||
@@ -183,6 +221,7 @@ export function restoreResourceCanvasAssetGenerationTask(
|
||||
): ResourceCanvasAssetGenerationTask {
|
||||
return {
|
||||
taskId: record.taskId,
|
||||
draftId: null,
|
||||
actionId: `restored:${record.kind}`,
|
||||
actionLabel:
|
||||
resourceCanvasAssetGenerationKindLabel(record.kind) ?? record.assetName,
|
||||
@@ -191,6 +230,8 @@ export function restoreResourceCanvasAssetGenerationTask(
|
||||
prompt: '',
|
||||
aspectRatio: '',
|
||||
imageSize: '',
|
||||
referenceAssetIds: [],
|
||||
targetCategory: null,
|
||||
outputPath: null,
|
||||
projectId: record.projectId,
|
||||
dispatched: true,
|
||||
|
||||
@@ -1092,6 +1092,12 @@
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.game-resource-panel-batch-tag-reason {
|
||||
margin: 0;
|
||||
color: #8c6252;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.game-resource-panel-empty {
|
||||
margin: 0;
|
||||
color: #8c6252;
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* 生成占位卡与「卡下独立浮层」的局部样式。
|
||||
*
|
||||
* 只服务栏目画布上的临时占位(宿主内存态)与挂在它下沿的生成浮层:两者都不是正式素材,
|
||||
* 所以占位卡刻意与资源卡区分开(虚线描边 + 生成图标),避免被误读成已经落地的素材。
|
||||
* 放在独立文件里而不是并进 `resourceCanvasChrome.css`:这条链路可以整体回滚,
|
||||
* 也不与画布手势/卡片展示的改动互相冲突。
|
||||
*/
|
||||
|
||||
.game-resource-generation-placeholder {
|
||||
position: absolute;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
align-content: center;
|
||||
gap: 4px;
|
||||
padding: 8px;
|
||||
border: 1px dashed #c9a493;
|
||||
border-radius: 14px;
|
||||
background: rgb(255 250 247 / 88%);
|
||||
color: #8a6a5c;
|
||||
text-align: center;
|
||||
cursor: grab;
|
||||
user-select: none;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.game-resource-generation-placeholder.is-active {
|
||||
border-color: #e2835a;
|
||||
box-shadow: 0 10px 26px rgb(62 37 27 / 18%);
|
||||
color: #6f4a3b;
|
||||
}
|
||||
|
||||
.game-resource-generation-placeholder.is-dragging {
|
||||
cursor: grabbing;
|
||||
box-shadow: 0 16px 32px rgb(62 37 27 / 24%);
|
||||
}
|
||||
|
||||
.game-resource-generation-placeholder > strong {
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.game-resource-generation-placeholder > small {
|
||||
font-size: 11px;
|
||||
color: #a68a7d;
|
||||
}
|
||||
|
||||
.game-resource-generation-placeholder > button {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.game-resource-generation-placeholder > button:hover {
|
||||
background: rgb(62 37 27 / 10%);
|
||||
}
|
||||
|
||||
/*
|
||||
* 独立浮层:定位与高度由宿主按**真实矩形**算好(贴着占位下沿、上界到画布可用底边),
|
||||
* 这里只负责面板外观与层级。选择器带上 `.game-approval-dialog` 是为了拿到共享面板 chrome
|
||||
* 的优先级:浮层与模态共用同一套 border/圆角/底色/内边距与 `> header` 排布,不另造一套外观。
|
||||
*/
|
||||
.game-approval-dialog.resource-canvas-generation-floating-panel {
|
||||
position: absolute;
|
||||
z-index: 70;
|
||||
/* 锚点给的是占位卡中心:不居中就会整体右偏半个面板宽(真实浏览器 x287 vs 卡中心 286 复现过)。 */
|
||||
transform: translateX(-50%);
|
||||
width: min(560px, calc(100% - 24px));
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
overscroll-behavior: contain;
|
||||
pointer-events: auto;
|
||||
/* 内联 `maxHeight` 按真实画布底边算;这条只是拿不到几何时的兜底上界。 */
|
||||
max-height: min(560px, calc(100dvh - 160px));
|
||||
}
|
||||
|
||||
/*
|
||||
* 提交行固定在浮层底部。
|
||||
*
|
||||
* 面板内容(素材名称 / 提示词 / 规格 / 润色 / 错误)会撑到比可用高度更高,此时滚动只应该发生在
|
||||
* 它自己身上:真实浏览器 1280x720 上提交按钮曾经整块被底栏盖住点不到。`background` 跟随面板
|
||||
* 底色,滚动内容不会从动作行后面透出来。
|
||||
*/
|
||||
.game-approval-dialog.resource-canvas-generation-floating-panel
|
||||
.game-resource-generation-actions {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
z-index: 1;
|
||||
padding-bottom: 2px;
|
||||
background: #fffaf7;
|
||||
}
|
||||
|
||||
.resource-canvas-asset-generation-prompt-input {
|
||||
max-height: 180px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.resource-canvas-asset-generation-reference-hint {
|
||||
margin: 0;
|
||||
color: #9a7d70;
|
||||
font-size: 11px;
|
||||
}
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
import {
|
||||
type CanvasOverlayStyle,
|
||||
resolveQuickEditPanelStyle,
|
||||
} from '../../../../../packages/image-canvas-core/src/overlays';
|
||||
import type { CanvasLayer } from '../../../../../packages/image-canvas-core/src/types';
|
||||
import type { CanvasViewport } from '../../../../../packages/image-canvas-core/src/types';
|
||||
import type { ProjectResourceCanvasCategory } from '../../../../../packages/shared/src/contracts/gameCreationApp';
|
||||
import {
|
||||
GAME_CREATION_RESOURCE_LAYOUT_MAX_COORDINATE,
|
||||
GAME_CREATION_RESOURCE_LAYOUT_MIN_COORDINATE,
|
||||
} from '../../../../../packages/shared/src/contracts/gameCreationApp';
|
||||
import {
|
||||
RESOURCE_CANVAS_CARD_HEIGHT,
|
||||
RESOURCE_CANVAS_CARD_WIDTH,
|
||||
RESOURCE_CANVAS_ROW_GAP,
|
||||
type ResourceCanvasCardSize,
|
||||
} from '../../view/project-development/resourceCanvasLayoutModel';
|
||||
import type { ResourceCanvasAssetToolAction } from './resourceCanvasBottomToolbarModel';
|
||||
import type { ResourceCanvasGenerationKind } from './resourceCanvasGenerationModel';
|
||||
|
||||
/**
|
||||
* 挂在这张占位下的生成浮层是谁。
|
||||
*
|
||||
* 工具点击时就把「哪块面板 + 哪份草稿」一起记在占位上,所以收起浮层后再点占位卡能精确回到
|
||||
* 同一块面板与同一份输入(而不是重新猜一次默认参数)。
|
||||
*/
|
||||
export type ResourceCanvasGenerationPlaceholderPanel =
|
||||
| { route: 'asset'; action: ResourceCanvasAssetToolAction }
|
||||
| {
|
||||
route: 'audio';
|
||||
kinds: readonly ResourceCanvasGenerationKind[];
|
||||
initialKind: ResourceCanvasGenerationKind;
|
||||
};
|
||||
|
||||
/**
|
||||
* 生成占位卡的状态。
|
||||
*
|
||||
* - `draft`:工具刚点开、请求还没交给后端;关掉浮层等于放弃这次草稿。
|
||||
* - `submitted`:已提交,任务在后台跑;关掉浮层**不等于**取消,占位继续显示在途。
|
||||
* - `failed`:这次生成失败;占位留在画布上,点它可以用同一份输入与引用重试。
|
||||
*/
|
||||
export type ResourceCanvasGenerationPlaceholderStatus =
|
||||
| 'draft'
|
||||
| 'submitted'
|
||||
| 'failed';
|
||||
|
||||
/**
|
||||
* 工具点击后先在当前栏目创建的临时占位卡。
|
||||
*
|
||||
* 它是**宿主临时状态**,不是正式素材:不登记 manifest、不进 Agent 可引用资源集、不写布局
|
||||
* sidecar,重开项目也不恢复位置。归属键是 `projectId + draftId`:切项目清掉上一份会话里未提交
|
||||
* 的草稿与界面位置;提交后用 `taskId` 关联后台任务,成功结果落到它的最新位置。
|
||||
*/
|
||||
export type ResourceCanvasGenerationPlaceholder = {
|
||||
/** 本次草稿的独立身份;同一个占位的重试沿用同一个 draftId。 */
|
||||
draftId: string;
|
||||
/** 归属项目:切项目时未提交草稿与界面位置一并作废。 */
|
||||
projectId: string;
|
||||
/** 占位所在的栏目(工具点击时用户正在看的那个栏目)。 */
|
||||
category: ProjectResourceCanvasCategory;
|
||||
actionId: string;
|
||||
actionLabel: string;
|
||||
assetName: string;
|
||||
/** 点这张占位要重新挂上的浮层(工具点击那一刻的动作,含全部默认参数)。 */
|
||||
panel: ResourceCanvasGenerationPlaceholderPanel;
|
||||
/** 画布局部坐标;与同栏目资源卡同一坐标系,拖动只改这里。 */
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
/** 提交后绑定的生成任务 id;未提交为 null。 */
|
||||
taskId: string | null;
|
||||
status: ResourceCanvasGenerationPlaceholderStatus;
|
||||
/** 失败原因(仅失败态有);重试面板据此给出同一条原因。 */
|
||||
error: string | null;
|
||||
};
|
||||
|
||||
/** 占位卡的默认尺寸:与既有资源卡默认格同口径,占位与结果卡不会一大一小。 */
|
||||
export function resourceCanvasGenerationPlaceholderSize(): ResourceCanvasCardSize {
|
||||
return {
|
||||
width: RESOURCE_CANVAS_CARD_WIDTH,
|
||||
height: RESOURCE_CANVAS_CARD_HEIGHT,
|
||||
};
|
||||
}
|
||||
|
||||
type OccupiedPlaceholderRect = {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* 新占位的落点:当前栏目已有内容(资源卡与同栏目其它占位)**下方**的第一个空位。
|
||||
*
|
||||
* 不用「屏幕中心」这类落点:占位必须落在它能被拖动、也能被结果接管的栏目局部坐标里,
|
||||
* 而栏目内容按行铺开,追加在最后一行之下既不会盖住已有卡片,也和自动补位的方向一致。
|
||||
* 空栏目直接落在原点。
|
||||
*/
|
||||
export function placeResourceCanvasGenerationPlaceholder({
|
||||
occupied,
|
||||
}: {
|
||||
occupied: readonly OccupiedPlaceholderRect[];
|
||||
}): { x: number; y: number } {
|
||||
const bottom = occupied.reduce(
|
||||
(current, rect) => Math.max(current, rect.y + rect.height),
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
if (!Number.isFinite(bottom)) {
|
||||
return { x: 0, y: 0 };
|
||||
}
|
||||
const left = occupied.reduce(
|
||||
(current, rect) => Math.min(current, rect.x),
|
||||
Number.POSITIVE_INFINITY,
|
||||
);
|
||||
return {
|
||||
x: Math.round(Number.isFinite(left) ? Math.max(0, left) : 0),
|
||||
y: Math.round(bottom + RESOURCE_CANVAS_ROW_GAP),
|
||||
};
|
||||
}
|
||||
|
||||
/** 拖动落点:与布局模型同一套有限数与范围收口,占位不会被拖到坐标域之外。 */
|
||||
export function moveResourceCanvasGenerationPlaceholder(
|
||||
placeholder: ResourceCanvasGenerationPlaceholder,
|
||||
x: number,
|
||||
y: number,
|
||||
): ResourceCanvasGenerationPlaceholder {
|
||||
const clamp = (value: number) =>
|
||||
Math.min(
|
||||
GAME_CREATION_RESOURCE_LAYOUT_MAX_COORDINATE,
|
||||
Math.max(GAME_CREATION_RESOURCE_LAYOUT_MIN_COORDINATE, Math.round(value)),
|
||||
);
|
||||
return {
|
||||
...placeholder,
|
||||
x: clamp(Number.isFinite(x) ? x : placeholder.x),
|
||||
y: clamp(Number.isFinite(y) ? y : placeholder.y),
|
||||
};
|
||||
}
|
||||
|
||||
/** 提交:把占位与后台任务绑定,之后的终局都由 taskId 找回它。 */
|
||||
export function bindResourceCanvasGenerationPlaceholderTask(
|
||||
placeholder: ResourceCanvasGenerationPlaceholder,
|
||||
taskId: string,
|
||||
): ResourceCanvasGenerationPlaceholder {
|
||||
return { ...placeholder, taskId, status: 'submitted', error: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务失败:占位留在画布上等重试,状态与原因跟着后端记录走。
|
||||
*
|
||||
* 失败**不**删占位:删掉就等于把用户这次输入与位置一起丢了,而重试恰恰要用同一份输入。
|
||||
*/
|
||||
export function failResourceCanvasGenerationPlaceholder(
|
||||
placeholder: ResourceCanvasGenerationPlaceholder,
|
||||
error: string | null,
|
||||
): ResourceCanvasGenerationPlaceholder {
|
||||
return { ...placeholder, status: 'failed', error };
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除占位。
|
||||
*
|
||||
* 只把这一条从宿主临时状态里去掉,**不**取消后台任务、也不丢弃正式结果:已提交的任务继续在账本里
|
||||
* 跑完并把结果登记进项目(见里程碑「删除占位只隐藏展示」)。
|
||||
*/
|
||||
export function removeResourceCanvasGenerationPlaceholder(
|
||||
placeholders: readonly ResourceCanvasGenerationPlaceholder[],
|
||||
draftId: string,
|
||||
): ResourceCanvasGenerationPlaceholder[] {
|
||||
return placeholders.filter((placeholder) => placeholder.draftId !== draftId);
|
||||
}
|
||||
|
||||
/** 切项目:只留当前项目的占位(未提交草稿与界面位置都不跨项目)。 */
|
||||
export function resourceCanvasGenerationPlaceholdersForProject(
|
||||
placeholders: readonly ResourceCanvasGenerationPlaceholder[],
|
||||
projectId: string,
|
||||
): ResourceCanvasGenerationPlaceholder[] {
|
||||
return placeholders.filter((placeholder) => placeholder.projectId === projectId);
|
||||
}
|
||||
|
||||
/** 按任务找回占位:成功落点与失败收口都以 taskId 为准,不按素材名猜。 */
|
||||
export function resourceCanvasGenerationPlaceholderByTaskId(
|
||||
placeholders: readonly ResourceCanvasGenerationPlaceholder[],
|
||||
taskId: string,
|
||||
): ResourceCanvasGenerationPlaceholder | null {
|
||||
return placeholders.find((placeholder) => placeholder.taskId === taskId) ?? null;
|
||||
}
|
||||
|
||||
export function resourceCanvasGenerationPlaceholderByDraftId(
|
||||
placeholders: readonly ResourceCanvasGenerationPlaceholder[],
|
||||
draftId: string,
|
||||
): ResourceCanvasGenerationPlaceholder | null {
|
||||
return placeholders.find((placeholder) => placeholder.draftId === draftId) ?? null;
|
||||
}
|
||||
|
||||
export const RESOURCE_CANVAS_GENERATION_PLACEHOLDER_STATUS_LABELS: Record<
|
||||
ResourceCanvasGenerationPlaceholderStatus,
|
||||
string
|
||||
> = {
|
||||
draft: '待提交',
|
||||
submitted: '生成中',
|
||||
failed: '生成失败',
|
||||
};
|
||||
|
||||
/**
|
||||
* 占位卡的浮层锚点层:与快速编辑 / 信息浮层共用同一条几何口径(贴着卡片下沿居中)。
|
||||
*
|
||||
* 占位不是正式资源,没有 manifest 身份,所以这里只造一个仅供锚点算法使用的壳,
|
||||
* 不把它塞进资源投影或布局模型。
|
||||
*/
|
||||
export function resourceCanvasGenerationPlaceholderLayer(
|
||||
placeholder: ResourceCanvasGenerationPlaceholder,
|
||||
): CanvasLayer {
|
||||
return {
|
||||
id: placeholder.draftId,
|
||||
resourceId: placeholder.draftId,
|
||||
title: placeholder.assetName,
|
||||
src: '',
|
||||
x: placeholder.x,
|
||||
y: placeholder.y,
|
||||
width: placeholder.width,
|
||||
height: placeholder.height,
|
||||
originalWidth: placeholder.width,
|
||||
originalHeight: placeholder.height,
|
||||
zIndex: 0,
|
||||
sourceType: 'uploaded',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 锚点探针:`resolveQuickEditPanelStyle` 只读 `panel` 判空,浮层自己不需要持有一份快速编辑
|
||||
* 专属状态(与信息浮层同一条做法)。
|
||||
*/
|
||||
const RESOURCE_GENERATION_PANEL_ANCHOR_PROBE = {
|
||||
sourceLayerId: '',
|
||||
prompt: '',
|
||||
size: '',
|
||||
model: '',
|
||||
status: 'idle',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* 生成浮层的落点:贴着占位卡下沿居中,与快速编辑 / 信息浮层同一套几何。
|
||||
*
|
||||
* 占位是可拖动的,所以浮层必须跟着卡走:这里每次都按占位当前坐标重算,浮层不会留在原地。
|
||||
*/
|
||||
export function resolveResourceCanvasGenerationPanelStyle({
|
||||
placeholder,
|
||||
viewport,
|
||||
canvasSize,
|
||||
}: {
|
||||
placeholder: ResourceCanvasGenerationPlaceholder;
|
||||
viewport: CanvasViewport;
|
||||
canvasSize: { width: number; height: number };
|
||||
}): CanvasOverlayStyle | null {
|
||||
return resolveQuickEditPanelStyle({
|
||||
panel: { ...RESOURCE_GENERATION_PANEL_ANCHOR_PROBE },
|
||||
sourceLayer: resourceCanvasGenerationPlaceholderLayer(placeholder),
|
||||
viewport,
|
||||
canvasSize,
|
||||
});
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
import type { CanvasViewport } from '../../../../../packages/image-canvas-core/src/types';
|
||||
import { normalizeResourceBookViewport } from '../../view/project-development/resourceBookViewport';
|
||||
|
||||
/**
|
||||
* 生成浮层/占位的可见性:把「占位卡 + 它下沿的浮层」整块带进画布安全区。
|
||||
*
|
||||
* 只做**最小平移**、不改缩放:用户的缩放预期不能被一次工具点击改掉。与既有
|
||||
* `ensureResourceBookContentVisible` / `centerResourceCanvasOnResource` 同一条口径,
|
||||
* 区别只在于这里要求内容**完整**落在安全区里、并且知道顶栏与底栏要留出来多少。
|
||||
*
|
||||
* 安全区 = 画布减去顶栏(栏目标题栏)与底栏(底部工具栏)后的区域:占位本来就可能被排到
|
||||
* 内容下方(真实浏览器 1280x720 上曾出现占位 y≈550、整块浮层落在可视区之外,用户只看到底栏)。
|
||||
*/
|
||||
export type ResourceCanvasGenerationSafeInsets = {
|
||||
top: number;
|
||||
bottom: number;
|
||||
left?: number;
|
||||
right?: number;
|
||||
};
|
||||
|
||||
export function revealResourceCanvasGenerationContent({
|
||||
viewport,
|
||||
content,
|
||||
canvasSize,
|
||||
insets,
|
||||
padding = 12,
|
||||
}: {
|
||||
viewport: CanvasViewport;
|
||||
/** 需要完整可见的内容矩形(画布坐标):占位卡 + 浮层高度 + 两者之间的间隙。 */
|
||||
content: { x: number; y: number; width: number; height: number };
|
||||
canvasSize: { width: number; height: number };
|
||||
insets: ResourceCanvasGenerationSafeInsets;
|
||||
/** 安全区左右默认留白(顶/底由 insets 覆盖)。 */
|
||||
padding?: number;
|
||||
}): CanvasViewport {
|
||||
const current = normalizeResourceBookViewport(viewport);
|
||||
const finite =
|
||||
Number.isFinite(content.x) &&
|
||||
Number.isFinite(content.y) &&
|
||||
Number.isFinite(content.width) &&
|
||||
Number.isFinite(content.height) &&
|
||||
Number.isFinite(canvasSize.width) &&
|
||||
Number.isFinite(canvasSize.height) &&
|
||||
canvasSize.width > 0 &&
|
||||
canvasSize.height > 0;
|
||||
if (!finite || content.width <= 0 || content.height <= 0) {
|
||||
return current;
|
||||
}
|
||||
const safeLeft = Math.max(0, insets.left ?? padding);
|
||||
const safeTop = Math.max(0, insets.top);
|
||||
const safeRight = Math.max(
|
||||
safeLeft + 1,
|
||||
canvasSize.width - Math.max(0, insets.right ?? padding),
|
||||
);
|
||||
const safeBottom = Math.max(
|
||||
safeTop + 1,
|
||||
canvasSize.height - Math.max(0, insets.bottom),
|
||||
);
|
||||
const screenLeft = current.x + content.x * current.scale;
|
||||
const screenTop = current.y + content.y * current.scale;
|
||||
const screenWidth = Math.max(1, content.width * current.scale);
|
||||
const screenHeight = Math.max(1, content.height * current.scale);
|
||||
const screenRight = screenLeft + screenWidth;
|
||||
const screenBottom = screenTop + screenHeight;
|
||||
|
||||
// 水平:先按左边界对齐,右边越界再整体左推;内容比安全区还宽时以左边界为准。
|
||||
let dx = 0;
|
||||
if (screenRight > safeRight) {
|
||||
dx = safeRight - screenRight;
|
||||
}
|
||||
if (screenLeft + dx < safeLeft) {
|
||||
dx = safeLeft - screenLeft;
|
||||
}
|
||||
// 垂直:同理。占位被排到内容下方时要往上带,浮层顶到顶栏时要往下带。
|
||||
let dy = 0;
|
||||
if (screenBottom > safeBottom) {
|
||||
dy = safeBottom - screenBottom;
|
||||
}
|
||||
if (screenTop + dy < safeTop) {
|
||||
dy = safeTop - screenTop;
|
||||
}
|
||||
if (dx === 0 && dy === 0) {
|
||||
return current;
|
||||
}
|
||||
return {
|
||||
scale: current.scale,
|
||||
x: current.x + dx,
|
||||
y: current.y + dy,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 浮层该占多高、以及它挂在占位卡下面还是直接盖住占位卡。
|
||||
*
|
||||
* 三版都踩过的坑,这里一次钉住:
|
||||
* 1. 用 `window.innerHeight` 当上界 → 面板垂到底栏下面,提交按钮点不到;
|
||||
* 2. 用「当前顶边到安全底边」当上界 → 打开瞬间只剩一百多像素,只见标题与提交行;
|
||||
* 3. 用固定最小高度硬顶 → 底边反过来被顶出画布(`overflow: hidden` 直接切掉)。
|
||||
*
|
||||
* 正确口径:只按**画布安全带**(画布高 − 顶栏 − 底栏)分配。装得下「占位卡 + 间隙 + 浮层」时
|
||||
* 浮层挂在卡下面;装不下时(例如缩放 1.5,卡就占 192px)浮层改为**与卡顶边对齐、盖住占位卡**,
|
||||
* 用整条安全带当编辑高度——占位允许被压到浮层后面,但全局缩放不变、提交按钮永远可见。
|
||||
*/
|
||||
export const RESOURCE_CANVAS_GENERATION_PANEL_MIN_HEIGHT = 280;
|
||||
export const RESOURCE_CANVAS_GENERATION_PANEL_FLOOR_HEIGHT = 160;
|
||||
export const RESOURCE_CANVAS_GENERATION_PANEL_MAX_HEIGHT = 520;
|
||||
|
||||
export type ResourceCanvasGenerationPanelPlacement = {
|
||||
/** 浮层顶边是否与占位卡顶边对齐(盖住占位)而不是挂在卡下面。 */
|
||||
overlaysAnchor: boolean;
|
||||
/** 浮层可用的高度(CSS px)。 */
|
||||
availableHeight: number;
|
||||
};
|
||||
|
||||
export function resolveResourceCanvasGenerationPanelPlacement({
|
||||
canvasHeight,
|
||||
topInset,
|
||||
bottomInset,
|
||||
anchorHeight,
|
||||
gap = 12,
|
||||
minHeight = RESOURCE_CANVAS_GENERATION_PANEL_MIN_HEIGHT,
|
||||
floor = RESOURCE_CANVAS_GENERATION_PANEL_FLOOR_HEIGHT,
|
||||
maxHeight = RESOURCE_CANVAS_GENERATION_PANEL_MAX_HEIGHT,
|
||||
}: {
|
||||
/** 画布可视高(CSS px)——`resourceCanvasElementSize` 量到的画布视口,不是外层容器。 */
|
||||
canvasHeight: number;
|
||||
topInset: number;
|
||||
bottomInset: number;
|
||||
/** 浮层锚点那一块(占位卡)的**屏幕**高度(世界尺寸 × 当前缩放)。 */
|
||||
anchorHeight: number;
|
||||
gap?: number;
|
||||
minHeight?: number;
|
||||
floor?: number;
|
||||
maxHeight?: number;
|
||||
}): ResourceCanvasGenerationPanelPlacement {
|
||||
if (
|
||||
!Number.isFinite(canvasHeight) ||
|
||||
!Number.isFinite(anchorHeight) ||
|
||||
canvasHeight <= 0
|
||||
) {
|
||||
return { overlaysAnchor: false, availableHeight: minHeight };
|
||||
}
|
||||
const bandHeight = Math.max(
|
||||
0,
|
||||
canvasHeight - Math.max(0, topInset) - Math.max(0, bottomInset),
|
||||
);
|
||||
const below = bandHeight - Math.max(0, anchorHeight) - Math.max(0, gap);
|
||||
if (below >= minHeight) {
|
||||
return {
|
||||
overlaysAnchor: false,
|
||||
availableHeight: Math.min(maxHeight, Math.floor(below)),
|
||||
};
|
||||
}
|
||||
// 卡下面塞不下可编辑高度:改用「盖住占位卡」的整条安全带。
|
||||
const overlayBudget = Math.max(0, bandHeight - Math.max(0, gap));
|
||||
return {
|
||||
overlaysAnchor: true,
|
||||
availableHeight:
|
||||
overlayBudget >= floor
|
||||
? Math.min(maxHeight, Math.floor(overlayBudget))
|
||||
: floor,
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user