//! Validated photo selections survive cancelled and invalid file replacements. use super::{el, hidden, input, text}; use base64::{Engine, engine::general_purpose::STANDARD}; use std::{cell::RefCell, rc::Rc}; use wasm_bindgen_futures::{JsFuture, spawn_local}; use web_sys::{File, HtmlImageElement, Url}; pub(super) type Shared = Rc>; #[derive(Default)] pub(super) struct Slot { version: u64, pending: bool, chosen: Option, original: String, deleted: bool, error: String, } struct Chosen { data: String, name: String, url: String, } impl Drop for Chosen { fn drop(&mut self) { let _ = Url::revoke_object_url(&self.url); } } fn file_id(index: usize) -> String { if index < 2 { format!("photo-{}", index + 1) } else { format!("edit-photo-{}", index - 1) } } pub(super) fn render(photos: &Shared, index: usize) { let slots = photos.borrow(); let slot = &slots[index]; let src = if slot.deleted { "" } else { slot.chosen .as_ref() .map(|c| c.url.as_str()) .unwrap_or(&slot.original) }; let preview = el(&format!("slot-preview-{index}")); if src.is_empty() { let _ = preview.remove_attribute("src"); } else { let _ = preview.set_attribute("src", src); } hidden(&format!("slot-preview-{index}"), src.is_empty()); text( &format!("slot-name-{index}"), if slot.deleted { "保存时删除现有照片" } else { slot.chosen .as_ref() .map(|c| c.name.as_str()) .unwrap_or(if slot.original.is_empty() { "点击选择本地图片" } else { "现有照片 · 保留" }) }, ); hidden( &format!("slot-remove-{index}"), slot.chosen.is_none() && !slot.deleted && !slot.pending, ); hidden(&format!("slot-keep-{index}"), slot.error.is_empty()); let status = el(&format!("slot-status-{index}")); let _ = status.set_attribute( "class", if slot.error.is_empty() { "photo-status" } else { "photo-status error" }, ); status.set_text_content(Some(if slot.pending { "正在校验照片…" } else { &slot.error })); let _ = status.set_attribute("aria-busy", if slot.pending { "true" } else { "false" }); if index >= 2 { let check = input(&format!("edit-delete-{}", index - 1)); check.set_checked(slot.deleted); check.set_disabled( slot.original.is_empty() || super::document().body().is_some_and(|b| { b.get_attribute("data-registry-busy").as_deref() == Some("true") }), ); } } pub(super) fn reset(photos: &Shared, index: usize, original: &str) { let version = photos.borrow()[index].version + 1; photos.borrow_mut()[index] = Slot { version, original: original.into(), ..Slot::default() }; input(&file_id(index)).set_value(""); render(photos, index); } pub(super) fn keep(photos: &Shared, index: usize) { photos.borrow_mut()[index].error.clear(); render(photos, index); } pub(super) fn remove(photos: &Shared, index: usize) { let original = photos.borrow()[index].original.clone(); reset(photos, index, &original); } pub(super) fn delete(photos: &Shared, index: usize, deleted: bool) { remove(photos, index); photos.borrow_mut()[index].deleted = deleted; render(photos, index); } pub(super) fn pending(photos: &Shared, editing: bool) -> bool { let offset = if editing { 2 } else { 0 }; photos.borrow()[offset..offset + 2] .iter() .any(|s| s.pending) } pub(super) fn validation_error(photos: &Shared, editing: bool) -> Option { let offset = if editing { 2 } else { 0 }; photos.borrow()[offset..offset + 2] .iter() .find(|slot| !slot.error.is_empty()) .map(|slot| slot.error.clone()) } pub(super) fn apply(photos: &Shared, editing: bool, body: &mut serde_json::Value) { let offset = if editing { 2 } else { 0 }; let slots = photos.borrow(); for (i, slot) in slots[offset..offset + 2].iter().enumerate() { let key = format!("photo{}", i + 1); if editing && slot.deleted { body[key] = serde_json::Value::Null; } else if let Some(chosen) = &slot.chosen { body[key] = serde_json::json!(chosen.data); } } } async fn validate(file: File) -> Result { let mime = file.type_(); if !matches!(mime.as_str(), "image/jpeg" | "image/png" | "image/webp") || file.size() <= 0.0 || file.size() > 5.0 * 1024.0 * 1024.0 { return Err("照片仅支持 5 MB 以内的 JPG、PNG 或 WebP;原选择已保留".into()); } let buffer = JsFuture::from(file.array_buffer()) .await .map_err(|_| "无法读取照片;原选择已保留")?; let bytes = js_sys::Uint8Array::new(&buffer).to_vec(); let signature = match mime.as_str() { "image/jpeg" => bytes.starts_with(&[255, 216, 255]), "image/png" => bytes.starts_with(b"\x89PNG\r\n\x1a\n"), _ => bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP"), }; if !signature { return Err("照片内容与格式不符;原选择已保留".into()); } let url = Url::create_object_url_with_blob(&file).map_err(|_| "无法预览照片")?; let chosen = Chosen { data: format!("data:{mime};base64,{}", STANDARD.encode(bytes)), name: file.name(), url, }; let image = HtmlImageElement::new().map_err(|_| "图片组件不可用")?; image.set_src(&chosen.url); JsFuture::from(image.decode()) .await .map_err(|_| "照片损坏,无法解码;原选择已保留")?; if image.natural_width() == 0 || image.natural_height() == 0 { return Err("照片尺寸无效;原选择已保留".into()); } Ok(chosen) } pub(super) fn choose(photos: Shared, index: usize, file: File) { let version = { let mut slots = photos.borrow_mut(); let slot = &mut slots[index]; slot.version += 1; slot.pending = true; slot.error.clear(); slot.version }; // The File is captured, so clearing the picker also permits choosing the same file again. input(&file_id(index)).set_value(""); render(&photos, index); spawn_local(async move { let result = validate(file).await; { let mut slots = photos.borrow_mut(); let slot = &mut slots[index]; if slot.version != version { return; } slot.pending = false; match result { Ok(chosen) => { slot.chosen = Some(chosen); slot.deleted = false; slot.error.clear(); } Err(error) => slot.error = error, } } render(&photos, index); }); }