对齐旅拍相册详情页 Android UI,并修复网格预览与布局问题。

重构相册详情为信息卡片、Tab 筛选、排序、批量删除与底部上传栏;修复网格重叠、禁用按钮蒙层,并支持点击预览大图。同步扩展素材列表 API 与 ViewModel 分页逻辑,并优化有线传图缩略图与传输性能。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-06-30 13:53:59 +08:00
parent c71b45bdfd
commit 5e620623eb
23 changed files with 2000 additions and 288 deletions

View File

@ -18,7 +18,13 @@ protocol TravelAlbumServing {
func albumInfo(id: Int) async throws -> TravelAlbumItem
func editAlbum(_ request: TravelAlbumEditRequest) async throws
func deleteAlbum(_ request: TravelAlbumDeleteRequest) async throws
func materialList(userEquityTravelId: Int, page: Int, pageSize: Int) async throws -> ListPayload<TravelAlbumMaterial>
func materialList(
userEquityTravelId: Int,
page: Int,
pageSize: Int,
orderBy: Int,
isPurchased: Int?
) async throws -> ListPayload<TravelAlbumMaterial>
func uploadMaterial(_ request: TravelAlbumUploadMaterialRequest) async throws -> TravelAlbumMaterial
func deleteMaterial(_ request: TravelAlbumDeleteMaterialRequest) async throws
func mpCode(id: Int) async throws -> TravelAlbumMpCodeResponse
@ -88,17 +94,27 @@ final class TravelAlbumAPI: TravelAlbumServing {
}
///
func materialList(userEquityTravelId: Int, page: Int, pageSize: Int) async throws -> ListPayload<TravelAlbumMaterial> {
try await client.send(
func materialList(
userEquityTravelId: Int,
page: Int,
pageSize: Int,
orderBy: Int = 2,
isPurchased: Int? = nil
) async throws -> ListPayload<TravelAlbumMaterial> {
var queryItems = [
URLQueryItem(name: "user_equity_travel_id", value: "\(userEquityTravelId)"),
URLQueryItem(name: "page", value: "\(max(page, 1))"),
URLQueryItem(name: "page_size", value: "\(max(pageSize, 1))"),
URLQueryItem(name: "order_by", value: "\(max(orderBy, 1))")
]
if let isPurchased {
queryItems.append(URLQueryItem(name: "is_purchased", value: "\(isPurchased)"))
}
return try await client.send(
APIRequest(
method: .get,
path: "\(travelAlbumBase)/material-list",
queryItems: [
URLQueryItem(name: "user_equity_travel_id", value: "\(userEquityTravelId)"),
URLQueryItem(name: "page", value: "\(max(page, 1))"),
URLQueryItem(name: "page_size", value: "\(max(pageSize, 1))"),
URLQueryItem(name: "order_by", value: "2")
]
queryItems: queryItems
)
)
}

View File

@ -161,6 +161,18 @@ struct TravelAlbumMaterial: Decodable, Identifiable, Equatable {
createdAt = container.lossyString(forKey: .createdAt)
updatedAt = container.lossyString(forKey: .updatedAt)
}
/// URL
var previewURLString: String {
if !fileURL.isEmpty { return fileURL }
return coverURL
}
/// URL
var thumbnailURLString: String {
if !coverURL.isEmpty { return coverURL }
return fileURL
}
}
///
@ -308,7 +320,10 @@ struct WiredTransferPhotoItem: Identifiable, Equatable {
let id: String
let sourceId: String
let fileName: String
/// 使 URL
let thumbnailURL: String
/// 使 URL
let previewURL: String
let capturedAt: String
let fileSizeText: String
let resolutionText: String
@ -321,6 +336,7 @@ struct WiredTransferPhotoItem: Identifiable, Equatable {
sourceId: String? = nil,
fileName: String,
thumbnailURL: String,
previewURL: String = "",
capturedAt: String,
fileSizeText: String,
resolutionText: String = "",
@ -332,6 +348,7 @@ struct WiredTransferPhotoItem: Identifiable, Equatable {
self.sourceId = sourceId ?? id
self.fileName = fileName
self.thumbnailURL = thumbnailURL
self.previewURL = previewURL
self.capturedAt = capturedAt
self.fileSizeText = fileSizeText
self.resolutionText = resolutionText
@ -385,8 +402,15 @@ struct WiredTransferPhotoRecord: Codable, Equatable {
let updatedAt: TimeInterval
func toPhotoItem() -> WiredTransferPhotoItem {
let previewCandidates = [thumbnailPath, localPath, remoteURL]
let thumbnailURL = previewCandidates.compactMap { path -> String? in
let thumbnailCandidates = [thumbnailPath, remoteURL]
let thumbnailURL = thumbnailCandidates.compactMap { path -> String? in
guard !path.isEmpty else { return nil }
if path.hasPrefix("http") { return path }
let preview = CameraDownloadStorage.previewURLString(from: path)
return preview.isEmpty ? nil : preview
}.first ?? ""
let previewCandidates = [localPath, remoteURL, thumbnailPath]
let previewURL = previewCandidates.compactMap { path -> String? in
guard !path.isEmpty else { return nil }
if path.hasPrefix("http") { return path }
let preview = CameraDownloadStorage.previewURLString(from: path)
@ -398,6 +422,7 @@ struct WiredTransferPhotoRecord: Codable, Equatable {
sourceId: sourceId,
fileName: fileName,
thumbnailURL: thumbnailURL,
previewURL: previewURL,
capturedAt: capturedAt,
fileSizeText: Self.formatFileSize(fileSizeBytes),
status: WiredTransferUploadStatus(rawValue: status) ?? .pending,
@ -465,6 +490,16 @@ extension Array where Element == WiredTransferPhotoItem {
Set(filter { $0.canSelectForSpecifyUpload }.map(\.id))
}
///
func sortedByCaptureTimeDescending() -> [WiredTransferPhotoItem] {
sorted { lhs, rhs in
let leftDate = lhs.capturedDate() ?? .distantPast
let rightDate = rhs.capturedDate() ?? .distantPast
if leftDate != rightDate { return leftDate > rightDate }
return lhs.id > rhs.id
}
}
/// 30
func buildPhotoSections() -> [WiredTransferPhotoSection] {
let grouped = Dictionary(grouping: compactMap { photo -> (Date, WiredTransferPhotoItem)? in

View File

@ -122,6 +122,9 @@ final class WiredTransferPhotoStore {
guard let data = defaults.data(forKey: storageKey(albumID)),
var records = try? JSONDecoder().decode([WiredTransferPhotoRecord].self, from: data)
else { return }
records
.filter { $0.id == photoID && $0.userId == userIDProvider() && $0.albumId == albumID }
.forEach { deleteRecordFiles($0) }
records = records.filter { record in
!deletedIDs.contains(record.id)
&& record.userId == userIDProvider()

View File

@ -15,9 +15,29 @@
| --- | --- |
| `TravelAlbumEntryView` | 新增相册列表、新建任务入口;卡片主区域点击进入详情,底部保留「拍传」「相册码」 |
| `CreateTravelAlbumSheet` | 先拍再买 / 买了再拍创建弹窗 |
| `TravelAlbumDetailView` | 相册详情与素材管理 |
| `TravelAlbumDetailView` | 相册详情与素材管理UI 对齐 Android |
| `WiredCameraTransferView` | 有线传图页UI 对齐 Android |
## 相册详情 UI 结构
Android 对照:`zhiflyfollow/.../TravelAlbumDetailScreen.kt`
```
TravelAlbumDetailInfoCard # 信息卡片:手机号 + 创建时间 + 拨号
TravelAlbumDetailPhotoManageCard # 白卡片Tab / 排序 / 批量选择 + 网格
TravelAlbumDetailMaterialGridItem# 缩略图 + 已上传角标 + 文件名 + 大小
BottomBar # 上传照片 + 条件删除选中
```
## 相册详情交互流程
1. **Tab**:全部照片 / 已购照片,切换后重载素材列表
2. **排序**:创建时间正序/倒序、文件名正序/倒序
3. **批量删除**仅在「全部照片」Tab 可选,且仅未购买素材可删
4. **上传照片**:底部按钮进入 `WiredCameraTransferView`,返回后自动刷新
5. **删除相册**:右上角更多菜单
6. **图片预览**:非选择模式下点击网格项打开大图预览,可左右滑动浏览当前列表
## 有线传图 UI 结构
Android 对照:`zhiflyfollow/.../WiredCameraTransferScreen.kt`
@ -50,6 +70,13 @@ SpecifyUploadBottomSheet # 指定上传选项弹层
4. 素材登记:`POST .../travel-album/upload-material`
5. 本地照片路径以相对 Documents 的路径持久化(如 `CameraDownloads/xxx.JPG`),加载时自动迁移旧版绝对路径
## 有线传图性能策略
- 本地下载原图只用于上传与大图预览;列表缩略图在后台下采样生成到 `CameraDownloads/Thumbnails/`,由 Kingfisher 统一加载与缓存。
- 连拍上传进度采用节流通知,下载/上传关键状态立即刷新,普通进度合并后再更新 UI边拍边传自动队列最多 3 张照片并发上传,避免滚动时高频触发整页重绘或网络资源被打满。
- `WiredCameraTransferViewModel` 缓存当前 Tab、时间侧栏和 30 分钟分组;新增/删除/切换 Tab 才重建分组,单张进度变化只替换对应行数据。
- 本地记录以相册和用户维度持久化,状态终态、路径变化立即保存,普通进度按步长或时间间隔降频保存。
## 解耦关系
- `CameraTransferPipeline` 只依赖 `CameraAssetUploadSink` 协议

View File

@ -177,38 +177,145 @@ struct TravelAlbumCodeSheetState: Identifiable {
var id: Int { albumID }
}
/// ViewModel
/// ViewModel Android TravelAlbumDetailViewModel
@MainActor
final class TravelAlbumDetailViewModel: ObservableObject {
static let tabAll = 0
static let tabPurchased = 1
static let materialStatusUnpurchased = 1
static let sortOptions: [(value: Int, label: String)] = [
(1, "创建时间正序"),
(2, "创建时间倒序"),
(3, "文件名正序"),
(4, "文件名倒序")
]
@Published var album: TravelAlbumItem?
@Published var materials: [TravelAlbumMaterial] = []
@Published var allPhotoCount = 0
@Published var selectedTab = tabAll
@Published var orderBy = 2
@Published var isSelectionMode = false
@Published var selectedMaterialIDs: Set<Int> = []
@Published var isLoading = false
@Published var isDeleting = false
@Published var showDeleteAlbumConfirm = false
@Published var showDeleteMaterialConfirm = false
@Published var errorMessage: String?
///
private var albumID = 0
private var currentPage = 1
private var canLoadMore = false
private var isLoadingMore = false
private static let pageSize = 30
private static let loadMoreThreshold = 6
private static let purchasedFilterYes = 1
///
func refreshAll(api: any TravelAlbumServing, albumID: Int) async {
self.albumID = albumID
async let infoTask: Void = loadAlbumInfo(api: api, albumID: albumID, showPageLoading: album == nil)
async let countTask: Void = loadAllPhotoCount(api: api, albumID: albumID)
async let materialsTask: Void = loadMaterials(api: api, albumID: albumID, reset: true)
_ = await (infoTask, countTask, materialsTask)
}
///
func load(api: any TravelAlbumServing, albumID: Int) async {
isLoading = true
defer { isLoading = false }
do {
async let info = api.albumInfo(id: albumID)
async let list = api.materialList(userEquityTravelId: albumID, page: 1, pageSize: 100)
album = try await info
materials = try await list.list
errorMessage = nil
} catch {
errorMessage = error.localizedDescription
await refreshAll(api: api, albumID: albumID)
}
/// Tab
func selectTab(_ tab: Int, api: any TravelAlbumServing) async {
guard selectedTab != tab else { return }
selectedTab = tab
isSelectionMode = false
selectedMaterialIDs = []
await loadMaterials(api: api, albumID: albumID, reset: true)
}
///
func setOrderBy(_ value: Int, api: any TravelAlbumServing) async {
guard orderBy != value else { return }
orderBy = value
await loadMaterials(api: api, albumID: albumID, reset: true)
}
/// Tab
func toggleSelectionMode() {
guard selectedTab == Self.tabAll else { return }
isSelectionMode.toggle()
if !isSelectionMode {
selectedMaterialIDs = []
}
}
///
func deleteMaterial(api: any TravelAlbumServing, materialID: Int, albumID: Int) async {
do {
try await api.deleteMaterial(TravelAlbumDeleteMaterialRequest(id: materialID))
await load(api: api, albumID: albumID)
} catch {
errorMessage = error.localizedDescription
///
func toggleMaterialSelection(_ material: TravelAlbumMaterial) {
guard isSelectionMode else { return }
guard material.status == Self.materialStatusUnpurchased else {
errorMessage = "仅未购买素材可删除"
return
}
if selectedMaterialIDs.contains(material.id) {
selectedMaterialIDs.remove(material.id)
} else {
selectedMaterialIDs.insert(material.id)
}
}
///
func loadMoreIfNeeded(lastVisibleIndex: Int, api: any TravelAlbumServing) async {
guard lastVisibleIndex >= materials.count - Self.loadMoreThreshold else { return }
await loadMaterials(api: api, albumID: albumID, reset: false)
}
///
func requestDeleteSelectedMaterials() {
guard !selectedMaterialIDs.isEmpty else {
errorMessage = "请选择要删除的素材"
return
}
showDeleteMaterialConfirm = true
}
///
@discardableResult
func confirmDeleteSelectedMaterials(api: any TravelAlbumServing) async -> Bool {
let ids = Array(selectedMaterialIDs)
guard !ids.isEmpty else {
showDeleteMaterialConfirm = false
return false
}
showDeleteMaterialConfirm = false
isDeleting = true
defer { isDeleting = false }
for id in ids {
do {
try await api.deleteMaterial(TravelAlbumDeleteMaterialRequest(id: id))
} catch {
errorMessage = error.localizedDescription
return false
}
}
isSelectionMode = false
selectedMaterialIDs = []
await refreshAll(api: api, albumID: albumID)
return true
}
/// 线
func wiredTransferContext() -> WiredTransferContext? {
guard let album else { return nil }
return WiredTransferContext(
albumId: album.id,
albumName: album.name,
phone: album.displayPhone,
orderNumber: album.orderNumber
)
}
///
@ -224,6 +331,80 @@ final class TravelAlbumDetailViewModel: ObservableObject {
return false
}
}
private func loadAlbumInfo(api: any TravelAlbumServing, albumID: Int, showPageLoading: Bool) async {
if showPageLoading {
isLoading = true
}
defer {
if showPageLoading {
isLoading = false
}
}
do {
album = try await api.albumInfo(id: albumID)
errorMessage = nil
} catch {
errorMessage = error.localizedDescription
}
}
private func loadAllPhotoCount(api: any TravelAlbumServing, albumID: Int) async {
do {
let payload = try await api.materialList(
userEquityTravelId: albumID,
page: 1,
pageSize: 1,
orderBy: orderBy,
isPurchased: nil
)
allPhotoCount = payload.total
} catch {
errorMessage = error.localizedDescription
}
}
private func loadMaterials(api: any TravelAlbumServing, albumID: Int, reset: Bool) async {
if reset {
currentPage = 1
canLoadMore = false
} else {
guard canLoadMore, !isLoadingMore else { return }
isLoadingMore = true
currentPage += 1
}
let isPurchasedFilter: Int? = selectedTab == Self.tabPurchased ? Self.purchasedFilterYes : nil
do {
let payload = try await api.materialList(
userEquityTravelId: albumID,
page: currentPage,
pageSize: Self.pageSize,
orderBy: orderBy,
isPurchased: isPurchasedFilter
)
if reset {
materials = payload.list
} else {
materials.append(contentsOf: payload.list)
}
canLoadMore = materials.count < payload.total
if selectedTab == Self.tabAll {
allPhotoCount = payload.total
}
errorMessage = nil
} catch {
if !reset, currentPage > 1 {
currentPage -= 1
}
errorMessage = error.localizedDescription
}
if !reset {
isLoadingMore = false
}
}
}
/// 线 ViewModel
@ -237,7 +418,11 @@ final class WiredCameraTransferViewModel: ObservableObject {
static let specifyUploadTodayCaptured = "上传所有今日拍摄的照片"
static let helpDocURL = URL(string: "https://sharesky.feishu.cn/wiki/CaAhwl3Gnin4Kqk0BVocK3SGnab?from=from_copylink")!
@Published var photos: [WiredTransferPhotoItem] = []
@Published private(set) var photos: [WiredTransferPhotoItem] = []
@Published private(set) var visiblePhotos: [WiredTransferPhotoItem] = []
@Published private(set) var sidebarGroups: [WiredTransferDateGroup] = []
@Published private(set) var photoSections: [WiredTransferPhotoSection] = []
@Published private(set) var tabCounts: [Int] = [0, 0, 0]
@Published var selectedTabIndex = 0
@Published var sidebarExpanded = true
@Published var selectedTimeSlotID: String?
@ -258,6 +443,8 @@ final class WiredCameraTransferViewModel: ObservableObject {
private var photoStore: WiredTransferPhotoStore?
private var userIDProvider: (() -> String)?
private var sessionNewPhotoIDs: Set<String> = []
private var persistedRecordsByID: [String: WiredTransferPhotoRecord] = [:]
private var lastProgressPersistDates: [String: Date] = [:]
private var wasConnected = false
private var disconnectAlertTask: Task<Void, Never>?
@ -276,7 +463,7 @@ final class WiredCameraTransferViewModel: ObservableObject {
}
pipeline.onTasksUpdated = { [weak self] tasks in
Task { @MainActor in
self?.applyPipelineTasks(tasks)
await self?.applyPipelineTasks(tasks)
}
}
}
@ -325,6 +512,7 @@ final class WiredCameraTransferViewModel: ObservableObject {
func selectTab(_ index: Int) {
selectedTabIndex = index
selectedTimeSlotID = nil
refreshDerivedPhotoState(rebuildGroups: true)
if selectUploadMode {
syncSelectionWithVisiblePhotos()
}
@ -432,16 +620,11 @@ final class WiredCameraTransferViewModel: ObservableObject {
}
}
/// Tab
var visiblePhotos: [WiredTransferPhotoItem] {
photos.filtered(byTabIndex: selectedTabIndex)
}
/// URL
func previewURL(for photoID: String) -> String {
guard let photo = photos.first(where: { $0.id == photoID }) else { return "" }
if !photo.thumbnailURL.isEmpty { return photo.thumbnailURL }
return ""
if !photo.previewURL.isEmpty { return photo.previewURL }
return photo.thumbnailURL
}
///
@ -474,14 +657,48 @@ final class WiredCameraTransferViewModel: ObservableObject {
}
///
func retryPhoto(id: String) async {
await pipeline.uploadAssets(withIDs: [id])
func retryPhoto(
id: String,
api: any TravelAlbumServing,
ossService: any OSSUploadServing,
scenicID: Int
) async {
guard let photo = photos.first(where: { $0.id == id }) else { return }
guard photo.status == .failed || photo.status == .pending else {
errorMessage = "当前状态不可重传"
return
}
ensureUploadEnabled(api: api, ossService: ossService, scenicID: scenicID)
updatePhotoStatus(id: id, status: .uploading, progress: 0, errorMessage: nil)
if pipeline.task(forAssetID: id) != nil {
await pipeline.uploadAssets(withIDs: [id])
return
}
guard let record = persistedRecord(for: id),
let localURL = CameraDownloadStorage.resolveLocalURL(from: record.localPath),
FileManager.default.fileExists(atPath: localURL.path) else {
updatePhotoStatus(id: id, status: .failed, progress: 0, errorMessage: "本地文件不存在")
errorMessage = "本地文件不存在,无法重传"
persistPhotoStatus(id: id, status: .failed, progress: 0, errorMessage: "本地文件不存在")
return
}
await pipeline.retryUpload(
assetID: id,
filename: record.fileName,
localPath: record.localPath
)
}
///
func deletePhoto(id: String) {
photoStore?.remove(albumID: context.albumId, photoID: id)
photos.removeAll { $0.id == id }
persistedRecordsByID.removeValue(forKey: id)
lastProgressPersistDates.removeValue(forKey: id)
setPhotos(photos.filter { $0.id != id }, rebuildGroups: true)
}
///
@ -515,11 +732,117 @@ final class WiredCameraTransferViewModel: ObservableObject {
pipeline.configure(uploadSink: uploader, uploadEnabled: true)
}
private func persistedRecord(for photoID: String) -> WiredTransferPhotoRecord? {
persistedRecordsByID[photoID]
}
private func updatePhotoStatus(
id: String,
status: WiredTransferUploadStatus,
progress: Int,
errorMessage: String?
) {
guard let index = photos.firstIndex(where: { $0.id == id }) else { return }
let photo = photos[index]
let updated = WiredTransferPhotoItem(
id: photo.id,
sourceId: photo.sourceId,
fileName: photo.fileName,
thumbnailURL: photo.thumbnailURL,
previewURL: photo.previewURL,
capturedAt: photo.capturedAt,
fileSizeText: photo.fileSizeText,
resolutionText: photo.resolutionText,
status: status,
progress: progress,
errorMessage: errorMessage
)
replacePhoto(updated, rebuildGroups: photo.status != status)
}
private func persistPhotoStatus(
id: String,
status: WiredTransferUploadStatus,
progress: Int,
errorMessage: String?
) {
guard context.albumId > 0,
let userID = userIDProvider?(), !userID.isEmpty else { return }
guard let existing = persistedRecordsByID[id] else { return }
let updated = WiredTransferPhotoRecord(
id: existing.id,
sourceId: existing.sourceId,
fileName: existing.fileName,
localPath: existing.localPath,
thumbnailPath: existing.thumbnailPath,
capturedAt: existing.capturedAt,
fileSizeBytes: existing.fileSizeBytes,
status: status.rawValue,
progress: progress,
errorMessage: errorMessage,
albumId: existing.albumId,
userId: existing.userId,
remoteURL: existing.remoteURL,
updatedAt: Date().timeIntervalSince1970
)
persistRecord(updated)
}
private func syncSelectionWithVisiblePhotos() {
let visibleIDs = Set(visiblePhotos.map(\.id))
selectedPhotoIDs = selectedPhotoIDs.intersection(visibleIDs)
}
/// UI
func replacePhotos(_ newPhotos: [WiredTransferPhotoItem]) {
setPhotos(newPhotos.sortedByCaptureTimeDescending(), rebuildGroups: true)
}
private func setPhotos(_ newPhotos: [WiredTransferPhotoItem], rebuildGroups: Bool) {
photos = newPhotos
refreshDerivedPhotoState(rebuildGroups: rebuildGroups)
}
private func replacePhoto(_ photo: WiredTransferPhotoItem, rebuildGroups: Bool) {
var updatedPhotos = photos
if let index = updatedPhotos.firstIndex(where: { $0.id == photo.id }) {
updatedPhotos[index] = photo
} else {
updatedPhotos.insert(photo, at: 0)
}
if rebuildGroups {
updatedPhotos = updatedPhotos.sortedByCaptureTimeDescending()
}
setPhotos(updatedPhotos, rebuildGroups: rebuildGroups)
}
private func refreshDerivedPhotoState(rebuildGroups: Bool) {
tabCounts = photos.transferTabCounts
let filtered = photos.filtered(byTabIndex: selectedTabIndex)
visiblePhotos = filtered
if rebuildGroups {
sidebarGroups = filtered.buildSidebarGroups()
photoSections = filtered.buildPhotoSections()
return
}
let latestByID = Dictionary(uniqueKeysWithValues: filtered.map { ($0.id, $0) })
photoSections = photoSections.map { section in
WiredTransferPhotoSection(
slotId: section.slotId,
headerTitle: section.headerTitle,
photos: section.photos.compactMap { latestByID[$0.id] }
)
}.filter { !$0.photos.isEmpty }
}
private func persistRecord(_ record: WiredTransferPhotoRecord) {
guard let photoStore, context.albumId > 0 else { return }
persistedRecordsByID[record.id] = record
photoStore.save(albumID: context.albumId, records: Array(persistedRecordsByID.values))
}
private func handleConnectionStateChange(_ state: CameraConnectionState) {
if wasConnected, !state.isConnected {
triggerCameraDisconnectedAlert()
@ -553,73 +876,182 @@ final class WiredCameraTransferViewModel: ObservableObject {
private func loadPersistedPhotos() {
guard context.albumId > 0, let photoStore else { return }
let records = photoStore.load(albumID: context.albumId)
photos = records.map { $0.toPhotoItem() }
persistedRecordsByID = Dictionary(uniqueKeysWithValues: records.map { ($0.id, $0) })
setPhotos(records.map { $0.toPhotoItem() }.sortedByCaptureTimeDescending(), rebuildGroups: true)
}
private func applyPipelineTasks(_ tasks: [CameraTransferTask]) {
guard let photoStore, let userIDProvider else { return }
private func applyPipelineTasks(_ tasks: [CameraTransferTask]) async {
guard let userIDProvider else { return }
let userID = userIDProvider()
var merged = photos.filter { photo in
!tasks.contains { $0.assetID == photo.id || $0.filename == photo.fileName }
}
// capturedAt
let existingByID = Dictionary(uniqueKeysWithValues: photos.map { ($0.id, $0) })
let existingByFileName = Dictionary(
photos.map { ($0.fileName, $0) },
uniquingKeysWith: { first, _ in first }
)
for task in tasks {
guard belongsToCurrentAlbum(task.assetID) else { continue }
let status: WiredTransferUploadStatus
switch task.status {
case .pending, .downloading:
status = .transferring
case .downloaded:
status = .pending
case .uploading:
status = .uploading
case .uploaded:
status = .uploaded
case .failed:
status = .failed
}
let capturedAt = Self.captureTimestampFormatter.string(from: Date())
let status = mapPipelineStatus(task.status)
let storedLocalPath = task.localPath ?? ""
let localURL = task.localURL
let fileSizeBytes: Int64
if let localURL {
fileSizeBytes = (try? FileManager.default.attributesOfItem(atPath: localURL.path)[.size] as? Int64) ?? 0
} else {
fileSizeBytes = 0
let fileSizeBytes = await CameraDownloadStorage.fileSizeBytes(for: localURL)
let existing = existingByID[task.assetID] ?? existingByFileName[task.filename]
let existingRecord = persistedRecordsByID[task.assetID]
let capturedAt = await resolveCapturedAt(
existing: existing,
taskCapturedAt: task.capturedAt,
localURL: localURL
)
var thumbnailPath = existingRecord?.thumbnailPath ?? ""
if thumbnailPath.isEmpty,
let localURL,
status != .transferring,
let generatedPath = await CameraThumbnailGenerator.generateThumbnail(for: localURL, assetID: task.assetID) {
thumbnailPath = generatedPath
}
let thumbnailURL = localURL.map(\.absoluteString) ?? ""
let thumbnailURL = thumbnailURLString(thumbnailPath: thumbnailPath, remoteURL: task.remoteURL ?? existingRecord?.remoteURL ?? "")
let previewURL = previewURLString(localPath: storedLocalPath, remoteURL: task.remoteURL ?? existingRecord?.remoteURL ?? "", thumbnailPath: thumbnailPath)
let fileSizeText = fileSizeBytes > 0
? WiredTransferPhotoRecord.formatFileSize(fileSizeBytes)
: (existing?.fileSizeText ?? "--")
let item = WiredTransferPhotoItem(
id: task.assetID,
sourceId: existing?.sourceId ?? task.assetID,
fileName: task.filename,
thumbnailURL: thumbnailURL,
previewURL: previewURL,
capturedAt: capturedAt,
fileSizeText: WiredTransferPhotoRecord.formatFileSize(fileSizeBytes),
fileSizeText: fileSizeText,
resolutionText: existing?.resolutionText ?? "",
status: status,
progress: task.progress,
errorMessage: task.errorMessage
)
merged.insert(item, at: 0)
let rebuildGroups = existing == nil
|| existing?.capturedAt != item.capturedAt
|| (selectedTabIndex != 0 && existing?.status != item.status)
replacePhoto(item, rebuildGroups: rebuildGroups)
sessionNewPhotoIDs.insert(task.assetID)
guard !userID.isEmpty else { continue }
let record = item.toRecord(
albumId: context.albumId,
userId: userID,
let remoteURL = task.remoteURL ?? ""
if shouldPersistPipelineUpdate(
photoID: task.assetID,
status: status,
localPath: storedLocalPath,
fileSizeBytes: fileSizeBytes,
remoteURL: task.remoteURL ?? ""
)
var records = photoStore.load(albumID: context.albumId)
records.removeAll { $0.id == record.id }
records.insert(record, at: 0)
photoStore.save(albumID: context.albumId, records: records)
thumbnailPath: thumbnailPath,
remoteURL: remoteURL,
progress: task.progress,
now: Date()
) {
let record = item.toRecord(
albumId: context.albumId,
userId: userID,
localPath: storedLocalPath,
thumbnailPath: thumbnailPath,
fileSizeBytes: fileSizeBytes,
remoteURL: remoteURL
)
persistRecord(record)
}
}
}
photos = merged.sorted { $0.capturedAt > $1.capturedAt }
/// 使退
private func thumbnailURLString(thumbnailPath: String, remoteURL: String) -> String {
if !thumbnailPath.isEmpty {
let localThumbnailURL = CameraDownloadStorage.previewURLString(from: thumbnailPath)
if !localThumbnailURL.isEmpty { return localThumbnailURL }
}
return remoteURL
}
private func previewURLString(localPath: String, remoteURL: String, thumbnailPath: String) -> String {
if !localPath.isEmpty {
let localPreviewURL = CameraDownloadStorage.previewURLString(from: localPath)
if !localPreviewURL.isEmpty { return localPreviewURL }
}
if !remoteURL.isEmpty { return remoteURL }
if !thumbnailPath.isEmpty {
return CameraDownloadStorage.previewURLString(from: thumbnailPath)
}
return ""
}
private func resolveCapturedAt(
existing: WiredTransferPhotoItem?,
taskCapturedAt: String?,
localURL: URL?
) async -> String {
if let existing, !existing.capturedAt.isEmpty {
return existing.capturedAt
}
if let taskCapturedAt, !taskCapturedAt.isEmpty {
return taskCapturedAt
}
if let localURL {
let date = await Task.detached(priority: .utility) {
let attributes = try? FileManager.default.attributesOfItem(atPath: localURL.path)
return (attributes?[.creationDate] as? Date)
?? (attributes?[.modificationDate] as? Date)
}.value
if let date {
return CameraTransferTask.capturedAtString(from: date)
}
}
return CameraTransferTask.capturedAtString(from: Date())
}
///
private func mapPipelineStatus(_ status: CameraTransferStatus) -> WiredTransferUploadStatus {
switch status {
case .pending, .downloading:
return .transferring
case .downloaded:
return .pending
case .uploading:
return .uploading
case .uploaded:
return .uploaded
case .failed:
return .failed
}
}
/// URL IO
private func shouldPersistPipelineUpdate(
photoID: String,
status: WiredTransferUploadStatus,
localPath: String,
thumbnailPath: String,
remoteURL: String,
progress: Int,
now: Date
) -> Bool {
guard let existing = persistedRecordsByID[photoID] else {
lastProgressPersistDates[photoID] = now
return true
}
if existing.status != status.rawValue { return true }
if !localPath.isEmpty, existing.localPath != localPath { return true }
if !thumbnailPath.isEmpty, existing.thumbnailPath != thumbnailPath { return true }
if !remoteURL.isEmpty, existing.remoteURL != remoteURL { return true }
if status == .uploaded || status == .failed { return true }
if abs(progress - existing.progress) >= 10 {
lastProgressPersistDates[photoID] = now
return true
}
let lastPersistDate = lastProgressPersistDates[photoID] ?? .distantPast
if now.timeIntervalSince(lastPersistDate) >= 1 {
lastProgressPersistDates[photoID] = now
return true
}
return false
}
///
@ -629,10 +1061,4 @@ final class WiredCameraTransferViewModel: ObservableObject {
}
return bound == context.albumId
}
private static let captureTimestampFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
}

View File

@ -0,0 +1,34 @@
//
// MiddleTruncatedText.swift
// suixinkan
//
// Android MiddleEllipsisTextView
//
import SwiftUI
import UIKit
///
struct MiddleTruncatedText: UIViewRepresentable {
let text: String
var font: UIFont = .systemFont(ofSize: 11, weight: .regular)
var textColor: UIColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
/// UILabel
func makeUIView(context: Context) -> UILabel {
let label = UILabel()
label.lineBreakMode = .byTruncatingMiddle
label.numberOfLines = 1
label.setContentHuggingPriority(.required, for: .vertical)
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
label.setContentCompressionResistancePriority(.required, for: .vertical)
return label
}
///
func updateUIView(_ uiView: UILabel, context: Context) {
uiView.text = text
uiView.font = font
uiView.textColor = textColor
}
}

View File

@ -0,0 +1,41 @@
//
// TravelAlbumDetailDesign.swift
// suixinkan
//
// Token Android TravelAlbumDetailScreen
//
import SwiftUI
///
enum TravelAlbumDetailDesign {
static let pageBackground = Color(hex: 0xF5F5F5)
static let text333 = Color(hex: 0x333333)
static let text999 = Color(hex: 0x999999)
static let lightBlue = Color(hex: 0xEAF4FF)
static let deleteRed = Color(hex: 0xE53935)
static let uploadedGreen = Color(hex: 0x34C759)
static let borderLight = Color(hex: 0xEEEEEE)
static let selectionInactiveBackground = Color(hex: 0xF4F4F4)
static let cardShadow = Color.black.opacity(0.08)
static let cardCornerRadius: CGFloat = 12
static let cardShadowRadius: CGFloat = 2
static let infoIconSize: CGFloat = 48
static let infoIconCornerRadius: CGFloat = 10
static let callButtonSize: CGFloat = 40
static let tabPillCornerRadius: CGFloat = 18
static let actionCircleSize: CGFloat = 32
static let gridHorizontalSpacing: CGFloat = 8
static let gridVerticalSpacing: CGFloat = 12
static let gridPadding: CGFloat = 12
static let thumbnailCornerRadius: CGFloat = 8
static let uploadedBadgeCornerRadius: CGFloat = 4
static let bottomButtonHeight: CGFloat = 48
static let bottomButtonCornerRadius: CGFloat = 10
static let contentHorizontalPadding: CGFloat = 16
static let sectionSpacing: CGFloat = 12
static let bottomBarHorizontalPadding: CGFloat = 20
static let bottomBarVerticalPadding: CGFloat = 12
static let selectionCheckSize: CGFloat = 20
}

View File

@ -0,0 +1,57 @@
//
// TravelAlbumDetailInfoCard.swift
// suixinkan
//
// Android AlbumInfoCard
//
import SwiftUI
///
struct TravelAlbumDetailInfoCard: View {
let album: TravelAlbumItem
let onCallClick: (String) -> Void
var body: some View {
HStack(spacing: 12) {
RoundedRectangle(cornerRadius: TravelAlbumDetailDesign.infoIconCornerRadius)
.fill(AppDesign.primary)
.frame(width: TravelAlbumDetailDesign.infoIconSize, height: TravelAlbumDetailDesign.infoIconSize)
.overlay {
Image(systemName: "list.clipboard.fill")
.font(.system(size: 28))
.foregroundStyle(.white)
}
VStack(alignment: .leading, spacing: 6) {
Text("手机号 \(OrderListUI.maskPhone(album.displayPhone))")
.font(.system(size: 14, weight: .medium))
.foregroundStyle(TravelAlbumDetailDesign.text333)
Text("创建时间 \(album.createdAt)")
.font(.system(size: 12))
.foregroundStyle(TravelAlbumDetailDesign.text999)
}
.frame(maxWidth: .infinity, alignment: .leading)
Button {
onCallClick(album.displayPhone)
} label: {
Circle()
.fill(TravelAlbumDetailDesign.lightBlue)
.frame(width: TravelAlbumDetailDesign.callButtonSize, height: TravelAlbumDetailDesign.callButtonSize)
.overlay {
Image(systemName: "phone.fill")
.font(.system(size: 20))
.foregroundStyle(AppDesign.primary)
}
}
.buttonStyle(.plain)
.accessibilityLabel("拨打电话")
}
.padding(.horizontal, 14)
.padding(.vertical, 14)
.background(Color.white)
.clipShape(RoundedRectangle(cornerRadius: TravelAlbumDetailDesign.cardCornerRadius))
.shadow(color: TravelAlbumDetailDesign.cardShadow, radius: TravelAlbumDetailDesign.cardShadowRadius, x: 0, y: 1)
}
}

View File

@ -0,0 +1,80 @@
//
// TravelAlbumDetailMaterialGridItem.swift
// suixinkan
//
// Android MaterialGridItem
//
import SwiftUI
///
struct TravelAlbumDetailMaterialGridItem: View {
let material: TravelAlbumMaterial
let isSelectionMode: Bool
let isSelected: Bool
let onSelect: () -> Void
let onPreview: () -> Void
var body: some View {
VStack(alignment: .leading, spacing: 4) {
thumbnailSection
MiddleTruncatedText(
text: material.fileName,
font: .systemFont(ofSize: 11),
textColor: UIColor(TravelAlbumDetailDesign.text333)
)
.frame(maxWidth: .infinity, minHeight: 14, maxHeight: 14, alignment: .leading)
Text(WiredTransferPhotoRecord.formatFileSize(Int64(material.fileSize)))
.font(.system(size: 10))
.foregroundStyle(TravelAlbumDetailDesign.text999)
.lineLimit(1)
}
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
.onTapGesture {
if isSelectionMode {
onSelect()
} else {
onPreview()
}
}
}
/// 1:1
private var thumbnailSection: some View {
Color.clear
.aspectRatio(1, contentMode: .fit)
.overlay {
RemoteImage(
urlString: material.thumbnailURLString,
contentMode: .fill
) {
Color(hex: 0xE5E7EB)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.clipShape(RoundedRectangle(cornerRadius: TravelAlbumDetailDesign.thumbnailCornerRadius))
.overlay(alignment: .topLeading) {
Text("已上传")
.font(.system(size: 10))
.foregroundStyle(.white)
.padding(.horizontal, 4)
.padding(.vertical, 2)
.background(TravelAlbumDetailDesign.uploadedGreen)
.clipShape(RoundedRectangle(cornerRadius: TravelAlbumDetailDesign.uploadedBadgeCornerRadius))
.padding(4)
}
.overlay(alignment: .topTrailing) {
if isSelectionMode {
Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")
.font(.system(size: TravelAlbumDetailDesign.selectionCheckSize))
.foregroundStyle(isSelected ? AppDesign.primary : .white)
.padding(4)
.background(Color.black.opacity(0.4), in: Circle())
.padding(4)
}
}
}
}

View File

@ -0,0 +1,153 @@
//
// TravelAlbumDetailPhotoManageCard.swift
// suixinkan
//
// Android PhotoManageCard
//
import SwiftUI
///
struct TravelAlbumDetailPhotoManageCard: View {
let materials: [TravelAlbumMaterial]
let allPhotoCount: Int
let selectedTab: Int
let orderBy: Int
let isSelectionMode: Bool
let selectedMaterialIDs: Set<Int>
let onTabSelect: (Int) -> Void
let onOrderBySelect: (Int) -> Void
let onToggleSelectionMode: () -> Void
let onMaterialClick: (TravelAlbumMaterial) -> Void
let onMaterialPreview: (TravelAlbumMaterial) -> Void
let onLoadMore: (Int) -> Void
private let gridColumns = [
GridItem(.flexible(), spacing: TravelAlbumDetailDesign.gridHorizontalSpacing),
GridItem(.flexible(), spacing: TravelAlbumDetailDesign.gridHorizontalSpacing),
GridItem(.flexible())
]
var body: some View {
VStack(spacing: 0) {
tabToolbar
Divider().overlay(TravelAlbumDetailDesign.borderLight)
photoGrid
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
.background(Color.white)
.clipShape(RoundedRectangle(cornerRadius: TravelAlbumDetailDesign.cardCornerRadius))
.shadow(color: TravelAlbumDetailDesign.cardShadow, radius: TravelAlbumDetailDesign.cardShadowRadius, x: 0, y: 1)
}
private var tabToolbar: some View {
HStack(spacing: 8) {
HStack(spacing: 8) {
tabPill(
text: "全部照片\(allPhotoCount)",
selected: selectedTab == TravelAlbumDetailViewModel.tabAll
) {
onTabSelect(TravelAlbumDetailViewModel.tabAll)
}
tabPill(
text: "已购照片",
selected: selectedTab == TravelAlbumDetailViewModel.tabPurchased
) {
onTabSelect(TravelAlbumDetailViewModel.tabPurchased)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
sortMenu
if selectedTab == TravelAlbumDetailViewModel.tabAll {
Button(action: onToggleSelectionMode) {
Circle()
.fill(isSelectionMode ? TravelAlbumDetailDesign.lightBlue : TravelAlbumDetailDesign.selectionInactiveBackground)
.frame(width: TravelAlbumDetailDesign.actionCircleSize, height: TravelAlbumDetailDesign.actionCircleSize)
.overlay {
Image(systemName: isSelectionMode ? "checkmark.circle.fill" : "circle")
.font(.system(size: 18))
.foregroundStyle(isSelectionMode ? AppDesign.primary : TravelAlbumDetailDesign.text999)
}
}
.buttonStyle(.plain)
.accessibilityLabel("选择")
}
}
.padding(.horizontal, 12)
.padding(.vertical, 12)
}
private var sortMenu: some View {
Menu {
ForEach(TravelAlbumDetailViewModel.sortOptions, id: \.value) { option in
Button {
onOrderBySelect(option.value)
} label: {
if orderBy == option.value {
Label(option.label, systemImage: "checkmark")
} else {
Text(option.label)
}
}
}
} label: {
Circle()
.fill(TravelAlbumDetailDesign.lightBlue)
.frame(width: TravelAlbumDetailDesign.actionCircleSize, height: TravelAlbumDetailDesign.actionCircleSize)
.overlay {
Image(systemName: "line.3.horizontal.decrease")
.font(.system(size: 16))
.foregroundStyle(AppDesign.primary)
}
}
.accessibilityLabel("筛选")
}
private var photoGrid: some View {
ScrollView {
if materials.isEmpty {
Text("暂无照片")
.font(.system(size: 14))
.foregroundStyle(TravelAlbumDetailDesign.text999)
.frame(maxWidth: .infinity, minHeight: 180)
} else {
LazyVGrid(
columns: gridColumns,
spacing: TravelAlbumDetailDesign.gridVerticalSpacing
) {
ForEach(Array(materials.enumerated()), id: \.element.id) { index, material in
TravelAlbumDetailMaterialGridItem(
material: material,
isSelectionMode: isSelectionMode,
isSelected: selectedMaterialIDs.contains(material.id),
onSelect: { onMaterialClick(material) },
onPreview: { onMaterialPreview(material) }
)
.onAppear {
onLoadMore(index)
}
}
}
.padding(TravelAlbumDetailDesign.gridPadding)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.clipped()
}
/// Tab
private func tabPill(text: String, selected: Bool, action: @escaping () -> Void) -> some View {
Button(action: action) {
Text(text)
.font(.system(size: 13, weight: selected ? .medium : .regular))
.foregroundStyle(selected ? Color.white : AppDesign.primary)
.padding(.horizontal, 14)
.padding(.vertical, 7)
.background(selected ? AppDesign.primary : TravelAlbumDetailDesign.lightBlue)
.clipShape(RoundedRectangle(cornerRadius: TravelAlbumDetailDesign.tabPillCornerRadius))
}
.buttonStyle(.plain)
}
}

View File

@ -7,7 +7,7 @@
import SwiftUI
///
/// Android TravelAlbumDetailScreen
struct TravelAlbumDetailView: View {
let albumID: Int
@ -16,9 +16,13 @@ struct TravelAlbumDetailView: View {
@EnvironmentObject private var toastCenter: ToastCenter
@Environment(\.globalLoading) private var globalLoading
@Environment(\.dismiss) private var dismiss
@Environment(\.openURL) private var openURL
@StateObject private var viewModel = TravelAlbumDetailViewModel()
@State private var showDeleteConfirm = false
@State private var showMoreMenu = false
@State private var navigateToWiredTransfer = false
@State private var didReturnFromWiredTransfer = false
@State private var previewPayload: TravelAlbumMaterialPreviewPayload?
private var photoStore: WiredTransferPhotoStore {
WiredTransferPhotoStore(
@ -28,125 +32,186 @@ struct TravelAlbumDetailView: View {
}
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: AppMetrics.Spacing.medium) {
if let album = viewModel.album {
albumHeader(album)
}
if viewModel.materials.isEmpty, !viewModel.isLoading {
AppContentUnavailableView("暂无素材", systemImage: "photo.on.rectangle")
.frame(maxWidth: .infinity, minHeight: 200)
} else {
LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())], spacing: 8) {
ForEach(viewModel.materials) { material in
materialCell(material)
}
}
}
Group {
if viewModel.isLoading, viewModel.album == nil {
ProgressView()
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else if viewModel.album != nil {
contentView
} else {
Text("加载失败")
.font(.system(size: 14))
.foregroundStyle(TravelAlbumDetailDesign.text333)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.padding(.horizontal, AppMetrics.Spacing.pageHorizontal)
.padding(.vertical, AppMetrics.Spacing.medium)
}
.background(Color(hex: 0xF5F7FA))
.navigationTitle(viewModel.album?.name ?? "相册详情")
.background(TravelAlbumDetailDesign.pageBackground.ignoresSafeArea())
.navigationTitle("相册管理")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItemGroup(placement: .topBarTrailing) {
if let album = viewModel.album {
NavigationLink {
WiredCameraTransferView(context: WiredTransferContext(
albumId: album.id,
albumName: album.name,
phone: album.displayPhone,
orderNumber: album.orderNumber
))
} label: {
Image(systemName: "cable.connector")
ToolbarItem(placement: .topBarTrailing) {
Menu {
Button("删除相册", role: .destructive) {
viewModel.showDeleteAlbumConfirm = true
}
.accessibilityLabel("有线传图")
}
Button(role: .destructive) {
showDeleteConfirm = true
} label: {
Image(systemName: "trash")
Image(systemName: "ellipsis")
.foregroundStyle(TravelAlbumDetailDesign.text333)
}
.accessibilityLabel("删除相册")
.accessibilityLabel("更多")
}
}
.confirmationDialog("确认删除该相册?", isPresented: $showDeleteConfirm, titleVisibility: .visible) {
.safeAreaInset(edge: .bottom) {
bottomBar
}
.background(wiredTransferNavigationLink)
.sheet(item: $previewPayload) { payload in
WiredTransferPhotoPreviewSheet(
imageSources: payload.sources,
startIndex: payload.startIndex,
onDismiss: { previewPayload = nil }
)
}
.confirmationDialog("删除相册", isPresented: $viewModel.showDeleteAlbumConfirm, titleVisibility: .visible) {
Button("删除", role: .destructive) {
Task { await deleteAlbum() }
}
Button("取消", role: .cancel) {}
} message: {
Text("确定删除该相册吗?已有购买素材的相册无法删除。")
}
.confirmationDialog("删除素材", isPresented: $viewModel.showDeleteMaterialConfirm, titleVisibility: .visible) {
Button("删除", role: .destructive) {
Task { await deleteSelectedMaterials() }
}
Button("取消", role: .cancel) {}
} message: {
Text("确定删除选中的 \(viewModel.selectedMaterialIDs.count) 张素材吗?")
}
.task(id: albumID) {
globalLoading.show()
defer { globalLoading.hide() }
await viewModel.load(api: travelAlbumAPI, albumID: albumID)
await viewModel.refreshAll(api: travelAlbumAPI, albumID: albumID)
}
.refreshable {
await viewModel.load(api: travelAlbumAPI, albumID: albumID)
.onChange(of: navigateToWiredTransfer) { isActive in
guard !isActive, didReturnFromWiredTransfer else { return }
didReturnFromWiredTransfer = false
Task { await viewModel.refreshAll(api: travelAlbumAPI, albumID: albumID) }
}
.onChange(of: viewModel.errorMessage) { message in
guard let message, !message.isEmpty else { return }
toastCenter.show(message)
viewModel.errorMessage = nil
}
}
private func albumHeader(_ album: TravelAlbumItem) -> some View {
VStack(alignment: .leading, spacing: 8) {
Text(album.type == 1 ? "先拍再买" : "买了再拍")
.font(.system(size: AppMetrics.FontSize.caption))
.foregroundStyle(AppDesign.primary)
if !album.displayPhone.isEmpty {
Label(album.displayPhone, systemImage: "phone.fill")
.font(.system(size: AppMetrics.FontSize.subheadline))
.foregroundStyle(AppDesign.textSecondary)
}
if !album.orderNumber.isEmpty {
Text("订单号:\(album.orderNumber)")
.font(.system(size: AppMetrics.FontSize.caption))
.foregroundStyle(AppDesign.textSecondary)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(AppMetrics.Spacing.large)
.background(Color.white)
.clipShape(RoundedRectangle(cornerRadius: AppMetrics.CornerRadius.card))
}
private func materialCell(_ material: TravelAlbumMaterial) -> some View {
ZStack(alignment: .topTrailing) {
RemoteImage(
urlString: material.coverURL.isEmpty ? material.fileURL : material.coverURL,
contentMode: .fill
) {
Color(hex: 0xE5E7EB)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
Menu {
Button(role: .destructive) {
Task {
await viewModel.deleteMaterial(api: travelAlbumAPI, materialID: material.id, albumID: albumID)
}
} label: {
Label("删除", systemImage: "trash")
private var contentView: some View {
VStack(spacing: TravelAlbumDetailDesign.sectionSpacing) {
if let album = viewModel.album {
TravelAlbumDetailInfoCard(album: album) { phone in
dialPhone(phone)
}
} label: {
Image(systemName: "ellipsis")
.padding(6)
.background(Color.black.opacity(0.35))
.foregroundStyle(.white)
.clipShape(Circle())
.padding(4)
}
TravelAlbumDetailPhotoManageCard(
materials: viewModel.materials,
allPhotoCount: viewModel.allPhotoCount,
selectedTab: viewModel.selectedTab,
orderBy: viewModel.orderBy,
isSelectionMode: viewModel.isSelectionMode,
selectedMaterialIDs: viewModel.selectedMaterialIDs,
onTabSelect: { tab in
Task { await viewModel.selectTab(tab, api: travelAlbumAPI) }
},
onOrderBySelect: { order in
Task { await viewModel.setOrderBy(order, api: travelAlbumAPI) }
},
onToggleSelectionMode: {
viewModel.toggleSelectionMode()
},
onMaterialClick: { material in
viewModel.toggleMaterialSelection(material)
},
onMaterialPreview: { material in
openMaterialPreview(material)
},
onLoadMore: { index in
Task { await viewModel.loadMoreIfNeeded(lastVisibleIndex: index, api: travelAlbumAPI) }
}
)
.frame(maxHeight: .infinity)
}
.aspectRatio(1, contentMode: .fit)
.frame(maxWidth: .infinity)
.clipShape(RoundedRectangle(cornerRadius: 8))
.padding(.horizontal, TravelAlbumDetailDesign.contentHorizontalPadding)
.padding(.top, 12)
.padding(.bottom, 8)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
}
private var bottomBar: some View {
VStack(spacing: 8) {
if viewModel.isSelectionMode, !viewModel.selectedMaterialIDs.isEmpty {
Button {
viewModel.requestDeleteSelectedMaterials()
} label: {
Text("删除选中(\(viewModel.selectedMaterialIDs.count))")
.font(.system(size: 16))
.foregroundStyle(.white)
.frame(maxWidth: .infinity)
.frame(height: TravelAlbumDetailDesign.bottomButtonHeight)
.background(TravelAlbumDetailDesign.deleteRed)
.clipShape(RoundedRectangle(cornerRadius: TravelAlbumDetailDesign.bottomButtonCornerRadius))
}
.buttonStyle(.plain)
}
Button {
didReturnFromWiredTransfer = true
navigateToWiredTransfer = true
} label: {
Text("上传照片")
.font(.system(size: 16, weight: .medium))
.foregroundStyle(.white)
.frame(maxWidth: .infinity)
.frame(height: TravelAlbumDetailDesign.bottomButtonHeight)
.background(AppDesign.primary)
.clipShape(RoundedRectangle(cornerRadius: TravelAlbumDetailDesign.bottomButtonCornerRadius))
}
.buttonStyle(.plain)
}
.padding(.horizontal, TravelAlbumDetailDesign.bottomBarHorizontalPadding)
.padding(.vertical, TravelAlbumDetailDesign.bottomBarVerticalPadding)
.background(TravelAlbumDetailDesign.pageBackground)
}
@ViewBuilder
private var wiredTransferNavigationLink: some View {
if let context = viewModel.wiredTransferContext() {
NavigationLink(isActive: $navigateToWiredTransfer) {
WiredCameraTransferView(context: context)
} label: {
EmptyView()
}
.hidden()
}
}
///
private func dialPhone(_ phone: String) {
let trimmed = phone.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, let url = URL(string: "tel:\(trimmed)") else { return }
openURL(url)
}
///
private func openMaterialPreview(_ material: TravelAlbumMaterial) {
let previewMaterials = viewModel.materials.filter { !$0.previewURLString.isEmpty }
guard !material.previewURLString.isEmpty else {
toastCenter.show("暂无法预览该照片")
return
}
let sources = previewMaterials.map(\.previewURLString)
let startIndex = previewMaterials.firstIndex(where: { $0.id == material.id }) ?? 0
previewPayload = TravelAlbumMaterialPreviewPayload(sources: sources, startIndex: startIndex)
}
private func deleteAlbum() async {
@ -158,4 +223,20 @@ struct TravelAlbumDetailView: View {
dismiss()
}
}
private func deleteSelectedMaterials() async {
globalLoading.show()
defer { globalLoading.hide() }
let success = await viewModel.confirmDeleteSelectedMaterials(api: travelAlbumAPI)
if success {
toastCenter.show("删除成功")
}
}
}
/// Sheet
private struct TravelAlbumMaterialPreviewPayload: Identifiable {
let id = UUID()
let sources: [String]
let startIndex: Int
}

View File

@ -53,7 +53,7 @@ struct WiredCameraTransferView: View {
cameraDeviceName: viewModel.cameraDeviceName,
transferModeOption: viewModel.transferModeOption,
tabTitles: tabTitles,
tabCounts: viewModel.photos.transferTabCounts,
tabCounts: viewModel.tabCounts,
selectedTabIndex: viewModel.selectedTabIndex,
onDeviceUsageClick: viewModel.onDeviceUsageClick,
onRefreshCameraFiles: {
@ -168,11 +168,11 @@ struct WiredCameraTransferView: View {
}
private var sidebarGroups: [WiredTransferDateGroup] {
visiblePhotos.buildSidebarGroups()
viewModel.sidebarGroups
}
private var photoSections: [WiredTransferPhotoSection] {
visiblePhotos.buildPhotoSections()
viewModel.photoSections
}
private var selectAllBar: some View {
@ -202,7 +202,16 @@ struct WiredCameraTransferView: View {
onToggleSidebar: viewModel.toggleSidebar,
onTimeSlotSelected: viewModel.selectTimeSlot,
onPhotoClick: openPhotoPreview,
onRetry: { id in Task { await viewModel.retryPhoto(id: id) } },
onRetry: { id in
Task {
await viewModel.retryPhoto(
id: id,
api: travelAlbumAPI,
ossService: ossUploadService,
scenicID: scenicID
)
}
},
onDelete: viewModel.deletePhoto,
onTogglePhotoSelection: viewModel.togglePhotoSelection
)

View File

@ -4,7 +4,6 @@
//
import SwiftUI
import UIKit
import Kingfisher
/// 线 file:// URL
@ -19,7 +18,8 @@ struct WiredTransferPhotoPreviewSheet: View {
self.imageSources = imageSources
self.startIndex = startIndex
self.onDismiss = onDismiss
_currentIndex = State(initialValue: startIndex)
let safeIndex = imageSources.isEmpty ? 0 : min(max(startIndex, 0), imageSources.count - 1)
_currentIndex = State(initialValue: safeIndex)
}
var body: some View {
@ -46,12 +46,7 @@ struct WiredTransferPhotoPreviewSheet: View {
@ViewBuilder
private func previewImage(_ source: String) -> some View {
if source.hasPrefix("file://"), let url = URL(string: source),
let uiImage = UIImage(contentsOfFile: url.path) {
Image(uiImage: uiImage)
.resizable()
.scaledToFit()
} else if let url = URL(string: source), !source.isEmpty {
if let url = URL(string: source), !source.isEmpty {
KFImage(url)
.resizable()
.scaledToFit()

View File

@ -3,6 +3,7 @@
// suixinkan
//
import Kingfisher
import SwiftUI
import UIKit
@ -23,36 +24,40 @@ struct WiredTransferPhotoRow: View {
var body: some View {
VStack(spacing: 0) {
HStack(alignment: .center, spacing: 8) {
if selectUploadMode {
Button(action: onToggleSelection) {
HStack(alignment: .center, spacing: 8) {
if selectUploadMode {
WiredTransferSelectIndicator(selected: selected, enabled: canSelect)
}
.buttonStyle(.plain)
.disabled(!canSelect)
}
thumbnailView
.frame(width: WiredTransferDesign.thumbnailSize, height: WiredTransferDesign.thumbnailSize)
.clipShape(RoundedRectangle(cornerRadius: WiredTransferDesign.thumbnailCornerRadius))
.opacity(rowOpacity)
.onTapGesture {
if !selectUploadMode { onPhotoClick() }
}
thumbnailView
.frame(width: WiredTransferDesign.thumbnailSize, height: WiredTransferDesign.thumbnailSize)
.clipShape(RoundedRectangle(cornerRadius: WiredTransferDesign.thumbnailCornerRadius))
.opacity(rowOpacity)
VStack(alignment: .leading, spacing: 3) {
HStack(spacing: 4) {
Text(photo.fileName)
.font(.system(size: 12, weight: .medium))
.foregroundStyle(WiredTransferDesign.text333.opacity(rowOpacity))
VStack(alignment: .leading, spacing: 3) {
HStack(spacing: 4) {
Text(photo.fileName)
.font(.system(size: 12, weight: .medium))
.foregroundStyle(WiredTransferDesign.text333.opacity(rowOpacity))
.lineLimit(1)
Spacer(minLength: 0)
WiredTransferStatusBadge(status: photo.status)
.opacity(rowOpacity)
}
Text(metaText)
.font(.system(size: 10))
.foregroundStyle(WiredTransferDesign.text999.opacity(rowOpacity))
.lineLimit(1)
Spacer(minLength: 0)
WiredTransferStatusBadge(status: photo.status)
.opacity(rowOpacity)
}
Text(metaText)
.font(.system(size: 10))
.foregroundStyle(WiredTransferDesign.text999.opacity(rowOpacity))
.lineLimit(1)
}
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
.onTapGesture {
if selectUploadMode {
if canSelect { onToggleSelection() }
} else {
onPhotoClick()
}
}
if !selectUploadMode {
@ -71,10 +76,6 @@ struct WiredTransferPhotoRow: View {
}
.padding(.horizontal, 10)
.padding(.vertical, 8)
.contentShape(Rectangle())
.onTapGesture {
if selectUploadMode, canSelect { onToggleSelection() }
}
if photo.status == .transferring || photo.status == .uploading {
ProgressView(value: Double(photo.progress), total: 100)
@ -93,18 +94,20 @@ struct WiredTransferPhotoRow: View {
@ViewBuilder
private var thumbnailView: some View {
if photo.thumbnailURL.hasPrefix("file://"), let url = URL(string: photo.thumbnailURL) {
if let uiImage = UIImage(contentsOfFile: url.path) {
Image(uiImage: uiImage)
.resizable()
.aspectRatio(contentMode: .fill)
} else {
thumbnailPlaceholder
}
} else if !photo.thumbnailURL.isEmpty {
RemoteImage(urlString: photo.thumbnailURL) {
thumbnailPlaceholder
}
if let url = URL(string: photo.thumbnailURL), !photo.thumbnailURL.isEmpty {
KFImage(url)
.placeholder { thumbnailPlaceholder }
.setProcessor(
DownsamplingImageProcessor(
size: CGSize(
width: WiredTransferDesign.thumbnailSize,
height: WiredTransferDesign.thumbnailSize
)
)
)
.scaleFactor(UIScreen.main.scale)
.resizable()
.aspectRatio(contentMode: .fill)
} else {
thumbnailPlaceholder
}