合并 9.9.1 机巢工作台与拍摄交付流程 #1
|
After Width: | Height: | Size: 1.9 MiB |
|
After Width: | Height: | Size: 346 KiB |
|
After Width: | Height: | Size: 1.9 MiB |
|
After Width: | Height: | Size: 1.9 MiB |
@@ -0,0 +1,119 @@
|
||||
{
|
||||
"date": "2026-10-26",
|
||||
"tests": 24,
|
||||
"failures": 0,
|
||||
"screenshots": [
|
||||
{
|
||||
"file": "paused.png",
|
||||
"state": "空镜库-后台暂停待继续",
|
||||
"test": "ScenicMaterialsFlowViewTests/testBackgroundPausesRejectsStaleCallbacksAndRequiresManualResume()",
|
||||
"source": "iPhone 11 XCTest window",
|
||||
"timestamp": 1792999280.445
|
||||
},
|
||||
{
|
||||
"file": "permission.png",
|
||||
"state": "空镜库-相册权限演示说明",
|
||||
"test": "ScenicMaterialsFlowViewTests/testDeniedDemoPermissionShowsExplanationWithoutStartingBatch()",
|
||||
"source": "iPhone 11 XCTest window",
|
||||
"timestamp": 1792999283.667
|
||||
},
|
||||
{
|
||||
"file": "completed.png",
|
||||
"state": "空镜库-下载演示完成",
|
||||
"test": "ScenicMaterialsFlowViewTests/testDownloadButtonCompletesLocalDemoAndKeepsSuccessfulClipUnavailable()",
|
||||
"source": "iPhone 11 XCTest window",
|
||||
"timestamp": 1792999286.855
|
||||
},
|
||||
{
|
||||
"file": "downloading.png",
|
||||
"state": "空镜库-本地下载演示",
|
||||
"test": "ScenicMaterialsFlowViewTests/testDownloadButtonCompletesLocalDemoAndKeepsSuccessfulClipUnavailable()",
|
||||
"source": "iPhone 11 XCTest window",
|
||||
"timestamp": 1792999285.283
|
||||
},
|
||||
{
|
||||
"file": "expanded-simulator.jpg",
|
||||
"state": "空镜库-展开第六段",
|
||||
"test": "ScenicMaterialsFlowViewTests/testIndependentEntryAndSixClipGroupSelectionAcrossExpandedLayout()",
|
||||
"source": "iPhone 18 Pro Simulator visual check",
|
||||
"verification": "Physical layout test passed; blank XCTest image replaced by verified simulator capture"
|
||||
},
|
||||
{
|
||||
"file": "group-selected.png",
|
||||
"state": "空镜库-整组六段含折叠选择",
|
||||
"test": "ScenicMaterialsFlowViewTests/testIndependentEntryAndSixClipGroupSelectionAcrossExpandedLayout()",
|
||||
"source": "iPhone 11 XCTest window",
|
||||
"timestamp": 1792999559.928,
|
||||
"verification": "Final expanded-layout retest"
|
||||
},
|
||||
{
|
||||
"file": "selected.png",
|
||||
"state": "空镜库-双列片段选择",
|
||||
"test": "ScenicMaterialsFlowViewTests/testIndependentEntryAndSixClipGroupSelectionAcrossExpandedLayout()",
|
||||
"source": "iPhone 11 XCTest window",
|
||||
"timestamp": 1792999558.906,
|
||||
"verification": "Final expanded-layout retest"
|
||||
},
|
||||
{
|
||||
"file": "library.png",
|
||||
"state": "空镜库-常态首段与双列",
|
||||
"test": "ScenicMaterialsFlowViewTests/testIndependentEntryAndSixClipGroupSelectionAcrossExpandedLayout()",
|
||||
"source": "iPhone 11 XCTest window",
|
||||
"timestamp": 1792999558.633,
|
||||
"verification": "Final expanded-layout retest"
|
||||
},
|
||||
{
|
||||
"file": "preview.png",
|
||||
"state": "空镜库-视频预览",
|
||||
"test": "ScenicMaterialsFlowViewTests/testPreviewOpenAndClosePreservesPausedBatchAndSelection()",
|
||||
"source": "iPhone 11 XCTest window",
|
||||
"timestamp": 1792999291.454
|
||||
},
|
||||
{
|
||||
"file": "retry-completed.png",
|
||||
"state": "空镜库-失败重试完成",
|
||||
"test": "ScenicMaterialsFlowViewTests/testRetryFailureOnlyRunsFailedClipAndPreservesSuccessfulDownloads()",
|
||||
"source": "iPhone 11 XCTest window",
|
||||
"timestamp": 1792999295.183
|
||||
},
|
||||
{
|
||||
"file": "partial-failure.png",
|
||||
"state": "空镜库-部分失败可重试",
|
||||
"test": "ScenicMaterialsFlowViewTests/testRetryFailureOnlyRunsFailedClipAndPreservesSuccessfulDownloads()",
|
||||
"source": "iPhone 11 XCTest window",
|
||||
"timestamp": 1792999293.652
|
||||
},
|
||||
{
|
||||
"file": "date-result.png",
|
||||
"state": "空镜库-日期筛选结果",
|
||||
"test": "ScenicMaterialsFlowViewTests/testRouteAndDateSheetCallbacksFilterResultsAndResetEmptyRoute()",
|
||||
"source": "iPhone 11 XCTest window",
|
||||
"timestamp": 1792999300.73
|
||||
},
|
||||
{
|
||||
"file": "date-filter.png",
|
||||
"state": "空镜库-起止日期筛选",
|
||||
"test": "ScenicMaterialsFlowViewTests/testRouteAndDateSheetCallbacksFilterResultsAndResetEmptyRoute()",
|
||||
"source": "iPhone 11 XCTest window",
|
||||
"timestamp": 1792999299.615
|
||||
},
|
||||
{
|
||||
"file": "no-results.png",
|
||||
"state": "空镜库-航线无结果",
|
||||
"test": "ScenicMaterialsFlowViewTests/testRouteAndDateSheetCallbacksFilterResultsAndResetEmptyRoute()",
|
||||
"source": "iPhone 11 XCTest window",
|
||||
"timestamp": 1792999297.768
|
||||
},
|
||||
{
|
||||
"file": "route-filter.png",
|
||||
"state": "空镜库-航线筛选",
|
||||
"test": "ScenicMaterialsFlowViewTests/testRouteAndDateSheetCallbacksFilterResultsAndResetEmptyRoute()",
|
||||
"source": "iPhone 11 XCTest window",
|
||||
"timestamp": 1792999296.677
|
||||
}
|
||||
],
|
||||
"finalLayoutRetest": {
|
||||
"tests": 1,
|
||||
"failures": 0
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 88 KiB |
|
After Width: | Height: | Size: 1.9 MiB |
|
After Width: | Height: | Size: 1.9 MiB |
|
After Width: | Height: | Size: 330 KiB |
|
After Width: | Height: | Size: 1.9 MiB |
|
After Width: | Height: | Size: 1.9 MiB |
|
After Width: | Height: | Size: 1.7 MiB |
|
After Width: | Height: | Size: 1.0 MiB |
|
After Width: | Height: | Size: 1.9 MiB |
|
After Width: | Height: | Size: 990 KiB |
|
After Width: | Height: | Size: 1.9 MiB |
@@ -0,0 +1,76 @@
|
||||
# 9.9.1 景区空镜库 UI 实现说明
|
||||
|
||||
实现日期:2026-10-26。分支:`dev_9_9_1`。
|
||||
|
||||
## 范围与入口
|
||||
|
||||
依据 2026-10-26 实际查看的[产品体验网页](https://voicestudio.suixinkan.cn/)搭建独立景区空镜库。页面标题沿用原型的“景区素材”,采用白底、航线/时间筛选、首段大图和后续双列卡片、按拍摄时间分组、底部固定下载栏。
|
||||
|
||||
景区空镜库与机巢工作台各自独立。本模块不依赖机巢订单、拍摄任务、剩余次数或成片交付。正式首页入口等待单独的菜单配置与权限 URI;现有 `drone_dock` 仍只指向机巢工作台。
|
||||
|
||||
本轮使用本地数据搭建交互,不接真实接口。Debug 版从“首页 → 更多功能 → 全部功能”右上角“空镜预览”进入;无需先打开机巢工作台。页面右上角提供本地状态菜单。
|
||||
|
||||
## 页面与交互
|
||||
|
||||
| 功能 | 本轮实现 |
|
||||
| --- | --- |
|
||||
| 航线筛选 | 全部航线、指定航线,选择后应用;暂无素材的航线显示筛选空态。 |
|
||||
| 日期筛选 | 选择起止日期或全部时间,确定后应用,取消不改变原条件;包含首尾两天。使用 iOS 日期滚轮。 |
|
||||
| 保留期 | 演示显示 90 天,包含今天及此前 89 天;排除未来和保留期外记录。正式值以后端配置为准。 |
|
||||
| 分组浏览 | 航线分区,同航线拍摄时间倒序;每组首段大图,其余双列,默认最多显示 5 段,可展开/收起。 |
|
||||
| 选择 | 单段勾选与视频预览独立;整组选中包含折叠片段;切换筛选时清除筛选范围外的选择。 |
|
||||
| 预览 | 独立半屏预览,展示航线、拍摄时间、片段信息,可播放随包的 3 秒示例短片;原片时长与演示短片明确区分。 |
|
||||
| 下载演示 | 点击后逐段推进进度,显示批次总数和完成数;锁定选择与筛选,仍可浏览和预览。 |
|
||||
| 暂停/继续 | 离开页面、锁屏或进入后台暂停;回到前台需手动继续,成功项保留,未完成单项允许从头开始。 |
|
||||
| 部分失败 | 成功项不重复处理,只重试失败项;支持取消或继续选择。 |
|
||||
| 权限提示 | 演示相册权限不足及恢复后的手动重试,不申请或更改真实系统权限。 |
|
||||
| 空态 | 区分整个景区暂无素材与筛选无结果;有筛选条件时可重置。 |
|
||||
|
||||
下载、预览与选择均不扣拍摄次数、不改变订单状态。开始后冻结当前批次,暂停、继续、重试和取消会使旧回执失效。演示记录仅保存在当前页面内存中,重新进入会重置。
|
||||
|
||||
## 实现结构
|
||||
|
||||
- `Features/ScenicMaterials/Models/ScenicMaterialModels.swift`:独立账号/景区上下文、航线、批次、片段和下载状态。
|
||||
- `Features/ScenicMaterials/ViewModels/ScenicMaterialsViewModel.swift`:Foundation 逻辑,管理筛选、选择、保留期及下载批次。
|
||||
- `UI/ScenicMaterials/ScenicMaterialsViewController.swift`:UIKit + SnapKit,Diffable Data Source 与 Compositional Layout,按操作显式刷新。
|
||||
- 同目录的组件、筛选面板、预览和演示驱动分别负责展示与本地进度。
|
||||
- `ScenicMaterialsPreview.swift`:独立 Debug 启动入口,未添加正式首页 URI 或权限常量。
|
||||
|
||||
下载阶段包括 `idle`、`downloading`、`paused`、`partialFailure`、`completed`。片段还可展示 `available`、`failed`、`unavailable` 等状态。成功文案为“演示已下载/演示完成”,不表示写入系统相册。
|
||||
|
||||
| Debug 启动参数 | 用途 |
|
||||
| --- | --- |
|
||||
| `--scenic-materials-preview` | 直接打开独立空镜库。 |
|
||||
| `--scenic-materials-scenario=selected` | 已选择两段。 |
|
||||
| `--scenic-materials-scenario=downloading` | 固定下载中状态,供布局检查;正常点击下载会自动推进。 |
|
||||
| `--scenic-materials-scenario=partialFailure` | 一段成功、一段失败,可点击重试。 |
|
||||
| `--scenic-materials-scenario=paused` | 一段成功、一段待继续。 |
|
||||
| `--scenic-materials-scenario=completed` | 下载演示完成。 |
|
||||
| `--scenic-materials-scenario=empty` | 整库为空。 |
|
||||
| `--scenic-materials-scenario=noResults` | 航线筛选无结果。 |
|
||||
| `--scenic-materials-permission-denied` | 点击下载后显示本地权限说明。 |
|
||||
|
||||
## 验证
|
||||
|
||||
- iPhone 11 真机复测 **24 项、0 失败**:17 项模型/ViewModel 测试和 7 项实际 UI 联动测试。模拟器仅用于编译与首屏检查,未运行模拟器单元测试。
|
||||
- 验证筛选边界、90 天范围、独立上下文、隐藏第六段全选、真实筛选按钮、预览播放与关闭、下载演示完成、后台暂停、手动继续、旧回执隔离、失败项重试和权限不足。
|
||||
- 真机截图检查后修正了日期按钮文字与下载按钮标题的更新过渡,随后全量复测上述 24 项通过。另对展开后的奇数末行补充布局验证,追加真机复测 **1 项、0 失败**,确保“收起片段”独占整行。
|
||||
- 14 张截图来自真机 XCTest 隔离窗口,系统状态栏不在图片中。展开态真机测试截图为空白,因此该图采用最终版本的模拟器实际操作截图,已注明来源;文件与测试对应关系见 [evidence.json](scenic-materials-ui-2026-10-26/evidence.json)。未进行全工程回归。
|
||||
|
||||
| 默认列表 | 选择片段 | 展开第六段 |
|
||||
| --- | --- | --- |
|
||||
|  |  |  |
|
||||
|
||||
| 航线筛选 | 日期筛选 | 筛选无结果 |
|
||||
| --- | --- | --- |
|
||||
|  |  |  |
|
||||
|
||||
| 视频预览 | 下载演示 | 演示完成 |
|
||||
| --- | --- | --- |
|
||||
|  |  |  |
|
||||
|
||||
| 暂停待继续 | 部分失败 | 权限说明 |
|
||||
| --- | --- | --- |
|
||||
|  |  |  |
|
||||
|
||||
本轮不包含真实空镜列表、授权下载地址、网络传输、相册写入、持久化恢复或后端联调。后续需对接独立景区素材的筛选选项、批次/片段列表及下载授权;具体接口契约另行确认。
|
||||
@@ -0,0 +1,155 @@
|
||||
import Foundation
|
||||
|
||||
/// 景区空镜库的独立访问上下文,不依赖拍摄订单、机巢或无人机任务。
|
||||
struct ScenicMaterialContext: Hashable, Sendable {
|
||||
/// 当前账号标识,用于隔离本机演示状态。
|
||||
let userID: String
|
||||
/// 当前景区稳定标识。
|
||||
let scenicID: String
|
||||
/// 当前景区的展示名称。
|
||||
let scenicName: String
|
||||
|
||||
/// 创建空镜库上下文;不会改写 App 的真实登录或景区会话。
|
||||
init(userID: String, scenicID: String, scenicName: String) {
|
||||
self.userID = userID
|
||||
self.scenicID = scenicID
|
||||
self.scenicName = scenicName
|
||||
}
|
||||
|
||||
/// 仅供独立页面预览的演示身份。
|
||||
static let demo = ScenicMaterialContext(userID: "scenic-demo-user", scenicID: "scenic-demo-songshan", scenicName: "嵩山少林景区")
|
||||
}
|
||||
|
||||
/// 景区空镜航线,不以名称匹配游客拍摄航线。
|
||||
struct ScenicMaterialRoute: Hashable, Sendable {
|
||||
/// 航线稳定标识。
|
||||
let id: String
|
||||
/// 航线展示名称。
|
||||
let name: String
|
||||
|
||||
/// 创建可供筛选的独立空镜航线。
|
||||
init(id: String, name: String) {
|
||||
self.id = id
|
||||
self.name = name
|
||||
}
|
||||
}
|
||||
|
||||
/// 一次空镜拍摄批次;完整片段列表独立于 UI 是否折叠。
|
||||
struct ScenicMaterialGroup: Hashable, Sendable {
|
||||
/// 批次稳定标识。
|
||||
let id: String
|
||||
/// 所属空镜航线标识。
|
||||
let routeID: String
|
||||
/// 批次拍摄时间,用于日期筛选和航线内排序。
|
||||
let capturedAt: Date
|
||||
/// 批次完整片段列表,整组选择包含未展开片段。
|
||||
let clips: [ScenicMaterialClip]
|
||||
|
||||
/// 创建一组完整空镜片段。
|
||||
init(id: String, routeID: String, capturedAt: Date, clips: [ScenicMaterialClip]) {
|
||||
self.id = id
|
||||
self.routeID = routeID
|
||||
self.capturedAt = capturedAt
|
||||
self.clips = clips
|
||||
}
|
||||
}
|
||||
|
||||
/// 单个空镜视频片段的内容元数据;下载演示状态另由 ViewModel 管理。
|
||||
struct ScenicMaterialClip: Hashable, Sendable {
|
||||
/// 在当前访问上下文中稳定且唯一的片段标识。
|
||||
let id: String
|
||||
/// 所属拍摄批次标识。
|
||||
let groupID: String
|
||||
/// 组内从 1 开始的片段序号。
|
||||
let ordinal: Int
|
||||
/// 原片段展示时长;本地播放器使用独立演示视频。
|
||||
let durationSeconds: Int
|
||||
/// 原片段展示大小,单位为字节。
|
||||
let fileSizeBytes: Int64
|
||||
/// 原片段分辨率展示值。
|
||||
let resolution: String
|
||||
/// 本地演示封面资源名。
|
||||
let coverAssetName: String
|
||||
/// 文件是否仍可预览和下载;不可用文件仍可展示其元数据。
|
||||
let isAvailable: Bool
|
||||
|
||||
/// 创建片段元数据,不读取本地相册或请求网络。
|
||||
init(id: String, groupID: String, ordinal: Int, durationSeconds: Int, fileSizeBytes: Int64,
|
||||
resolution: String, coverAssetName: String, isAvailable: Bool = true) {
|
||||
self.id = id
|
||||
self.groupID = groupID
|
||||
self.ordinal = ordinal
|
||||
self.durationSeconds = durationSeconds
|
||||
self.fileSizeBytes = fileSizeBytes
|
||||
self.resolution = resolution
|
||||
self.coverAssetName = coverAssetName
|
||||
self.isAvailable = isAvailable
|
||||
}
|
||||
|
||||
/// 用于封面与预览信息的分秒时长。
|
||||
var durationText: String {
|
||||
let value = max(durationSeconds, 0)
|
||||
return String(format: "%02d:%02d", value / 60, value % 60)
|
||||
}
|
||||
|
||||
/// 使用十进制 MB 展示片段大小,避免将原文件与本地示例文件混淆。
|
||||
var sizeText: String {
|
||||
let megabytes = Double(max(fileSizeBytes, 0)) / 1_000_000
|
||||
return megabytes.rounded() == megabytes ? String(format: "%.0fMB", megabytes) : String(format: "%.1fMB", megabytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// 已规范化到日历日的闭区间筛选范围。
|
||||
struct ScenicMaterialDateRange: Hashable, Sendable {
|
||||
/// 起始日的零点,包含该日全部记录。
|
||||
let start: Date
|
||||
/// 结束日的零点,包含该日全部记录。
|
||||
let end: Date
|
||||
|
||||
/// 由 ViewModel 校验并规范化日期后创建。
|
||||
init(start: Date, end: Date) {
|
||||
self.start = start
|
||||
self.end = end
|
||||
}
|
||||
}
|
||||
|
||||
/// 本机批量下载演示的阶段,不代表服务器或系统相册已完成操作。
|
||||
enum ScenicMaterialDownloadPhase: String, Hashable, Sendable {
|
||||
case idle, downloading, paused, partialFailure, completed
|
||||
}
|
||||
|
||||
/// 单个演示片段的本机状态,供列表显示,不写入服务端素材模型。
|
||||
enum ScenicMaterialDownloadState: Hashable, Sendable {
|
||||
case available
|
||||
case downloading(progress: Double)
|
||||
case paused
|
||||
case failed
|
||||
case completed
|
||||
case unavailable
|
||||
}
|
||||
|
||||
/// 演示驱动对当前批次单项的回执;所有成功只表示本地 UI 演示完成。
|
||||
enum ScenicMaterialTransferEvent: Sendable {
|
||||
case progress(Double)
|
||||
case completed
|
||||
case failed
|
||||
}
|
||||
|
||||
/// 独立空镜库的可复现演示场景,不改变真实权限、订单或设备状态。
|
||||
enum ScenicMaterialsScenario: String, CaseIterable, Sendable {
|
||||
case normal, selected, downloading, completed, partialFailure, paused, empty, noResults
|
||||
|
||||
/// Debug 状态菜单的展示名称。
|
||||
var title: String {
|
||||
switch self {
|
||||
case .normal: "正常素材列表"
|
||||
case .selected: "已选两段"
|
||||
case .downloading: "下载中"
|
||||
case .completed: "下载演示完成"
|
||||
case .partialFailure: "部分下载失败"
|
||||
case .paused: "下载已暂停"
|
||||
case .empty: "暂无景区素材"
|
||||
case .noResults: "筛选无结果"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
import Foundation
|
||||
|
||||
/// 独立景区空镜库的筛选、选择和前台下载演示逻辑;不依赖 UIKit 或机巢业务。
|
||||
final class ScenicMaterialsViewModel {
|
||||
/// 本次页面的独立账号与景区范围。
|
||||
let context: ScenicMaterialContext
|
||||
/// 用于筛选的日历及其时区。
|
||||
let calendar: Calendar
|
||||
/// 本地演示保留天数,正式对接后由服务端配置决定。
|
||||
let retentionDays = 90
|
||||
/// 保留期首日零点,包含今天一共 90 个日历日。
|
||||
let minimumDate: Date
|
||||
/// 可选的最后一天零点,不允许选择未来日期。
|
||||
let maximumDate: Date
|
||||
/// 当前景区的独立空镜航线,含暂无片段的航线。
|
||||
private(set) var routes: [ScenicMaterialRoute]
|
||||
/// 当前演示数据集的所有批次,筛选不会修改它们。
|
||||
private(set) var allGroups: [ScenicMaterialGroup]
|
||||
/// 选择的航线标识,nil 代表全部航线。
|
||||
private(set) var selectedRouteID: String?
|
||||
/// 已应用的日历日筛选范围,nil 代表全部保留期。
|
||||
private(set) var dateRange: ScenicMaterialDateRange?
|
||||
/// 选择的未完成片段,不包含不可用或已完成文件。
|
||||
private(set) var selectedIDs = Set<String>()
|
||||
/// 需要展开超过五段的批次标识。
|
||||
private(set) var expandedGroupIDs = Set<String>()
|
||||
/// 当前下载演示阶段。
|
||||
private(set) var phase: ScenicMaterialDownloadPhase = .idle
|
||||
/// 当前传输尝试的令牌;暂停、继续和重试会作废旧令牌。
|
||||
private(set) var batchID: UUID?
|
||||
/// 本次下载完整范围,重试时仍保留已完成项用于展示进度。
|
||||
private(set) var batchItemIDs: [String] = []
|
||||
/// 当前页面已完成演示的片段;不等于写入系统相册。
|
||||
private(set) var completedIDs = Set<String>()
|
||||
/// 当前批次明确失败的片段,可单独重试。
|
||||
private(set) var failedIDs = Set<String>()
|
||||
/// 当前批次的逐项演示进度。
|
||||
private(set) var progressByID: [String: Double] = [:]
|
||||
|
||||
private let initialGroups: [ScenicMaterialGroup]
|
||||
|
||||
/// 创建演示库;可注入日历、日期和数据,测试不依赖时间、网络或登录单例。
|
||||
init(context: ScenicMaterialContext = .demo, now: Date = Date(), calendar: Calendar = .current,
|
||||
routes: [ScenicMaterialRoute]? = nil, groups: [ScenicMaterialGroup]? = nil) {
|
||||
self.context = context
|
||||
self.calendar = calendar
|
||||
maximumDate = calendar.startOfDay(for: now)
|
||||
minimumDate = calendar.date(byAdding: .day, value: -(retentionDays - 1), to: maximumDate) ?? maximumDate
|
||||
let demoRoutes = Self.makeRoutes(context: context)
|
||||
self.routes = routes ?? demoRoutes
|
||||
let data = groups ?? Self.makeGroups(context: context, routes: demoRoutes, today: maximumDate, calendar: calendar)
|
||||
initialGroups = data
|
||||
allGroups = data
|
||||
}
|
||||
|
||||
/// 按航线分区、同航线时间倒序的有效批次;保留期外记录不会进入显示或选择范围。
|
||||
var filteredGroups: [ScenicMaterialGroup] {
|
||||
let routeOrder = Dictionary(routes.enumerated().map { ($0.element.id, $0.offset) }, uniquingKeysWith: { first, _ in first })
|
||||
return allGroups.filter { group in
|
||||
guard routeOrder[group.routeID] != nil else { return false }
|
||||
let day = calendar.startOfDay(for: group.capturedAt)
|
||||
guard day >= minimumDate, day <= maximumDate else { return false }
|
||||
if let selectedRouteID, group.routeID != selectedRouteID { return false }
|
||||
if let dateRange, day < dateRange.start || day > dateRange.end { return false }
|
||||
return true
|
||||
}.sorted { lhs, rhs in
|
||||
let left = routeOrder[lhs.routeID] ?? 0
|
||||
let right = routeOrder[rhs.routeID] ?? 0
|
||||
if left != right { return left < right }
|
||||
if lhs.capturedAt != rhs.capturedAt { return lhs.capturedAt > rhs.capturedAt }
|
||||
return lhs.id < rhs.id
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前筛选范围内完整片段,包含 UI 折叠的部分。
|
||||
var filteredClips: [ScenicMaterialClip] { filteredGroups.flatMap(\.clips) }
|
||||
/// 任何批次尚未清理时锁定选择与筛选,避免改变正在展示的批次范围。
|
||||
var isSelectionLocked: Bool { batchID != nil }
|
||||
/// 尚未开始传输且有可选片段时可以下载。
|
||||
var canStartDownload: Bool { !isSelectionLocked && !selectedIDs.isEmpty }
|
||||
/// 当前选择数量。
|
||||
var selectedCount: Int { selectedIDs.count }
|
||||
/// 当前批次总项数。
|
||||
var totalCount: Int { batchItemIDs.count }
|
||||
/// 当前批次成功演示项数,不混入此前批次结果。
|
||||
var completedCount: Int { batchItemIDs.filter { completedIDs.contains($0) }.count }
|
||||
/// 当前批次失败项数。
|
||||
var failedCount: Int { batchItemIDs.filter { failedIDs.contains($0) }.count }
|
||||
/// 当前批次仍待处理的完整片段标识。
|
||||
var pendingIDs: [String] { batchItemIDs.filter { !completedIDs.contains($0) && !failedIDs.contains($0) } }
|
||||
/// 按文件数量平均的演示进度,成功项始终计为 1。
|
||||
var downloadProgress: Double {
|
||||
guard !batchItemIDs.isEmpty else { return 0 }
|
||||
return batchItemIDs.reduce(0) { sum, id in
|
||||
sum + (completedIDs.contains(id) ? 1 : progressByID[id, default: 0])
|
||||
} / Double(batchItemIDs.count)
|
||||
}
|
||||
/// 当前航线筛选标题。
|
||||
var routeFilterTitle: String { selectedRouteID.flatMap { route(id: $0)?.name } ?? "全部航线" }
|
||||
/// 当前日期筛选标题。
|
||||
var dateFilterTitle: String {
|
||||
guard let dateRange else { return "全部时间" }
|
||||
let start = formatDate(dateRange.start, format: "MM.dd")
|
||||
let end = formatDate(dateRange.end, format: "MM.dd")
|
||||
return dateRange.start == dateRange.end ? start : "\(start) – \(end)"
|
||||
}
|
||||
/// 当前景区保留期内是否存在片段,不受用户筛选条件影响。
|
||||
var hasAnyMaterials: Bool {
|
||||
allGroups.contains { group in
|
||||
let day = calendar.startOfDay(for: group.capturedAt)
|
||||
return !group.clips.isEmpty && day >= minimumDate && day <= maximumDate
|
||||
&& routes.contains(where: { $0.id == group.routeID })
|
||||
}
|
||||
}
|
||||
/// 当前空态标题,区分全库为空与有筛选但无结果。
|
||||
var emptyTitle: String { hasAnyMaterials ? "没有符合条件的素材" : "暂无景区素材" }
|
||||
/// 当前空态说明。
|
||||
var emptyMessage: String {
|
||||
hasAnyMaterials ? "试试其他航线或时间范围" : "景区空镜上传后,将显示在这里"
|
||||
}
|
||||
|
||||
/// 查找稳定航线,不依赖名称。
|
||||
func route(id: String) -> ScenicMaterialRoute? { routes.first { $0.id == id } }
|
||||
/// 查找完整批次,不受折叠影响。
|
||||
func group(id: String) -> ScenicMaterialGroup? { allGroups.first { $0.id == id } }
|
||||
/// 查找当前库片段,不扩大页面上下文。
|
||||
func clip(id: String) -> ScenicMaterialClip? { allGroups.lazy.flatMap(\.clips).first { $0.id == id } }
|
||||
|
||||
/// 返回列表当前应显示的片段;默认显示首五段。
|
||||
func visibleClips(in group: ScenicMaterialGroup) -> [ScenicMaterialClip] {
|
||||
expandedGroupIDs.contains(group.id) ? group.clips : Array(group.clips.prefix(5))
|
||||
}
|
||||
|
||||
/// 格式化批次拍摄时间,使用同一日历时区。
|
||||
func capturedAtText(for group: ScenicMaterialGroup) -> String { formatDate(group.capturedAt, format: "MM-dd HH:mm") }
|
||||
|
||||
/// 切换航线后移除隐藏选择,传入未知航线不会更改现有状态。
|
||||
@discardableResult
|
||||
func setRoute(id: String?) -> Bool {
|
||||
guard !isSelectionLocked, id == nil || routes.contains(where: { $0.id == id }) else { return false }
|
||||
selectedRouteID = id
|
||||
pruneSelection()
|
||||
return true
|
||||
}
|
||||
|
||||
/// 应用包含首尾两天的范围;两端均 nil 表示全部,非法或越界日期保持原值。
|
||||
@discardableResult
|
||||
func setDateRange(start: Date?, end: Date?) -> Bool {
|
||||
guard !isSelectionLocked else { return false }
|
||||
if start == nil && end == nil {
|
||||
dateRange = nil
|
||||
pruneSelection()
|
||||
return true
|
||||
}
|
||||
guard let start, let end else { return false }
|
||||
let first = calendar.startOfDay(for: start)
|
||||
let last = calendar.startOfDay(for: end)
|
||||
guard first >= minimumDate, last <= maximumDate, first <= last else { return false }
|
||||
dateRange = ScenicMaterialDateRange(start: first, end: last)
|
||||
pruneSelection()
|
||||
return true
|
||||
}
|
||||
|
||||
/// 清除筛选,保留仍有效的已选片段,不改变下载结果。
|
||||
func resetFilters() {
|
||||
guard !isSelectionLocked else { return }
|
||||
selectedRouteID = nil
|
||||
dateRange = nil
|
||||
pruneSelection()
|
||||
}
|
||||
|
||||
/// 当前可选状态;完成、不可用、隐藏片段或锁定批次均不可新选。
|
||||
func canSelect(id: String) -> Bool {
|
||||
!isSelectionLocked && filteredClips.contains { $0.id == id && $0.isAvailable && !completedIDs.contains(id) }
|
||||
}
|
||||
|
||||
/// 切换单项选择,不涉及预览或下载。
|
||||
func toggleSelection(id: String) {
|
||||
guard canSelect(id: id) else { return }
|
||||
if !selectedIDs.insert(id).inserted { selectedIDs.remove(id) }
|
||||
}
|
||||
|
||||
/// 完整批次内所有可选片段是否都已选中,不把空组视为全选。
|
||||
func isGroupSelected(id: String) -> Bool {
|
||||
let ids = selectableIDs(in: id)
|
||||
return !ids.isEmpty && ids.isSubset(of: selectedIDs)
|
||||
}
|
||||
|
||||
/// 全选或取消全选本组;包含未展开片段,排除已完成与不可用项。
|
||||
func toggleGroup(id: String) {
|
||||
guard !isSelectionLocked else { return }
|
||||
let ids = selectableIDs(in: id)
|
||||
if !ids.isEmpty && ids.isSubset(of: selectedIDs) { selectedIDs.subtract(ids) }
|
||||
else { selectedIDs.formUnion(ids) }
|
||||
}
|
||||
|
||||
/// 展开/收起只改变布局,下载过程中也可浏览,不改变选择和批次。
|
||||
func toggleExpandedGroup(id: String) {
|
||||
guard filteredGroups.contains(where: { $0.id == id }) else { return }
|
||||
if !expandedGroupIDs.insert(id).inserted { expandedGroupIDs.remove(id) }
|
||||
}
|
||||
|
||||
/// 获取当前片段的本机展示状态;成功仅表示本地演示完成。
|
||||
func downloadState(for id: String) -> ScenicMaterialDownloadState {
|
||||
guard let clip = clip(id: id), clip.isAvailable else { return .unavailable }
|
||||
if completedIDs.contains(id) { return .completed }
|
||||
if failedIDs.contains(id) { return .failed }
|
||||
guard batchItemIDs.contains(id) else { return .available }
|
||||
if phase == .paused { return .paused }
|
||||
if phase == .downloading { return .downloading(progress: progressByID[id, default: 0]) }
|
||||
return .available
|
||||
}
|
||||
|
||||
/// 冻结当前可选范围并开启一轮下载演示,返回是否成功建立批次。
|
||||
@discardableResult
|
||||
func startDownload() -> Bool {
|
||||
guard !isSelectionLocked else { return false }
|
||||
let items = filteredClips.filter { selectedIDs.contains($0.id) && $0.isAvailable && !completedIDs.contains($0.id) }
|
||||
guard !items.isEmpty else { return false }
|
||||
batchItemIDs = items.map(\.id)
|
||||
selectedIDs = Set(batchItemIDs)
|
||||
failedIDs.removeAll()
|
||||
progressByID = Dictionary(uniqueKeysWithValues: batchItemIDs.map { ($0, 0) })
|
||||
batchID = UUID()
|
||||
phase = .downloading
|
||||
return true
|
||||
}
|
||||
|
||||
/// 暂停当前演示并作废旧驱动回执,回前台不自动继续。
|
||||
func pauseDownload() {
|
||||
guard phase == .downloading else { return }
|
||||
batchID = UUID()
|
||||
phase = .paused
|
||||
}
|
||||
|
||||
/// 手动继续未完成项,允许未完成文件从头演示,已完成项不重复处理。
|
||||
@discardableResult
|
||||
func continueDownload() -> Bool {
|
||||
guard phase == .paused, !pendingIDs.isEmpty else { return false }
|
||||
for id in pendingIDs { progressByID[id] = 0 }
|
||||
batchID = UUID()
|
||||
phase = .downloading
|
||||
return true
|
||||
}
|
||||
|
||||
/// 仅重新处理明确失败的项,成功项及原批次范围保留。
|
||||
@discardableResult
|
||||
func retryFailedDownloads() -> Bool {
|
||||
guard phase == .partialFailure, !failedIDs.isEmpty else { return false }
|
||||
for id in failedIDs { progressByID[id] = 0 }
|
||||
failedIDs.removeAll()
|
||||
batchID = UUID()
|
||||
phase = .downloading
|
||||
return true
|
||||
}
|
||||
|
||||
/// 取消当前批次并清理未完成项;已成功的本机演示标记继续保留。
|
||||
func cancelDownload() { clearBatch() }
|
||||
|
||||
/// 终态后开始重新选择;传输或暂停中的批次需先继续或取消。
|
||||
func continueSelecting() {
|
||||
guard phase != .downloading, phase != .paused else { return }
|
||||
clearBatch()
|
||||
}
|
||||
|
||||
/// 只接收当前传输令牌的未终结项,拒绝旧批次、重复终态及无效进度。
|
||||
func receive(_ event: ScenicMaterialTransferEvent, clipID: String, batchID: UUID) {
|
||||
guard self.batchID == batchID, phase == .downloading, batchItemIDs.contains(clipID),
|
||||
!completedIDs.contains(clipID), !failedIDs.contains(clipID), clip(id: clipID)?.isAvailable == true else { return }
|
||||
switch event {
|
||||
case .progress(let value):
|
||||
guard value.isFinite else { return }
|
||||
progressByID[clipID] = max(progressByID[clipID, default: 0], min(max(value, 0), 1))
|
||||
case .completed:
|
||||
completedIDs.insert(clipID)
|
||||
progressByID[clipID] = 1
|
||||
case .failed:
|
||||
failedIDs.insert(clipID)
|
||||
progressByID[clipID] = 0
|
||||
}
|
||||
guard pendingIDs.isEmpty else { return }
|
||||
phase = failedIDs.isEmpty ? .completed : .partialFailure
|
||||
selectedIDs = failedIDs
|
||||
}
|
||||
|
||||
/// 切换本地状态预览,不读取真实相册,也不更改登录身份或订单。
|
||||
func applyScenario(_ scenario: ScenicMaterialsScenario) {
|
||||
clearBatch()
|
||||
completedIDs.removeAll()
|
||||
allGroups = initialGroups
|
||||
selectedRouteID = nil
|
||||
dateRange = nil
|
||||
expandedGroupIDs.removeAll()
|
||||
switch scenario {
|
||||
case .normal: break
|
||||
case .empty: allGroups = []
|
||||
case .noResults:
|
||||
selectedRouteID = routes.first(where: { route in !allGroups.contains(where: { $0.routeID == route.id }) })?.id
|
||||
if selectedRouteID == nil {
|
||||
dateRange = ScenicMaterialDateRange(start: maximumDate, end: maximumDate)
|
||||
}
|
||||
case .selected, .downloading, .completed, .partialFailure, .paused:
|
||||
let items = Array(filteredClips.filter(\.isAvailable).prefix(2))
|
||||
selectedIDs = Set(items.map(\.id))
|
||||
guard scenario != .selected, startDownload(), let token = batchID else { return }
|
||||
if scenario == .downloading {
|
||||
if let item = items.first { receive(.progress(0.35), clipID: item.id, batchID: token) }
|
||||
} else if scenario == .completed {
|
||||
for item in items { receive(.completed, clipID: item.id, batchID: token) }
|
||||
} else if scenario == .partialFailure {
|
||||
for (index, item) in items.enumerated() {
|
||||
receive(index == 0 ? .completed : .failed, clipID: item.id, batchID: token)
|
||||
}
|
||||
} else {
|
||||
if let item = items.first, items.count > 1 { receive(.completed, clipID: item.id, batchID: token) }
|
||||
pauseDownload()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func selectableIDs(in groupID: String) -> Set<String> {
|
||||
guard let group = filteredGroups.first(where: { $0.id == groupID }) else { return [] }
|
||||
return Set(group.clips.filter { $0.isAvailable && !completedIDs.contains($0.id) }.map(\.id))
|
||||
}
|
||||
|
||||
private func pruneSelection() {
|
||||
let valid = Set(filteredClips.filter { $0.isAvailable && !completedIDs.contains($0.id) }.map(\.id))
|
||||
selectedIDs.formIntersection(valid)
|
||||
}
|
||||
|
||||
private func clearBatch() {
|
||||
batchID = nil
|
||||
batchItemIDs = []
|
||||
selectedIDs.removeAll()
|
||||
failedIDs.removeAll()
|
||||
progressByID.removeAll()
|
||||
phase = .idle
|
||||
}
|
||||
|
||||
private func formatDate(_ date: Date, format: String) -> String {
|
||||
let formatter = DateFormatter()
|
||||
formatter.calendar = calendar
|
||||
formatter.timeZone = calendar.timeZone
|
||||
formatter.locale = Locale(identifier: "zh_CN")
|
||||
formatter.dateFormat = format
|
||||
return formatter.string(from: date)
|
||||
}
|
||||
|
||||
private static func makeRoutes(context: ScenicMaterialContext) -> [ScenicMaterialRoute] {
|
||||
let prefix = "\(context.userID):\(context.scenicID)"
|
||||
return [
|
||||
ScenicMaterialRoute(id: "\(prefix):route-1", name: "共眠岸 → 三皇寨 → 好汉坡"),
|
||||
ScenicMaterialRoute(id: "\(prefix):route-2", name: "少林寺 → 塔林 → 达摩洞"),
|
||||
ScenicMaterialRoute(id: "\(prefix):route-3", name: "少室山 → 迎客峰")
|
||||
]
|
||||
}
|
||||
|
||||
private static func makeGroups(context: ScenicMaterialContext, routes: [ScenicMaterialRoute], today: Date,
|
||||
calendar: Calendar) -> [ScenicMaterialGroup] {
|
||||
let prefix = "\(context.userID):\(context.scenicID)"
|
||||
let configurations = [(0, 3, 17, 20, 5), (0, 3, 14, 30, 6), (0, 4, 16, 10, 3), (1, 3, 10, 40, 4), (1, 16, 15, 35, 5)]
|
||||
let durations = [28, 27, 30, 24, 31, 26]
|
||||
let covers = ["drone_demo_mountain", "drone_demo_pagoda", "drone_demo_mountain", "drone_demo_pagoda", "drone_demo_mountain", "drone_demo_pagoda"]
|
||||
return configurations.enumerated().map { index, configuration in
|
||||
let (routeIndex, daysAgo, hour, minute, count) = configuration
|
||||
let day = calendar.date(byAdding: .day, value: -daysAgo, to: today) ?? today
|
||||
let capturedAt = calendar.date(bySettingHour: hour, minute: minute, second: 0, of: day) ?? day
|
||||
let groupID = "\(prefix):group-\(index + 1)"
|
||||
let clips = (0..<count).map { clipIndex in
|
||||
ScenicMaterialClip(id: "\(groupID):clip-\(clipIndex + 1)", groupID: groupID, ordinal: clipIndex + 1,
|
||||
durationSeconds: durations[clipIndex], fileSizeBytes: Int64(178 + clipIndex * 12) * 1_000_000,
|
||||
resolution: "4K", coverAssetName: covers[clipIndex])
|
||||
}
|
||||
return ScenicMaterialGroup(id: groupID, routeID: routes[routeIndex].id, capturedAt: capturedAt, clips: clips)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
|
||||
self.window = window
|
||||
(UIApplication.shared.delegate as? AppDelegate)?.window = window
|
||||
#if DEBUG
|
||||
if let preview = DroneDockPreview.navigationController(arguments: ProcessInfo.processInfo.arguments) {
|
||||
if let preview = ScenicMaterialsPreview.navigationController(arguments: ProcessInfo.processInfo.arguments)
|
||||
?? DroneDockPreview.navigationController(arguments: ProcessInfo.processInfo.arguments) {
|
||||
window.rootViewController = preview
|
||||
window.makeKeyAndVisible()
|
||||
return
|
||||
|
||||
@@ -59,9 +59,10 @@ final class AllFunctionsViewController: BaseViewController {
|
||||
override func setupNavigationBar() {
|
||||
title = "全部功能"
|
||||
#if DEBUG
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(
|
||||
title: "机巢预览", style: .plain, target: self, action: #selector(openDroneDockPreview)
|
||||
)
|
||||
navigationItem.rightBarButtonItems = [
|
||||
UIBarButtonItem(title: "空镜预览", style: .plain, target: self, action: #selector(openScenicMaterialsPreview)),
|
||||
UIBarButtonItem(title: "机巢预览", style: .plain, target: self, action: #selector(openDroneDockPreview))
|
||||
]
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -69,6 +70,11 @@ final class AllFunctionsViewController: BaseViewController {
|
||||
@objc private func openDroneDockPreview() {
|
||||
navigationController?.pushViewController(DroneDockWorkbenchViewController(), animated: true)
|
||||
}
|
||||
|
||||
/// 空镜库作为独立模块预览,不经机巢工作台导航或业务状态。
|
||||
@objc private func openScenicMaterialsPreview() {
|
||||
navigationController?.pushViewController(ScenicMaterialsViewController(), animated: true)
|
||||
}
|
||||
#endif
|
||||
|
||||
override func setupUI() {
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 景区素材模块的局部样式,可独立于机巢业务使用。
|
||||
@MainActor
|
||||
enum ScenicMaterialsStyle {
|
||||
static let primary = UIColor(hex: 0x3164FF)
|
||||
static let background = UIColor.white
|
||||
static let text = UIColor(hex: 0x20242C)
|
||||
static let secondary = UIColor(hex: 0x9297A1)
|
||||
static let border = UIColor(hex: 0xECEEF2)
|
||||
static let success = UIColor(hex: 0x17986A)
|
||||
static let warning = UIColor(hex: 0xD98926)
|
||||
|
||||
/// 创建模块内使用的系统字体标签。
|
||||
static func label(_ text: String? = nil, size: CGFloat = 14, weight: UIFont.Weight = .regular,
|
||||
color: UIColor? = nil) -> UILabel {
|
||||
let label = UILabel()
|
||||
label.text = text
|
||||
label.font = .systemFont(ofSize: size, weight: weight)
|
||||
label.textColor = color ?? ScenicMaterialsStyle.text
|
||||
return label
|
||||
}
|
||||
}
|
||||
|
||||
/// 视频封面底部渐变,只用于保证白色元信息在照片上的对比度。
|
||||
@MainActor
|
||||
private final class ScenicMaterialGradientView: UIView {
|
||||
override class var layerClass: AnyClass { CAGradientLayer.self }
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
isUserInteractionEnabled = false
|
||||
if let gradient = layer as? CAGradientLayer {
|
||||
gradient.colors = [UIColor.clear.cgColor, UIColor.black.withAlphaComponent(0.68).cgColor]
|
||||
gradient.locations = [0, 1]
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
}
|
||||
|
||||
/// 景区空镜片段卡,预览和选择分别命中,下载期间仍可预览。
|
||||
@MainActor
|
||||
final class ScenicMaterialClipCell: UICollectionViewCell {
|
||||
/// 请求预览当前片段,不改变选择状态。
|
||||
var onPreview: (() -> Void)?
|
||||
/// 请求切换当前片段的勾选状态。
|
||||
var onToggleSelection: (() -> Void)?
|
||||
|
||||
private let cover = UIImageView()
|
||||
private let previewButton = UIButton(type: .custom)
|
||||
private let selectionButton = UIButton(type: .custom)
|
||||
private let ordinalLabel = ScenicMaterialsStyle.label(size: 11, color: .white)
|
||||
private let metadataLabel = ScenicMaterialsStyle.label(size: 11, color: .white)
|
||||
private let statusLabel = ScenicMaterialsStyle.label(size: 10, weight: .medium, color: .white)
|
||||
private let progressView = UIProgressView(progressViewStyle: .bar)
|
||||
|
||||
/// 创建圆角图片卡和独立的四十四点选择命中区。
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
setupUI()
|
||||
setupConstraints()
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func prepareForReuse() {
|
||||
super.prepareForReuse()
|
||||
onPreview = nil
|
||||
onToggleSelection = nil
|
||||
cover.image = nil
|
||||
progressView.isHidden = true
|
||||
statusLabel.isHidden = true
|
||||
}
|
||||
|
||||
/// 显示片段及本机演示传输状态;首段大图额外显示分辨率和体积。
|
||||
func configure(clip: ScenicMaterialClip, selected: Bool, isSelectionEnabled: Bool,
|
||||
statusText: String? = nil, progress: Double? = nil, isHero: Bool = false) {
|
||||
cover.image = UIImage(named: clip.coverAssetName)
|
||||
ordinalLabel.text = String(format: "片段 %02d", clip.ordinal)
|
||||
metadataLabel.text = isHero ? "\(clip.durationText) · \(clip.resolution) · \(clip.sizeText)" : clip.durationText
|
||||
metadataLabel.font = .monospacedDigitSystemFont(ofSize: isHero ? 11 : 10, weight: .regular)
|
||||
selectionButton.setImage(UIImage(systemName: selected ? "checkmark.circle.fill" : "circle",
|
||||
withConfiguration: UIImage.SymbolConfiguration(pointSize: 22, weight: .regular)), for: .normal)
|
||||
selectionButton.tintColor = selected ? ScenicMaterialsStyle.primary : .white
|
||||
selectionButton.isEnabled = isSelectionEnabled
|
||||
selectionButton.alpha = isSelectionEnabled ? 1 : 0.45
|
||||
selectionButton.accessibilityIdentifier = "scenic.materials.select.\(clip.id)"
|
||||
selectionButton.accessibilityLabel = "\(selected ? "取消选择" : "选择")片段\(clip.ordinal)"
|
||||
selectionButton.accessibilityTraits = selected ? [.button, .selected] : .button
|
||||
if !isSelectionEnabled { selectionButton.accessibilityTraits.insert(.notEnabled) }
|
||||
previewButton.accessibilityIdentifier = "scenic.materials.preview.\(clip.id)"
|
||||
previewButton.accessibilityLabel = "预览片段\(clip.ordinal),\(clip.durationText)"
|
||||
previewButton.isEnabled = clip.isAvailable
|
||||
statusLabel.text = statusText.map { " \($0) " }
|
||||
statusLabel.isHidden = statusText == nil
|
||||
statusLabel.backgroundColor = statusText?.contains("失败") == true
|
||||
? ScenicMaterialsStyle.warning.withAlphaComponent(0.95)
|
||||
: ScenicMaterialsStyle.primary.withAlphaComponent(0.88)
|
||||
progressView.isHidden = progress == nil
|
||||
progressView.progress = Float(min(max(progress ?? 0, 0), 1))
|
||||
accessibilityIdentifier = "scenic.materials.clip.\(clip.id)"
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
contentView.backgroundColor = UIColor(hex: 0xE9EDF4)
|
||||
contentView.layer.cornerRadius = 10
|
||||
contentView.layer.cornerCurve = .continuous
|
||||
contentView.clipsToBounds = true
|
||||
cover.contentMode = .scaleAspectFill
|
||||
cover.clipsToBounds = true
|
||||
previewButton.setImage(UIImage(systemName: "play.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 24)), for: .normal)
|
||||
previewButton.tintColor = .white
|
||||
previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside)
|
||||
selectionButton.addTarget(self, action: #selector(selectionTapped), for: .touchUpInside)
|
||||
statusLabel.layer.cornerRadius = 5
|
||||
statusLabel.clipsToBounds = true
|
||||
statusLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||
ordinalLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||
metadataLabel.textAlignment = .right
|
||||
metadataLabel.minimumScaleFactor = 0.85
|
||||
metadataLabel.adjustsFontSizeToFitWidth = true
|
||||
progressView.progressTintColor = ScenicMaterialsStyle.primary
|
||||
progressView.trackTintColor = .white.withAlphaComponent(0.4)
|
||||
let gradient = ScenicMaterialGradientView()
|
||||
gradient.tag = 701
|
||||
[cover, previewButton, gradient, ordinalLabel, metadataLabel, statusLabel, selectionButton, progressView].forEach(contentView.addSubview)
|
||||
}
|
||||
|
||||
private func setupConstraints() {
|
||||
cover.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
previewButton.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
contentView.viewWithTag(701)?.snp.makeConstraints {
|
||||
$0.leading.trailing.bottom.equalToSuperview()
|
||||
$0.height.equalTo(55)
|
||||
}
|
||||
selectionButton.snp.makeConstraints { $0.top.leading.equalToSuperview(); $0.size.equalTo(44) }
|
||||
statusLabel.snp.makeConstraints {
|
||||
$0.top.trailing.equalToSuperview().inset(9)
|
||||
$0.leading.greaterThanOrEqualTo(selectionButton.snp.trailing).offset(2)
|
||||
$0.height.equalTo(22)
|
||||
}
|
||||
ordinalLabel.snp.makeConstraints { $0.leading.bottom.equalToSuperview().inset(9) }
|
||||
metadataLabel.snp.makeConstraints {
|
||||
$0.trailing.bottom.equalToSuperview().inset(9)
|
||||
$0.leading.greaterThanOrEqualTo(ordinalLabel.snp.trailing).offset(5)
|
||||
}
|
||||
progressView.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview(); $0.height.equalTo(3) }
|
||||
}
|
||||
|
||||
@objc private func previewTapped() { onPreview?() }
|
||||
@objc private func selectionTapped() { onToggleSelection?() }
|
||||
}
|
||||
|
||||
/// 航线与拍摄批次标题,整组勾选由 ViewModel 决定完整片段范围。
|
||||
@MainActor
|
||||
final class ScenicMaterialGroupHeaderView: UICollectionReusableView {
|
||||
/// 请求勾选或取消本组全部可选片段。
|
||||
var onToggleGroup: (() -> Void)?
|
||||
private let routeLabel = ScenicMaterialsStyle.label(size: 17, weight: .semibold)
|
||||
private let timeLabel = ScenicMaterialsStyle.label(size: 11, color: ScenicMaterialsStyle.secondary)
|
||||
private let groupButton = UIButton(type: .system)
|
||||
|
||||
/// 创建可复用的航线标题和批次选择行。
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
routeLabel.numberOfLines = 2
|
||||
routeLabel.accessibilityTraits = .header
|
||||
timeLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
|
||||
groupButton.addTarget(self, action: #selector(groupTapped), for: .touchUpInside)
|
||||
addSubview(routeLabel)
|
||||
addSubview(timeLabel)
|
||||
addSubview(groupButton)
|
||||
routeLabel.snp.makeConstraints {
|
||||
$0.leading.trailing.equalToSuperview()
|
||||
$0.top.equalToSuperview().offset(10)
|
||||
$0.bottom.lessThanOrEqualTo(groupButton.snp.top).offset(-4)
|
||||
}
|
||||
timeLabel.snp.makeConstraints {
|
||||
$0.leading.equalToSuperview()
|
||||
$0.centerY.equalTo(groupButton)
|
||||
$0.trailing.lessThanOrEqualTo(groupButton.snp.leading).offset(-6)
|
||||
}
|
||||
groupButton.snp.makeConstraints {
|
||||
$0.trailing.equalToSuperview()
|
||||
$0.bottom.equalToSuperview()
|
||||
$0.height.equalTo(44)
|
||||
$0.width.greaterThanOrEqualTo(88)
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func prepareForReuse() { super.prepareForReuse(); onToggleGroup = nil }
|
||||
|
||||
/// 首组显示航线标题,后续同航线批次仅显示时间和数量。
|
||||
func configure(groupID: String, routeName: String?, timeTitle: String, count: Int,
|
||||
isSelected: Bool, canSelect: Bool) {
|
||||
routeLabel.text = routeName
|
||||
routeLabel.isHidden = routeName == nil
|
||||
routeLabel.snp.remakeConstraints {
|
||||
$0.leading.trailing.equalToSuperview()
|
||||
if routeName == nil {
|
||||
$0.top.equalToSuperview()
|
||||
$0.height.equalTo(0)
|
||||
} else {
|
||||
$0.top.equalToSuperview().offset(10)
|
||||
$0.bottom.lessThanOrEqualTo(groupButton.snp.top).offset(-4)
|
||||
}
|
||||
}
|
||||
timeLabel.text = "\(timeTitle) · \(count) 段素材"
|
||||
var configuration = UIButton.Configuration.plain()
|
||||
configuration.title = "选择本组"
|
||||
configuration.image = UIImage(systemName: isSelected ? "checkmark.circle.fill" : "circle")
|
||||
configuration.imagePadding = 5
|
||||
configuration.contentInsets = .zero
|
||||
configuration.baseForegroundColor = isSelected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.secondary
|
||||
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 16)
|
||||
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { input in
|
||||
var output = input
|
||||
output.font = .systemFont(ofSize: 11)
|
||||
return output
|
||||
}
|
||||
groupButton.configuration = configuration
|
||||
groupButton.isEnabled = canSelect
|
||||
groupButton.accessibilityIdentifier = "scenic.materials.group.\(groupID)"
|
||||
groupButton.accessibilityLabel = "\(isSelected ? "取消选择本组" : "选择本组"),\(timeTitle),\(count)段"
|
||||
groupButton.accessibilityTraits = isSelected ? [.button, .selected] : .button
|
||||
if !canSelect { groupButton.accessibilityTraits.insert(.notEnabled) }
|
||||
}
|
||||
|
||||
@objc private func groupTapped() { onToggleGroup?() }
|
||||
}
|
||||
|
||||
/// 展开或收起同一拍摄批次中默认折叠的片段。
|
||||
@MainActor
|
||||
final class ScenicMaterialExpandCell: UICollectionViewCell {
|
||||
/// 切换本组片段展示范围,选择范围不随折叠改变。
|
||||
var onToggleExpanded: (() -> Void)?
|
||||
private let button = UIButton(type: .system)
|
||||
|
||||
/// 创建居中的轻量展开按钮。
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
button.tintColor = ScenicMaterialsStyle.secondary
|
||||
button.titleLabel?.font = .systemFont(ofSize: 12)
|
||||
button.addTarget(self, action: #selector(tapped), for: .touchUpInside)
|
||||
contentView.addSubview(button)
|
||||
button.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func prepareForReuse() { super.prepareForReuse(); onToggleExpanded = nil }
|
||||
|
||||
/// 显示展开余量或收起文案。
|
||||
func configure(groupID: String, title: String) {
|
||||
button.setTitle(title, for: .normal)
|
||||
button.setImage(UIImage(systemName: title.contains("收起") ? "chevron.up" : "chevron.down"), for: .normal)
|
||||
button.semanticContentAttribute = .forceRightToLeft
|
||||
button.accessibilityIdentifier = "scenic.materials.expand.\(groupID)"
|
||||
}
|
||||
|
||||
@objc private func tapped() { onToggleExpanded?() }
|
||||
}
|
||||
|
||||
/// 固定底部的选择/下载摘要,不直接持有 ViewModel 或执行文件操作。
|
||||
@MainActor
|
||||
final class ScenicMaterialsFooterView: UIView {
|
||||
/// 当前阶段的主要操作,例如下载、继续或重试。
|
||||
var onPrimaryTap: (() -> Void)?
|
||||
/// 当前阶段的次要操作,例如取消或继续选择。
|
||||
var onSecondaryTap: (() -> Void)?
|
||||
private let titleLabel = ScenicMaterialsStyle.label(size: 14, weight: .medium)
|
||||
private let detailLabel = ScenicMaterialsStyle.label(size: 10, color: ScenicMaterialsStyle.secondary)
|
||||
private let primaryButton = UIButton(type: .custom)
|
||||
private let secondaryButton = UIButton(type: .custom)
|
||||
private let progressView = UIProgressView(progressViewStyle: .bar)
|
||||
|
||||
/// 创建随安全区延伸的白色底栏。
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
backgroundColor = .white
|
||||
titleLabel.numberOfLines = 2
|
||||
detailLabel.numberOfLines = 2
|
||||
primaryButton.titleLabel?.font = .systemFont(ofSize: 14, weight: .semibold)
|
||||
primaryButton.titleLabel?.numberOfLines = 2
|
||||
primaryButton.titleLabel?.textAlignment = .center
|
||||
primaryButton.setTitleColor(.white, for: .normal)
|
||||
primaryButton.setTitleColor(.white, for: .disabled)
|
||||
primaryButton.layer.cornerRadius = 10
|
||||
primaryButton.clipsToBounds = true
|
||||
primaryButton.accessibilityIdentifier = "scenic.materials.primary"
|
||||
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
|
||||
secondaryButton.tintColor = ScenicMaterialsStyle.primary
|
||||
secondaryButton.setTitleColor(ScenicMaterialsStyle.primary, for: .normal)
|
||||
secondaryButton.titleLabel?.font = .systemFont(ofSize: 13)
|
||||
secondaryButton.accessibilityIdentifier = "scenic.materials.secondary"
|
||||
secondaryButton.addTarget(self, action: #selector(secondaryTapped), for: .touchUpInside)
|
||||
progressView.progressTintColor = ScenicMaterialsStyle.primary
|
||||
progressView.trackTintColor = ScenicMaterialsStyle.border
|
||||
let labels = UIStackView(arrangedSubviews: [titleLabel, detailLabel])
|
||||
labels.axis = .vertical
|
||||
labels.spacing = 5
|
||||
let row = UIStackView(arrangedSubviews: [labels, primaryButton])
|
||||
row.axis = .horizontal
|
||||
row.spacing = 12
|
||||
row.alignment = .center
|
||||
let stack = UIStackView(arrangedSubviews: [row, progressView, secondaryButton])
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 10
|
||||
let separator = UIView()
|
||||
separator.backgroundColor = ScenicMaterialsStyle.border
|
||||
addSubview(separator)
|
||||
addSubview(stack)
|
||||
separator.snp.makeConstraints { $0.top.leading.trailing.equalToSuperview(); $0.height.equalTo(0.5) }
|
||||
stack.snp.makeConstraints {
|
||||
$0.top.equalToSuperview().offset(14)
|
||||
$0.leading.trailing.equalToSuperview().inset(20)
|
||||
$0.bottom.equalTo(safeAreaLayoutGuide).inset(12)
|
||||
}
|
||||
primaryButton.snp.makeConstraints { $0.width.equalTo(158); $0.height.equalTo(46) }
|
||||
progressView.snp.makeConstraints { $0.height.equalTo(3).priority(999) }
|
||||
secondaryButton.snp.makeConstraints { $0.height.equalTo(32).priority(999) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 由当前页面状态显式刷新底栏,始终保留禁用按钮的可读标题。
|
||||
func configure(title: String, detail: String?, primaryTitle: String, primaryEnabled: Bool,
|
||||
secondaryTitle: String? = nil, progress: Float? = nil) {
|
||||
UIView.performWithoutAnimation {
|
||||
titleLabel.text = title
|
||||
detailLabel.text = detail
|
||||
detailLabel.isHidden = detail == nil
|
||||
if primaryButton.title(for: .normal) != primaryTitle {
|
||||
primaryButton.setTitle(primaryTitle, for: .normal)
|
||||
primaryButton.setTitle(primaryTitle, for: .disabled)
|
||||
}
|
||||
primaryButton.backgroundColor = primaryEnabled ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.primary.withAlphaComponent(0.25)
|
||||
primaryButton.isEnabled = primaryEnabled
|
||||
if secondaryButton.title(for: .normal) != secondaryTitle {
|
||||
secondaryButton.setTitle(secondaryTitle, for: .normal)
|
||||
}
|
||||
secondaryButton.isHidden = secondaryTitle == nil
|
||||
progressView.isHidden = progress == nil
|
||||
progressView.progress = min(max(progress ?? 0, 0), 1)
|
||||
layoutIfNeeded()
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func primaryTapped() { onPrimaryTap?() }
|
||||
@objc private func secondaryTapped() { onSecondaryTap?() }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import Foundation
|
||||
|
||||
/// 推进空镜库本地下载演示,不发起网络请求,也不写入文件或系统相册。
|
||||
@MainActor
|
||||
final class ScenicMaterialDemoDownloadDriver {
|
||||
private var task: Task<Void, Never>?
|
||||
private var activeBatchID: UUID?
|
||||
|
||||
/// 只推进当前批次的未完成项,旧批次回执由 ViewModel 再次校验。
|
||||
func start(viewModel: ScenicMaterialsViewModel, onProgress: @escaping () -> Void) {
|
||||
guard viewModel.phase == .downloading, let batchID = viewModel.batchID else { return }
|
||||
guard activeBatchID != batchID || task == nil else { return }
|
||||
stop()
|
||||
activeBatchID = batchID
|
||||
let itemIDs = viewModel.pendingIDs
|
||||
task = Task { @MainActor [weak self, weak viewModel] in
|
||||
guard let self, let viewModel else { return }
|
||||
defer {
|
||||
if self.activeBatchID == batchID {
|
||||
self.task = nil
|
||||
self.activeBatchID = nil
|
||||
}
|
||||
}
|
||||
for id in itemIDs where !viewModel.completedIDs.contains(id) {
|
||||
for progress in [0.2, 0.45, 0.7, 0.95] {
|
||||
do { try await Task.sleep(nanoseconds: 200_000_000) } catch { return }
|
||||
guard !Task.isCancelled, self.activeBatchID == batchID,
|
||||
viewModel.batchID == batchID, viewModel.phase == .downloading else { return }
|
||||
viewModel.receive(.progress(progress), clipID: id, batchID: batchID)
|
||||
onProgress()
|
||||
}
|
||||
viewModel.receive(.completed, clipID: id, batchID: batchID)
|
||||
onProgress()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 停止演示计时;调用方另行暂停或取消批次,避免把取消计时视为下载成功。
|
||||
func stop() {
|
||||
task?.cancel()
|
||||
task = nil
|
||||
activeBatchID = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 独立景区素材航线筛选 Sheet,选择即应用,不要求加载工作台。
|
||||
@MainActor
|
||||
final class ScenicMaterialRouteFilterViewController: UIViewController, UITableViewDelegate {
|
||||
/// 选择全部传 nil,选择具体航线传稳定 ID。
|
||||
var onSelectRoute: ((String?) -> Void)?
|
||||
|
||||
/// 筛选行使用明确身份,避免“全部”与业务航线 ID 冲突。
|
||||
private enum Row: Hashable { case all, route(String) }
|
||||
private let routes: [ScenicMaterialRoute]
|
||||
private let selectedRouteID: String?
|
||||
private let tableView = UITableView(frame: .zero, style: .plain)
|
||||
private var dataSource: UITableViewDiffableDataSource<Int, Row>!
|
||||
|
||||
/// 使用当前筛选快照创建独立选择面板。
|
||||
init(routes: [ScenicMaterialRoute], selectedRouteID: String?) {
|
||||
var identifiers = Set<String>()
|
||||
self.routes = routes.filter { identifiers.insert($0.id).inserted }
|
||||
self.selectedRouteID = selectedRouteID
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
modalPresentationStyle = .pageSheet
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
setupUI()
|
||||
let desiredHeight = min(CGFloat(routes.count + 1) * 58 + 90, 460)
|
||||
sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, desiredHeight) }]
|
||||
sheetPresentationController?.prefersGrabberVisible = true
|
||||
sheetPresentationController?.preferredCornerRadius = 24
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
view.backgroundColor = .white
|
||||
view.accessibilityIdentifier = "scenic.materials.route.sheet"
|
||||
let title = ScenicMaterialsStyle.label("选择航线", size: 19, weight: .semibold)
|
||||
let close = UIButton(type: .system)
|
||||
close.setImage(UIImage(systemName: "xmark"), for: .normal)
|
||||
close.tintColor = ScenicMaterialsStyle.secondary
|
||||
close.accessibilityLabel = "关闭航线筛选"
|
||||
close.accessibilityIdentifier = "scenic.materials.route.close"
|
||||
close.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
|
||||
tableView.backgroundColor = .white
|
||||
tableView.separatorStyle = .none
|
||||
tableView.rowHeight = 58
|
||||
tableView.delegate = self
|
||||
tableView.accessibilityIdentifier = "scenic.materials.route.list"
|
||||
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "route")
|
||||
[title, close, tableView].forEach(view.addSubview)
|
||||
title.snp.makeConstraints { $0.top.equalTo(view.safeAreaLayoutGuide).offset(20); $0.leading.equalToSuperview().offset(22) }
|
||||
close.snp.makeConstraints { $0.trailing.equalToSuperview().inset(10); $0.centerY.equalTo(title); $0.size.equalTo(44) }
|
||||
tableView.snp.makeConstraints {
|
||||
$0.top.equalTo(title.snp.bottom).offset(14)
|
||||
$0.leading.trailing.equalToSuperview().inset(8)
|
||||
$0.bottom.equalTo(view.safeAreaLayoutGuide)
|
||||
}
|
||||
dataSource = UITableViewDiffableDataSource<Int, Row>(tableView: tableView) { [weak self] table, indexPath, row in
|
||||
guard let self else { return nil }
|
||||
let cell = table.dequeueReusableCell(withIdentifier: "route", for: indexPath)
|
||||
let id: String?
|
||||
let name: String
|
||||
switch row {
|
||||
case .all: id = nil; name = "全部航线"
|
||||
case let .route(routeID):
|
||||
id = routeID
|
||||
name = self.routes.first { $0.id == routeID }?.name ?? "航线暂不可用"
|
||||
}
|
||||
let selected = id == self.selectedRouteID
|
||||
cell.textLabel?.text = name
|
||||
cell.textLabel?.font = .systemFont(ofSize: 15, weight: selected ? .medium : .regular)
|
||||
cell.textLabel?.textColor = selected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.text
|
||||
cell.backgroundColor = .white
|
||||
let image = UIImageView(image: UIImage(systemName: selected ? "checkmark.circle.fill" : "circle",
|
||||
withConfiguration: UIImage.SymbolConfiguration(pointSize: 22)))
|
||||
image.tintColor = selected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.border
|
||||
image.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
|
||||
cell.accessoryView = image
|
||||
cell.accessibilityIdentifier = "scenic.materials.route.\(id ?? "all")"
|
||||
cell.accessibilityTraits = selected ? [.button, .selected] : .button
|
||||
return cell
|
||||
}
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, Row>()
|
||||
snapshot.appendSections([0])
|
||||
snapshot.appendItems([.all] + routes.map { .route($0.id) })
|
||||
dataSource.apply(snapshot, animatingDifferences: false)
|
||||
}
|
||||
|
||||
/// 将选中航线提交给调用页,再关闭筛选面板。
|
||||
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
|
||||
guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
|
||||
let id: String?
|
||||
switch item { case .all: id = nil; case let .route(routeID): id = routeID }
|
||||
let completion = onSelectRoute
|
||||
dismiss(animated: true) { completion?(id) }
|
||||
}
|
||||
|
||||
@objc private func closeTapped() { dismiss(animated: true) }
|
||||
}
|
||||
|
||||
/// 景区素材起止日期筛选 Sheet,临时选择只在点击确定后应用。
|
||||
@MainActor
|
||||
final class ScenicMaterialDateFilterViewController: UIViewController {
|
||||
/// nil/nil 表示保留期内的全部时间,其他值为按日包含端点的区间。
|
||||
var onSelectRange: ((Date?, Date?) -> Void)?
|
||||
|
||||
/// 当前正在编辑的日期端点。
|
||||
private enum Endpoint: Equatable { case start, end }
|
||||
private let minimumDate: Date
|
||||
private let maximumDate: Date
|
||||
private let calendar: Calendar
|
||||
private var startDate: Date
|
||||
private var endDate: Date
|
||||
private var usesAllDates: Bool
|
||||
private var endpoint: Endpoint = .start
|
||||
private let allButton = UIButton(type: .system)
|
||||
private let startButton = UIButton(type: .custom)
|
||||
private let endButton = UIButton(type: .custom)
|
||||
private let picker = UIDatePicker()
|
||||
|
||||
/// 约束到服务端约定或演示给定的保留区间,不提供未来日期。
|
||||
init(start: Date?, end: Date?, minimumDate: Date, maximumDate: Date, calendar: Calendar = .current) {
|
||||
self.calendar = calendar
|
||||
self.minimumDate = calendar.startOfDay(for: minimumDate)
|
||||
self.maximumDate = max(calendar.startOfDay(for: minimumDate), calendar.startOfDay(for: maximumDate))
|
||||
let clampedStart = min(max(calendar.startOfDay(for: start ?? maximumDate), self.minimumDate), self.maximumDate)
|
||||
let clampedEnd = min(max(calendar.startOfDay(for: end ?? maximumDate), self.minimumDate), self.maximumDate)
|
||||
self.startDate = min(clampedStart, clampedEnd)
|
||||
self.endDate = max(clampedStart, clampedEnd)
|
||||
usesAllDates = start == nil && end == nil
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
modalPresentationStyle = .pageSheet
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
setupUI()
|
||||
updateUI()
|
||||
sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, 530) }]
|
||||
sheetPresentationController?.prefersGrabberVisible = true
|
||||
sheetPresentationController?.preferredCornerRadius = 24
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
view.backgroundColor = .white
|
||||
view.accessibilityIdentifier = "scenic.materials.date.sheet"
|
||||
let title = ScenicMaterialsStyle.label("选择时间", size: 19, weight: .semibold)
|
||||
let hint = ScenicMaterialsStyle.label("选择起止日期", size: 13, color: ScenicMaterialsStyle.secondary)
|
||||
allButton.addTarget(self, action: #selector(allTapped), for: .touchUpInside)
|
||||
allButton.accessibilityIdentifier = "scenic.materials.date.all"
|
||||
startButton.addTarget(self, action: #selector(startTapped), for: .touchUpInside)
|
||||
startButton.accessibilityIdentifier = "scenic.materials.date.start"
|
||||
endButton.addTarget(self, action: #selector(endTapped), for: .touchUpInside)
|
||||
endButton.accessibilityIdentifier = "scenic.materials.date.end"
|
||||
[startButton, endButton].forEach {
|
||||
$0.layer.cornerRadius = 10
|
||||
$0.layer.borderWidth = 1
|
||||
}
|
||||
let dateRow = UIStackView(arrangedSubviews: [startButton, endButton])
|
||||
dateRow.distribution = .fillEqually
|
||||
dateRow.spacing = 12
|
||||
picker.datePickerMode = .date
|
||||
picker.preferredDatePickerStyle = .wheels
|
||||
picker.locale = Locale(identifier: "zh_CN")
|
||||
picker.calendar = calendar
|
||||
picker.timeZone = calendar.timeZone
|
||||
picker.minimumDate = minimumDate
|
||||
picker.maximumDate = maximumDate
|
||||
picker.accessibilityIdentifier = "scenic.materials.date.picker"
|
||||
picker.addTarget(self, action: #selector(dateChanged), for: .valueChanged)
|
||||
let retention = ScenicMaterialsStyle.label("仅显示保留期内已到来的日期", size: 11, color: ScenicMaterialsStyle.secondary)
|
||||
retention.textAlignment = .center
|
||||
let cancel = UIButton(type: .system)
|
||||
cancel.setTitle("取消", for: .normal)
|
||||
cancel.tintColor = ScenicMaterialsStyle.secondary
|
||||
cancel.backgroundColor = UIColor(hex: 0xF5F6F8)
|
||||
cancel.layer.cornerRadius = 10
|
||||
cancel.accessibilityIdentifier = "scenic.materials.date.cancel"
|
||||
cancel.addTarget(self, action: #selector(cancelTapped), for: .touchUpInside)
|
||||
let confirm = UIButton(type: .system)
|
||||
confirm.setTitle("确定", for: .normal)
|
||||
confirm.setTitleColor(.white, for: .normal)
|
||||
confirm.backgroundColor = ScenicMaterialsStyle.primary
|
||||
confirm.layer.cornerRadius = 10
|
||||
confirm.accessibilityIdentifier = "scenic.materials.date.confirm"
|
||||
confirm.addTarget(self, action: #selector(confirmTapped), for: .touchUpInside)
|
||||
let actions = UIStackView(arrangedSubviews: [cancel, confirm])
|
||||
actions.distribution = .fillEqually
|
||||
actions.spacing = 12
|
||||
let scrollView = UIScrollView()
|
||||
let content = UIView()
|
||||
view.addSubview(scrollView)
|
||||
view.addSubview(actions)
|
||||
scrollView.addSubview(content)
|
||||
[title, hint, allButton, dateRow, picker, retention].forEach(content.addSubview)
|
||||
actions.snp.makeConstraints {
|
||||
$0.leading.trailing.equalToSuperview().inset(22)
|
||||
$0.bottom.equalTo(view.safeAreaLayoutGuide).inset(12)
|
||||
$0.height.equalTo(46)
|
||||
}
|
||||
scrollView.snp.makeConstraints {
|
||||
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
|
||||
$0.bottom.equalTo(actions.snp.top).offset(-12)
|
||||
}
|
||||
content.snp.makeConstraints { $0.edges.equalTo(scrollView.contentLayoutGuide); $0.width.equalTo(scrollView.frameLayoutGuide) }
|
||||
title.snp.makeConstraints { $0.top.equalToSuperview().offset(20); $0.leading.equalToSuperview().offset(22) }
|
||||
hint.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(12); $0.leading.equalTo(title) }
|
||||
allButton.snp.makeConstraints { $0.centerY.equalTo(hint); $0.trailing.equalToSuperview().inset(22); $0.height.equalTo(44) }
|
||||
dateRow.snp.makeConstraints { $0.top.equalTo(hint.snp.bottom).offset(16); $0.leading.trailing.equalToSuperview().inset(22); $0.height.equalTo(65) }
|
||||
picker.snp.makeConstraints { $0.top.equalTo(dateRow.snp.bottom).offset(4); $0.leading.trailing.equalToSuperview().inset(12); $0.height.equalTo(210) }
|
||||
retention.snp.makeConstraints { $0.top.equalTo(picker.snp.bottom).offset(4); $0.leading.trailing.equalToSuperview().inset(20); $0.bottom.equalToSuperview().inset(4) }
|
||||
}
|
||||
|
||||
private func updateUI() {
|
||||
var allConfiguration = UIButton.Configuration.plain()
|
||||
allConfiguration.title = "全部时间"
|
||||
allConfiguration.image = UIImage(systemName: usesAllDates ? "checkmark.circle.fill" : "circle")
|
||||
allConfiguration.imagePadding = 5
|
||||
allConfiguration.baseForegroundColor = usesAllDates ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.secondary
|
||||
allConfiguration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 16)
|
||||
allConfiguration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { input in
|
||||
var output = input; output.font = .systemFont(ofSize: 12); return output
|
||||
}
|
||||
allButton.configuration = allConfiguration
|
||||
allButton.accessibilityTraits = usesAllDates ? [.button, .selected] : .button
|
||||
let formatter = DateFormatter()
|
||||
formatter.calendar = calendar
|
||||
formatter.timeZone = calendar.timeZone
|
||||
formatter.locale = Locale(identifier: "zh_CN")
|
||||
formatter.dateFormat = "M 月 d 日"
|
||||
for (button, value, name, candidate) in [(startButton, startDate, "开始日期", Endpoint.start), (endButton, endDate, "结束日期", Endpoint.end)] {
|
||||
let active = endpoint == candidate && !usesAllDates
|
||||
let foreground = active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.text
|
||||
let titleColor = active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.secondary
|
||||
var configuration = UIButton.Configuration.plain()
|
||||
configuration.title = name
|
||||
configuration.subtitle = formatter.string(from: value)
|
||||
configuration.titleAlignment = .center
|
||||
configuration.titlePadding = 4
|
||||
configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8)
|
||||
configuration.baseForegroundColor = foreground
|
||||
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
|
||||
var result = attributes
|
||||
result.font = .systemFont(ofSize: 12, weight: .regular)
|
||||
result.foregroundColor = titleColor
|
||||
return result
|
||||
}
|
||||
configuration.subtitleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
|
||||
var result = attributes
|
||||
result.font = .systemFont(ofSize: 14, weight: active ? .medium : .regular)
|
||||
result.foregroundColor = foreground
|
||||
return result
|
||||
}
|
||||
UIView.performWithoutAnimation {
|
||||
button.configuration = configuration
|
||||
button.layoutIfNeeded()
|
||||
}
|
||||
button.backgroundColor = active ? ScenicMaterialsStyle.primary.withAlphaComponent(0.06) : UIColor(hex: 0xF7F8FA)
|
||||
button.layer.borderColor = (active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.border).cgColor
|
||||
button.accessibilityTraits = active ? [.button, .selected] : .button
|
||||
button.accessibilityLabel = "\(name),\(formatter.string(from: value))"
|
||||
}
|
||||
picker.setDate(endpoint == .start ? startDate : endDate, animated: false)
|
||||
picker.alpha = usesAllDates ? 0.4 : 1
|
||||
picker.isUserInteractionEnabled = !usesAllDates
|
||||
}
|
||||
|
||||
@objc private func allTapped() { usesAllDates.toggle(); updateUI() }
|
||||
@objc private func startTapped() { endpoint = .start; usesAllDates = false; updateUI() }
|
||||
@objc private func endTapped() { endpoint = .end; usesAllDates = false; updateUI() }
|
||||
|
||||
@objc private func dateChanged() {
|
||||
let value = min(max(calendar.startOfDay(for: picker.date), minimumDate), maximumDate)
|
||||
if endpoint == .start {
|
||||
startDate = value
|
||||
if endDate < value { endDate = value }
|
||||
} else {
|
||||
endDate = value
|
||||
if startDate > value { startDate = value }
|
||||
}
|
||||
updateUI()
|
||||
}
|
||||
|
||||
@objc private func cancelTapped() { dismiss(animated: true) }
|
||||
|
||||
@objc private func confirmTapped() {
|
||||
let start: Date? = usesAllDates ? nil : startDate
|
||||
let end: Date? = usesAllDates ? nil : endDate
|
||||
let completion = onSelectRange
|
||||
dismiss(animated: true) { completion?(start, end) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import AVFoundation
|
||||
import AVKit
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 景区空镜独立预览面板,仅播放应用内演示短片,不接入订单或网络素材。
|
||||
@MainActor
|
||||
final class ScenicMaterialPreviewViewController: UIViewController {
|
||||
private let clip: ScenicMaterialClip
|
||||
private let routeName: String
|
||||
private let capturedAt: Date
|
||||
private let calendar: Calendar
|
||||
private let playerController = AVPlayerViewController()
|
||||
private let coverView = UIImageView()
|
||||
private let playButton = UIButton(type: .system)
|
||||
private let playbackStatus = ScenicMaterialsStyle.label("本地演示短片 · 非真实景区视频", size: 11, color: ScenicMaterialsStyle.secondary)
|
||||
private var playbackTask: Task<Void, Never>?
|
||||
|
||||
/// 预览指定片段,原片元信息与本地演示视频时长明确区分。
|
||||
init(clip: ScenicMaterialClip, routeName: String, capturedAt: Date, calendar: Calendar = .current) {
|
||||
self.clip = clip
|
||||
self.routeName = routeName
|
||||
self.capturedAt = capturedAt
|
||||
self.calendar = calendar
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
modalPresentationStyle = .pageSheet
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
setupUI()
|
||||
sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, 510) }]
|
||||
sheetPresentationController?.prefersGrabberVisible = true
|
||||
sheetPresentationController?.preferredCornerRadius = 24
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(pausePlayback),
|
||||
name: UIApplication.willResignActiveNotification, object: nil)
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
pausePlayback()
|
||||
playbackTask?.cancel()
|
||||
playbackTask = nil
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
view.backgroundColor = .white
|
||||
view.accessibilityIdentifier = "scenic.materials.preview.sheet"
|
||||
let title = ScenicMaterialsStyle.label("视频预览", size: 19, weight: .semibold)
|
||||
let closeButton = UIButton(type: .system)
|
||||
closeButton.setImage(UIImage(systemName: "xmark"), for: .normal)
|
||||
closeButton.tintColor = ScenicMaterialsStyle.secondary
|
||||
closeButton.accessibilityLabel = "关闭景区视频预览"
|
||||
closeButton.accessibilityIdentifier = "scenic.materials.preview.close"
|
||||
closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
|
||||
let mediaContainer = UIView()
|
||||
mediaContainer.backgroundColor = .black
|
||||
mediaContainer.layer.cornerRadius = 12
|
||||
mediaContainer.clipsToBounds = true
|
||||
coverView.image = UIImage(named: clip.coverAssetName)
|
||||
coverView.contentMode = .scaleAspectFill
|
||||
coverView.clipsToBounds = true
|
||||
playButton.setImage(UIImage(systemName: "play.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 48)), for: .normal)
|
||||
playButton.tintColor = .white
|
||||
playButton.accessibilityLabel = "播放本地演示视频"
|
||||
playButton.accessibilityIdentifier = "scenic.materials.preview.play"
|
||||
playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside)
|
||||
playbackStatus.numberOfLines = 2
|
||||
let metadata = ScenicMaterialsStyle.label("片段 \(String(format: "%02d", clip.ordinal)) · 原片 \(clip.durationText) · \(clip.resolution) · \(clip.sizeText)", size: 12, color: ScenicMaterialsStyle.secondary)
|
||||
metadata.numberOfLines = 2
|
||||
metadata.accessibilityIdentifier = "scenic.materials.preview.metadata"
|
||||
let route = ScenicMaterialsStyle.label(routeName, size: 17, weight: .semibold)
|
||||
route.numberOfLines = 2
|
||||
route.accessibilityIdentifier = "scenic.materials.preview.route"
|
||||
let formatter = DateFormatter()
|
||||
formatter.calendar = calendar
|
||||
formatter.timeZone = calendar.timeZone
|
||||
formatter.locale = Locale(identifier: "zh_CN")
|
||||
formatter.dateFormat = "MM-dd HH:mm"
|
||||
let time = ScenicMaterialsStyle.label(formatter.string(from: capturedAt), size: 12, color: ScenicMaterialsStyle.secondary)
|
||||
let done = UIButton(type: .system)
|
||||
done.setTitle("返回素材列表", for: .normal)
|
||||
done.setTitleColor(ScenicMaterialsStyle.primary, for: .normal)
|
||||
done.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
|
||||
done.backgroundColor = ScenicMaterialsStyle.primary.withAlphaComponent(0.07)
|
||||
done.layer.cornerRadius = 10
|
||||
done.accessibilityIdentifier = "scenic.materials.preview.done"
|
||||
done.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
|
||||
let scroll = UIScrollView()
|
||||
let content = UIView()
|
||||
view.addSubview(scroll)
|
||||
scroll.addSubview(content)
|
||||
[title, closeButton, playbackStatus, mediaContainer, metadata, route, time, done].forEach(content.addSubview)
|
||||
addChild(playerController)
|
||||
playerController.view.backgroundColor = .black
|
||||
playerController.view.isHidden = true
|
||||
playerController.allowsPictureInPicturePlayback = false
|
||||
playerController.exitsFullScreenWhenPlaybackEnds = true
|
||||
mediaContainer.addSubview(playerController.view)
|
||||
playerController.didMove(toParent: self)
|
||||
mediaContainer.addSubview(coverView)
|
||||
mediaContainer.addSubview(playButton)
|
||||
scroll.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
|
||||
content.snp.makeConstraints { $0.edges.equalTo(scroll.contentLayoutGuide); $0.width.equalTo(scroll.frameLayoutGuide) }
|
||||
title.snp.makeConstraints { $0.top.equalToSuperview().offset(20); $0.leading.equalToSuperview().offset(22) }
|
||||
closeButton.snp.makeConstraints { $0.trailing.equalToSuperview().inset(10); $0.centerY.equalTo(title); $0.size.equalTo(44) }
|
||||
playbackStatus.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(10); $0.leading.trailing.equalToSuperview().inset(22) }
|
||||
mediaContainer.snp.makeConstraints {
|
||||
$0.top.equalTo(playbackStatus.snp.bottom).offset(14)
|
||||
$0.leading.trailing.equalToSuperview().inset(22)
|
||||
$0.height.equalTo(mediaContainer.snp.width).multipliedBy(9.0 / 16.0)
|
||||
}
|
||||
playerController.view.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
coverView.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
playButton.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
metadata.snp.makeConstraints { $0.top.equalTo(mediaContainer.snp.bottom).offset(10); $0.leading.trailing.equalTo(mediaContainer) }
|
||||
route.snp.makeConstraints { $0.top.equalTo(metadata.snp.bottom).offset(17); $0.leading.trailing.equalTo(mediaContainer) }
|
||||
time.snp.makeConstraints { $0.top.equalTo(route.snp.bottom).offset(8); $0.leading.trailing.equalTo(mediaContainer) }
|
||||
done.snp.makeConstraints {
|
||||
$0.top.equalTo(time.snp.bottom).offset(18)
|
||||
$0.leading.trailing.equalTo(mediaContainer)
|
||||
$0.height.equalTo(44)
|
||||
$0.bottom.equalToSuperview().inset(14)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func playTapped() {
|
||||
guard playbackTask == nil, clip.isAvailable else { return }
|
||||
guard let url = Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4")
|
||||
?? Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4", subdirectory: "DroneDock") else {
|
||||
playbackStatus.text = "本地演示视频暂不可用"
|
||||
return
|
||||
}
|
||||
playButton.isEnabled = false
|
||||
playbackTask = Task { @MainActor [weak self] in
|
||||
let playable = (try? await AVURLAsset(url: url).load(.isPlayable)) == true
|
||||
guard let self else { return }
|
||||
self.playbackTask = nil
|
||||
self.playButton.isEnabled = true
|
||||
guard !Task.isCancelled, self.view.window != nil else { return }
|
||||
guard playable else {
|
||||
self.playbackStatus.text = "本地演示视频暂不可播放"
|
||||
return
|
||||
}
|
||||
self.playerController.player = AVPlayer(url: url)
|
||||
self.playerController.view.isHidden = false
|
||||
self.coverView.isHidden = true
|
||||
self.playButton.isHidden = true
|
||||
self.playbackStatus.text = "正在播放 3 秒本地演示 · 原片时长见下方"
|
||||
self.playerController.player?.play()
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func pausePlayback() { playerController.player?.pause() }
|
||||
@objc private func closeTapped() { pausePlayback(); dismiss(animated: true) }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import UIKit
|
||||
|
||||
#if DEBUG
|
||||
/// 空镜库独立调试入口,不伪造正式首页权限,也不创建机巢工作台或订单。
|
||||
@MainActor
|
||||
enum ScenicMaterialsPreview {
|
||||
/// 指定启动参数时展示独立素材库;正式首页入口等待实际权限 URI 配置。
|
||||
static func navigationController(arguments: [String]) -> UINavigationController? {
|
||||
guard arguments.contains("--scenic-materials-preview") else { return nil }
|
||||
let model = ScenicMaterialsViewModel()
|
||||
if let value = arguments.first(where: { $0.hasPrefix("--scenic-materials-scenario=") }),
|
||||
let scenario = ScenicMaterialsScenario(rawValue: String(value.dropFirst("--scenic-materials-scenario=".count))) {
|
||||
model.applyScenario(scenario)
|
||||
}
|
||||
let controller = ScenicMaterialsViewController(viewModel: model,
|
||||
isDemoPhotoPermissionAllowed: !arguments.contains("--scenic-materials-permission-denied"))
|
||||
return UINavigationController(rootViewController: controller)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,467 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 独立景区空镜库页面,提供筛选、分组预览、选择与前台下载演示,不依赖机巢订单。
|
||||
@MainActor
|
||||
final class ScenicMaterialsViewController: BaseViewController {
|
||||
/// 当前景区的素材与本地选择、下载状态。
|
||||
let viewModel: ScenicMaterialsViewModel
|
||||
|
||||
/// 辅助说明与每次拍摄批次分别使用稳定分区身份。
|
||||
private enum Section: Hashable { case retention, group(String), end }
|
||||
/// 选择与进度不参与身份,Diffable 更新时复用原有单元。
|
||||
private enum Item: Hashable { case retention, clip(String), expand(String), end }
|
||||
|
||||
private let filterBar = UIStackView()
|
||||
private let routeButton = UIButton(type: .system)
|
||||
private let dateButton = UIButton(type: .system)
|
||||
private let footer = ScenicMaterialsFooterView()
|
||||
private let emptyView = UIView()
|
||||
private let emptyTitle = ScenicMaterialsStyle.label(size: 18, weight: .semibold)
|
||||
private let emptyMessage = ScenicMaterialsStyle.label(size: 14, color: ScenicMaterialsStyle.secondary)
|
||||
private let resetButton = UIButton(type: .system)
|
||||
private let driver = ScenicMaterialDemoDownloadDriver()
|
||||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
|
||||
private var isDemoPhotoPermissionAllowed: Bool
|
||||
|
||||
/// 注入独立景区上下文;权限开关只用于本地演示,不读写系统相册授权。
|
||||
init(viewModel: ScenicMaterialsViewModel = ScenicMaterialsViewModel(), isDemoPhotoPermissionAllowed: Bool = true) {
|
||||
self.viewModel = viewModel
|
||||
self.isDemoPhotoPermissionAllowed = isDemoPhotoPermissionAllowed
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "景区素材"
|
||||
navigationItem.backButtonDisplayMode = .minimal
|
||||
let appearance = UINavigationBarAppearance()
|
||||
appearance.configureWithOpaqueBackground()
|
||||
appearance.backgroundColor = .white
|
||||
appearance.shadowColor = .clear
|
||||
appearance.titleTextAttributes = [.foregroundColor: ScenicMaterialsStyle.text,
|
||||
.font: UIFont.systemFont(ofSize: 18, weight: .semibold)]
|
||||
navigationItem.standardAppearance = appearance
|
||||
navigationItem.scrollEdgeAppearance = appearance
|
||||
#if DEBUG
|
||||
var actions: [UIAction] = ScenicMaterialsScenario.allCases.map { scenario in
|
||||
UIAction(title: scenario.title) { [weak self] _ in self?.applyPreviewScenario(scenario) }
|
||||
}
|
||||
actions.append(UIAction(title: "相册权限不足") { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.driver.stop()
|
||||
self.viewModel.pauseDownload()
|
||||
self.isDemoPhotoPermissionAllowed = false
|
||||
self.refreshDisplay(animated: false)
|
||||
self.presentPermissionDemo()
|
||||
})
|
||||
let menu = UIBarButtonItem(image: UIImage(systemName: "slider.horizontal.3"), menu: UIMenu(title: "空镜库本地演示", children: actions))
|
||||
menu.accessibilityLabel = "体验空镜库其他状态"
|
||||
menu.accessibilityIdentifier = "scenic.materials.scenarios"
|
||||
navigationItem.rightBarButtonItem = menu
|
||||
#endif
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = .white
|
||||
view.accessibilityIdentifier = "scenic.materials"
|
||||
filterBar.axis = .horizontal
|
||||
filterBar.distribution = .fillEqually
|
||||
filterBar.spacing = 10
|
||||
configureFilterButton(routeButton, identifier: "scenic.materials.routeFilter")
|
||||
configureFilterButton(dateButton, identifier: "scenic.materials.dateFilter")
|
||||
filterBar.addArrangedSubview(routeButton)
|
||||
filterBar.addArrangedSubview(dateButton)
|
||||
collectionView.backgroundColor = .white
|
||||
collectionView.alwaysBounceVertical = true
|
||||
collectionView.showsVerticalScrollIndicator = true
|
||||
collectionView.accessibilityIdentifier = "scenic.materials.list"
|
||||
collectionView.register(ScenicMaterialClipCell.self, forCellWithReuseIdentifier: "clip")
|
||||
collectionView.register(ScenicMaterialExpandCell.self, forCellWithReuseIdentifier: "expand")
|
||||
collectionView.register(ScenicMaterialTextCell.self, forCellWithReuseIdentifier: "text")
|
||||
collectionView.register(ScenicMaterialGroupHeaderView.self,
|
||||
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
|
||||
withReuseIdentifier: "group")
|
||||
view.addSubview(filterBar)
|
||||
view.addSubview(collectionView)
|
||||
view.addSubview(footer)
|
||||
setupEmptyView()
|
||||
configureDataSource()
|
||||
refreshDisplay(animated: false)
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
filterBar.snp.makeConstraints { make in
|
||||
make.top.equalTo(view.safeAreaLayoutGuide).offset(10)
|
||||
make.leading.trailing.equalToSuperview().inset(16)
|
||||
make.height.equalTo(42)
|
||||
}
|
||||
collectionView.snp.makeConstraints { make in
|
||||
make.top.equalTo(filterBar.snp.bottom).offset(8)
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.bottom.equalTo(footer.snp.top)
|
||||
}
|
||||
footer.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() }
|
||||
}
|
||||
|
||||
override func bindActions() {
|
||||
routeButton.addTarget(self, action: #selector(selectRoute), for: .touchUpInside)
|
||||
dateButton.addTarget(self, action: #selector(selectDateRange), for: .touchUpInside)
|
||||
resetButton.addTarget(self, action: #selector(resetFilters), for: .touchUpInside)
|
||||
footer.onPrimaryTap = { [weak self] in self?.performPrimaryAction() }
|
||||
footer.onSecondaryTap = { [weak self] in
|
||||
guard let self else { return }
|
||||
self.driver.stop()
|
||||
if self.viewModel.phase == .downloading || self.viewModel.phase == .paused {
|
||||
self.viewModel.cancelDownload()
|
||||
} else {
|
||||
self.viewModel.continueSelecting()
|
||||
}
|
||||
self.refreshDisplay(animated: true)
|
||||
}
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(pauseForBackground),
|
||||
name: UIApplication.willResignActiveNotification, object: nil)
|
||||
}
|
||||
|
||||
/// 真正离开时暂停;预览或筛选弹层不会中止下载,取消返回手势也不会误暂停。
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
guard isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true else { return }
|
||||
if let coordinator = transitionCoordinator, coordinator.isInteractive {
|
||||
coordinator.animate(alongsideTransition: nil) { [weak self] context in
|
||||
if !context.isCancelled { self?.pauseForBackground() }
|
||||
}
|
||||
} else {
|
||||
pauseForBackground()
|
||||
}
|
||||
}
|
||||
|
||||
/// 外部演示回执后显式刷新,不自动开始或继续任何传输。
|
||||
func refreshDisplay(animated: Bool = true) {
|
||||
guard dataSource != nil else { return }
|
||||
routeButton.setTitle(viewModel.routeFilterTitle, for: .normal)
|
||||
dateButton.setTitle(viewModel.dateFilterTitle, for: .normal)
|
||||
routeButton.isEnabled = !viewModel.isSelectionLocked
|
||||
dateButton.isEnabled = !viewModel.isSelectionLocked
|
||||
emptyTitle.text = viewModel.emptyTitle
|
||||
emptyMessage.text = viewModel.emptyMessage
|
||||
resetButton.isHidden = viewModel.selectedRouteID == nil && viewModel.dateRange == nil
|
||||
collectionView.backgroundView = viewModel.filteredGroups.isEmpty ? emptyView : nil
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
|
||||
snapshot.appendSections([.retention])
|
||||
snapshot.appendItems([.retention])
|
||||
for group in viewModel.filteredGroups {
|
||||
snapshot.appendSections([.group(group.id)])
|
||||
snapshot.appendItems(viewModel.visibleClips(in: group).map { .clip($0.id) })
|
||||
if group.clips.count > 5 { snapshot.appendItems([.expand(group.id)]) }
|
||||
}
|
||||
if !viewModel.filteredGroups.isEmpty {
|
||||
snapshot.appendSections([.end]); snapshot.appendItems([.end])
|
||||
}
|
||||
let existing = Set(dataSource.snapshot().itemIdentifiers)
|
||||
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
|
||||
dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in
|
||||
guard let self else { return }
|
||||
self.collectionView.collectionViewLayout.invalidateLayout()
|
||||
self.refreshVisibleHeaders()
|
||||
}
|
||||
updateFooter()
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
/// 状态菜单只切换本地演示,重置演示权限后等待工作人员主动操作。
|
||||
func applyPreviewScenario(_ scenario: ScenicMaterialsScenario) {
|
||||
driver.stop()
|
||||
isDemoPhotoPermissionAllowed = true
|
||||
viewModel.applyScenario(scenario)
|
||||
refreshDisplay(animated: true)
|
||||
}
|
||||
#endif
|
||||
|
||||
private func configureFilterButton(_ button: UIButton, identifier: String) {
|
||||
var configuration = UIButton.Configuration.plain()
|
||||
configuration.image = UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .medium))
|
||||
configuration.imagePlacement = .trailing
|
||||
configuration.imagePadding = 8
|
||||
configuration.baseForegroundColor = ScenicMaterialsStyle.text
|
||||
configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12)
|
||||
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
|
||||
var result = incoming; result.font = .systemFont(ofSize: 13); return result
|
||||
}
|
||||
button.configuration = configuration
|
||||
button.backgroundColor = UIColor(hex: 0xF6F7F9)
|
||||
button.layer.cornerRadius = 10
|
||||
button.layer.borderWidth = 0.5
|
||||
button.layer.borderColor = ScenicMaterialsStyle.border.cgColor
|
||||
button.titleLabel?.lineBreakMode = .byTruncatingTail
|
||||
button.accessibilityIdentifier = identifier
|
||||
}
|
||||
|
||||
private func setupEmptyView() {
|
||||
let icon = UIImageView(image: UIImage(systemName: "photo.on.rectangle.angled"))
|
||||
icon.tintColor = ScenicMaterialsStyle.secondary.withAlphaComponent(0.5)
|
||||
icon.contentMode = .scaleAspectFit
|
||||
emptyTitle.textAlignment = .center
|
||||
emptyTitle.numberOfLines = 0
|
||||
emptyMessage.textAlignment = .center
|
||||
emptyMessage.numberOfLines = 0
|
||||
resetButton.setTitle("重置筛选", for: .normal)
|
||||
resetButton.tintColor = ScenicMaterialsStyle.primary
|
||||
resetButton.accessibilityIdentifier = "scenic.materials.resetFilters"
|
||||
emptyView.accessibilityIdentifier = "scenic.materials.empty"
|
||||
let stack = UIStackView(arrangedSubviews: [icon, emptyTitle, emptyMessage, resetButton])
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 14
|
||||
emptyView.addSubview(stack)
|
||||
stack.snp.makeConstraints { make in
|
||||
make.centerX.equalToSuperview(); make.centerY.equalToSuperview().offset(-24)
|
||||
make.leading.trailing.equalToSuperview().inset(32)
|
||||
}
|
||||
icon.snp.makeConstraints { $0.height.equalTo(48) }
|
||||
resetButton.snp.makeConstraints { $0.height.equalTo(44).priority(999) }
|
||||
}
|
||||
|
||||
private func configureDataSource() {
|
||||
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, path, item in
|
||||
guard let self else { return UICollectionViewCell() }
|
||||
switch item {
|
||||
case .clip(let id):
|
||||
guard let clip = self.viewModel.clip(id: id),
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "clip", for: path) as? ScenicMaterialClipCell else { return UICollectionViewCell() }
|
||||
self.configureClip(cell, clip: clip)
|
||||
return cell
|
||||
case .expand(let id):
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "expand", for: path) as! ScenicMaterialExpandCell
|
||||
let expanded = self.viewModel.expandedGroupIDs.contains(id)
|
||||
let remaining = max((self.viewModel.group(id: id)?.clips.count ?? 5) - 5, 0)
|
||||
cell.configure(groupID: id, title: expanded ? "收起片段" : "展开其余 \(remaining) 段")
|
||||
cell.onToggleExpanded = { [weak self] in
|
||||
self?.viewModel.toggleExpandedGroup(id: id)
|
||||
self?.refreshDisplay(animated: true)
|
||||
}
|
||||
return cell
|
||||
case .retention, .end:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! ScenicMaterialTextCell
|
||||
cell.configure(item == .retention ? "素材保留 90 天,请及时下载" : "已显示保留期内的全部演示记录", identifier: item == .retention ? "scenic.materials.retention" : "scenic.materials.end")
|
||||
return cell
|
||||
}
|
||||
}
|
||||
dataSource.supplementaryViewProvider = { [weak self] list, kind, path in
|
||||
guard let self, kind == UICollectionView.elementKindSectionHeader else { return nil }
|
||||
let sections = self.dataSource.snapshot().sectionIdentifiers
|
||||
guard sections.indices.contains(path.section), case .group(let id) = sections[path.section],
|
||||
let group = self.viewModel.group(id: id) else { return nil }
|
||||
let header = list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "group", for: path) as! ScenicMaterialGroupHeaderView
|
||||
self.configureHeader(header, group: group)
|
||||
return header
|
||||
}
|
||||
}
|
||||
|
||||
private func configureClip(_ cell: ScenicMaterialClipCell, clip: ScenicMaterialClip) {
|
||||
let completed = viewModel.completedIDs.contains(clip.id)
|
||||
let failed = viewModel.failedIDs.contains(clip.id)
|
||||
let inBatch = viewModel.batchItemIDs.contains(clip.id)
|
||||
let status: String? = completed ? "演示已下载" : failed ? "下载失败" : inBatch && viewModel.phase == .paused ? "已暂停" : nil
|
||||
cell.configure(clip: clip, selected: viewModel.selectedIDs.contains(clip.id),
|
||||
isSelectionEnabled: viewModel.canSelect(id: clip.id), statusText: status,
|
||||
progress: inBatch && viewModel.phase == .downloading && !completed ? viewModel.progressByID[clip.id] ?? 0 : nil,
|
||||
isHero: viewModel.group(id: clip.groupID)?.clips.first?.id == clip.id)
|
||||
cell.onToggleSelection = { [weak self] in
|
||||
self?.viewModel.toggleSelection(id: clip.id)
|
||||
self?.refreshDisplay(animated: true)
|
||||
}
|
||||
cell.onPreview = { [weak self] in self?.preview(clip) }
|
||||
}
|
||||
|
||||
private func configureHeader(_ header: ScenicMaterialGroupHeaderView, group: ScenicMaterialGroup) {
|
||||
let index = viewModel.filteredGroups.firstIndex { $0.id == group.id } ?? 0
|
||||
let showRoute = index == 0 || viewModel.filteredGroups[index - 1].routeID != group.routeID
|
||||
let formatter = DateFormatter()
|
||||
formatter.locale = Locale(identifier: "zh_CN")
|
||||
formatter.calendar = viewModel.calendar
|
||||
formatter.timeZone = viewModel.calendar.timeZone
|
||||
formatter.dateFormat = "MM-dd HH:mm"
|
||||
header.configure(groupID: group.id, routeName: showRoute ? viewModel.route(id: group.routeID)?.name : nil,
|
||||
timeTitle: formatter.string(from: group.capturedAt), count: group.clips.count,
|
||||
isSelected: viewModel.isGroupSelected(id: group.id),
|
||||
canSelect: group.clips.contains { viewModel.canSelect(id: $0.id) })
|
||||
header.onToggleGroup = { [weak self] in
|
||||
self?.viewModel.toggleGroup(id: group.id)
|
||||
self?.refreshDisplay(animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
private func refreshVisibleHeaders() {
|
||||
for path in collectionView.indexPathsForVisibleSupplementaryElements(ofKind: UICollectionView.elementKindSectionHeader) {
|
||||
let sections = dataSource.snapshot().sectionIdentifiers
|
||||
guard sections.indices.contains(path.section), case .group(let id) = sections[path.section],
|
||||
let group = viewModel.group(id: id),
|
||||
let header = collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: path) as? ScenicMaterialGroupHeaderView else { continue }
|
||||
configureHeader(header, group: group)
|
||||
}
|
||||
}
|
||||
|
||||
private func makeLayout() -> UICollectionViewLayout {
|
||||
UICollectionViewCompositionalLayout { [weak self] index, environment in
|
||||
guard let self, let dataSource = self.dataSource else { return nil }
|
||||
let sections = dataSource.snapshot().sectionIdentifiers
|
||||
guard sections.indices.contains(index) else { return nil }
|
||||
let section = sections[index]
|
||||
guard case .group(let id) = section, let group = self.viewModel.group(id: id) else {
|
||||
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)))
|
||||
let row = NSCollectionLayoutGroup.vertical(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(36)), subitems: [item])
|
||||
let layout = NSCollectionLayoutSection(group: row)
|
||||
layout.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)
|
||||
return layout
|
||||
}
|
||||
let width = max(environment.container.effectiveContentSize.width - 32, 1)
|
||||
let heroHeight = width * 9 / 16
|
||||
let smallWidth = (width - 8) / 2
|
||||
let smallHeight = smallWidth * 9 / 16
|
||||
var rows: [NSCollectionLayoutItem] = [NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(heroHeight)))]
|
||||
var height = heroHeight
|
||||
var remaining = max(self.viewModel.visibleClips(in: group).count - 1, 0)
|
||||
while remaining > 0 {
|
||||
let count = min(remaining, 2)
|
||||
let items = (0..<count).map { _ in NSCollectionLayoutItem(layoutSize: .init(widthDimension: .absolute(smallWidth), heightDimension: .fractionalHeight(1))) }
|
||||
// 奇数末项限定行宽,防止组合布局将下一条“收起”单元补入右侧空位。
|
||||
let rowWidth: NSCollectionLayoutDimension = count == 1 ? .absolute(smallWidth) : .fractionalWidth(1)
|
||||
let row = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: rowWidth, heightDimension: .absolute(smallHeight)), subitems: items)
|
||||
row.interItemSpacing = .fixed(8)
|
||||
rows.append(row); height += 8 + smallHeight; remaining -= count
|
||||
}
|
||||
if group.clips.count > 5 {
|
||||
rows.append(NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(40))))
|
||||
height += 48
|
||||
}
|
||||
let grid = NSCollectionLayoutGroup.vertical(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(height)), subitems: rows)
|
||||
grid.interItemSpacing = .fixed(8)
|
||||
let layout = NSCollectionLayoutSection(group: grid)
|
||||
layout.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 20, trailing: 16)
|
||||
let previous = self.viewModel.filteredGroups.firstIndex { $0.id == id } ?? 0
|
||||
let showRoute = previous == 0 || self.viewModel.filteredGroups[previous - 1].routeID != group.routeID
|
||||
layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
|
||||
layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(showRoute ? 94 : 48)),
|
||||
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)]
|
||||
return layout
|
||||
}
|
||||
}
|
||||
|
||||
private func updateFooter() {
|
||||
let completed = viewModel.completedCount
|
||||
let total = viewModel.totalCount
|
||||
switch viewModel.phase {
|
||||
case .idle:
|
||||
footer.configure(title: "已选 \(viewModel.selectedCount) 段", detail: "本地演示 · 不下载或保存真实文件",
|
||||
primaryTitle: viewModel.selectedCount > 0 ? "下载所选(\(viewModel.selectedCount))" : "下载所选", primaryEnabled: viewModel.canStartDownload)
|
||||
case .downloading:
|
||||
footer.configure(title: "下载中 · \(completed)/\(total) 段", detail: "请保持页面开启,切后台将暂停",
|
||||
primaryTitle: "正在下载…", primaryEnabled: false, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress))
|
||||
case .paused:
|
||||
footer.configure(title: "已暂停 · 已完成 \(completed)/\(total) 段", detail: "演示进度已保留,请手动继续",
|
||||
primaryTitle: "继续下载", primaryEnabled: true, secondaryTitle: "取消")
|
||||
case .partialFailure:
|
||||
footer.configure(title: "演示完成 \(completed) 段 · 失败 \(viewModel.failedCount) 段", detail: "未保存真实文件,成功项不重复下载",
|
||||
primaryTitle: "重试失败(\(viewModel.failedCount))", primaryEnabled: true, secondaryTitle: "继续选择")
|
||||
case .completed:
|
||||
footer.configure(title: "演示完成 \(completed) 段", detail: "未写入系统相册",
|
||||
primaryTitle: "继续选择素材", primaryEnabled: true)
|
||||
}
|
||||
}
|
||||
|
||||
private func performPrimaryAction() {
|
||||
if viewModel.phase == .completed {
|
||||
viewModel.continueSelecting(); refreshDisplay(); return
|
||||
}
|
||||
guard isDemoPhotoPermissionAllowed else { presentPermissionDemo(); return }
|
||||
let started: Bool
|
||||
switch viewModel.phase {
|
||||
case .idle: started = viewModel.startDownload()
|
||||
case .paused: started = viewModel.continueDownload()
|
||||
case .partialFailure: started = viewModel.retryFailedDownloads()
|
||||
case .downloading, .completed: started = false
|
||||
}
|
||||
refreshDisplay(animated: false)
|
||||
if started { driver.start(viewModel: viewModel) { [weak self] in self?.refreshDisplay(animated: false) } }
|
||||
}
|
||||
|
||||
@objc private func pauseForBackground() {
|
||||
driver.stop()
|
||||
viewModel.pauseDownload()
|
||||
if isViewLoaded { refreshDisplay(animated: false) }
|
||||
}
|
||||
|
||||
@objc private func selectRoute() {
|
||||
guard !viewModel.isSelectionLocked else { return }
|
||||
let picker = ScenicMaterialRouteFilterViewController(routes: viewModel.routes, selectedRouteID: viewModel.selectedRouteID)
|
||||
picker.onSelectRoute = { [weak self] id in
|
||||
self?.viewModel.setRoute(id: id)
|
||||
self?.refreshDisplay()
|
||||
self?.collectionView.setContentOffset(.zero, animated: false)
|
||||
}
|
||||
present(picker, animated: true)
|
||||
}
|
||||
|
||||
@objc private func selectDateRange() {
|
||||
guard !viewModel.isSelectionLocked else { return }
|
||||
let picker = ScenicMaterialDateFilterViewController(start: viewModel.dateRange?.start, end: viewModel.dateRange?.end,
|
||||
minimumDate: viewModel.minimumDate, maximumDate: viewModel.maximumDate,
|
||||
calendar: viewModel.calendar)
|
||||
picker.onSelectRange = { [weak self] start, end in
|
||||
guard let self else { return }
|
||||
if self.viewModel.setDateRange(start: start, end: end) {
|
||||
self.refreshDisplay()
|
||||
self.collectionView.setContentOffset(.zero, animated: false)
|
||||
} else { self.showToast("请选择保留期内的有效日期范围") }
|
||||
}
|
||||
present(picker, animated: true)
|
||||
}
|
||||
|
||||
@objc private func resetFilters() {
|
||||
viewModel.resetFilters()
|
||||
refreshDisplay()
|
||||
}
|
||||
|
||||
private func preview(_ clip: ScenicMaterialClip) {
|
||||
guard clip.isAvailable, let group = viewModel.group(id: clip.groupID) else { return }
|
||||
let controller = ScenicMaterialPreviewViewController(clip: clip, routeName: viewModel.route(id: group.routeID)?.name ?? "景区航线",
|
||||
capturedAt: group.capturedAt, calendar: viewModel.calendar)
|
||||
present(controller, animated: true)
|
||||
}
|
||||
|
||||
private func presentPermissionDemo() {
|
||||
guard presentedViewController == nil else { return }
|
||||
let alert = UIAlertController(title: "需要相册保存权限", message: "真实下载需允许保存视频。此处仅演示权限流程,不读取或修改系统权限。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "暂不下载", style: .cancel))
|
||||
alert.addAction(UIAlertAction(title: "演示允许权限", style: .default) { [weak self] _ in
|
||||
self?.isDemoPhotoPermissionAllowed = true
|
||||
self?.refreshDisplay(animated: false)
|
||||
self?.showToast("演示权限已恢复,请手动下载")
|
||||
})
|
||||
present(alert, animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// 空镜列表的保留期与末尾说明,不参与素材选择。
|
||||
private final class ScenicMaterialTextCell: UICollectionViewCell {
|
||||
private let label = ScenicMaterialsStyle.label(size: 12, color: ScenicMaterialsStyle.secondary)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
contentView.addSubview(label)
|
||||
label.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 根据单元用途更新文案及可访问标识。
|
||||
func configure(_ text: String, identifier: String) {
|
||||
label.text = text
|
||||
label.accessibilityIdentifier = identifier
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
import UIKit
|
||||
import XCTest
|
||||
@testable import suixinkan
|
||||
|
||||
#if DEBUG
|
||||
/// 在真机隔离窗口验证独立空镜库的布局、筛选、预览与本地下载流程。
|
||||
@MainActor
|
||||
final class ScenicMaterialsFlowViewTests: XCTestCase {
|
||||
private weak var previousKeyWindow: UIWindow?
|
||||
|
||||
/// 独立入口不创建工作台;首段和双列可点,整组选中包括折叠的第六段。
|
||||
func testIndependentEntryAndSixClipGroupSelectionAcrossExpandedLayout() async throws {
|
||||
XCTAssertNil(ScenicMaterialsPreview.navigationController(arguments: []))
|
||||
let navigation = try XCTUnwrap(ScenicMaterialsPreview.navigationController(arguments: ["--scenic-materials-preview"]))
|
||||
XCTAssertEqual(navigation.viewControllers.count, 1)
|
||||
let controller = try XCTUnwrap(navigation.topViewController as? ScenicMaterialsViewController)
|
||||
let window = makeWindow(root: navigation)
|
||||
defer { close(window) }
|
||||
let model = controller.viewModel
|
||||
let list = try await waitForLibrary(controller, window: window)
|
||||
let firstGroup = try XCTUnwrap(model.filteredGroups.first)
|
||||
let hero = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 0, section: 1)))
|
||||
let left = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 1, section: 1)))
|
||||
let right = try XCTUnwrap(list.cellForItem(at: IndexPath(item: 2, section: 1)))
|
||||
XCTAssertGreaterThan(hero.bounds.width, left.bounds.width * 1.8)
|
||||
XCTAssertGreaterThan(hero.bounds.height, 100)
|
||||
XCTAssertEqual(left.frame.minY, right.frame.minY, accuracy: 1)
|
||||
XCTAssertLessThan(left.frame.maxX, right.frame.minX)
|
||||
capture(window, named: "空镜库-常态首段与双列")
|
||||
let heroSelect = try button(in: controller.view, identifier: "scenic.materials.select.\(firstGroup.clips[0].id)")
|
||||
assertReachable(heroSelect, window: window)
|
||||
heroSelect.sendActions(for: .touchUpInside)
|
||||
XCTAssertEqual(model.selectedIDs, [firstGroup.clips[0].id])
|
||||
let tileSelect = try button(in: controller.view, identifier: "scenic.materials.select.\(firstGroup.clips[1].id)")
|
||||
assertReachable(tileSelect, window: window)
|
||||
tileSelect.sendActions(for: .touchUpInside)
|
||||
XCTAssertEqual(model.selectedCount, 2)
|
||||
assertLayout(in: controller.view)
|
||||
capture(window, named: "空镜库-双列片段选择")
|
||||
|
||||
model.toggleSelection(id: firstGroup.clips[0].id)
|
||||
model.toggleSelection(id: firstGroup.clips[1].id)
|
||||
controller.refreshDisplay(animated: false)
|
||||
let groupIndex = try XCTUnwrap(model.filteredGroups.firstIndex { $0.clips.count == 6 })
|
||||
let group = model.filteredGroups[groupIndex]
|
||||
let section = groupIndex + 1
|
||||
try await showGroupHeader(section: section, list: list, window: window)
|
||||
let groupSelect = try button(in: controller.view, identifier: "scenic.materials.group.\(group.id)")
|
||||
assertReachable(groupSelect, window: window)
|
||||
groupSelect.sendActions(for: .touchUpInside)
|
||||
XCTAssertEqual(model.selectedIDs, Set(group.clips.map(\.id)))
|
||||
XCTAssertEqual(model.visibleClips(in: group).count, 5)
|
||||
XCTAssertEqual(list.numberOfItems(inSection: section), 6)
|
||||
try await settle(window) {
|
||||
self.find(in: controller.view, identifier: "scenic.materials.group.\(group.id)")?.accessibilityTraits.contains(.selected) == true
|
||||
}
|
||||
capture(window, named: "空镜库-整组六段含折叠选择")
|
||||
list.scrollToItem(at: IndexPath(item: 5, section: section), at: .centeredVertically, animated: false)
|
||||
try await settle(window) { self.find(in: controller.view, identifier: "scenic.materials.expand.\(group.id)") != nil }
|
||||
let expand = try button(in: controller.view, identifier: "scenic.materials.expand.\(group.id)")
|
||||
assertReachable(expand, window: window)
|
||||
expand.sendActions(for: .touchUpInside)
|
||||
try await settle(window) { list.numberOfItems(inSection: section) == 7 }
|
||||
XCTAssertEqual(model.visibleClips(in: group).count, 6)
|
||||
XCTAssertEqual(model.selectedIDs, Set(group.clips.map(\.id)))
|
||||
list.scrollToItem(at: IndexPath(item: 5, section: section), at: .centeredVertically, animated: false)
|
||||
try await settle(window) { self.find(in: controller.view, identifier: "scenic.materials.clip.\(group.clips[5].id)") != nil }
|
||||
let sixth = try XCTUnwrap(list.layoutAttributesForItem(at: IndexPath(item: 5, section: section)))
|
||||
let collapse = try XCTUnwrap(list.layoutAttributesForItem(at: IndexPath(item: 6, section: section)))
|
||||
let groupHero = try XCTUnwrap(list.layoutAttributesForItem(at: IndexPath(item: 0, section: section)))
|
||||
XCTAssertGreaterThan(collapse.frame.minY, sixth.frame.maxY, "收起按钮必须独占第六段下方一行")
|
||||
XCTAssertEqual(collapse.frame.width, groupHero.frame.width, accuracy: 1, "收起按钮应与首段卡片等宽")
|
||||
XCTAssertEqual(collapse.frame.minX, groupHero.frame.minX, accuracy: 1)
|
||||
assertLayout(in: controller.view)
|
||||
capture(window, named: "空镜库-展开第六段")
|
||||
}
|
||||
|
||||
/// 航线无结果可重置;日期面板的实际控件只在确定后应用按日筛选。
|
||||
func testRouteAndDateSheetCallbacksFilterResultsAndResetEmptyRoute() async throws {
|
||||
let controller = ScenicMaterialsViewController()
|
||||
let window = makeWindow(root: controller)
|
||||
defer { close(window) }
|
||||
let model = controller.viewModel
|
||||
_ = try await waitForLibrary(controller, window: window)
|
||||
let originalCount = model.filteredGroups.count
|
||||
try button(in: controller.view, identifier: "scenic.materials.routeFilter").sendActions(for: .touchUpInside)
|
||||
try await settle(window) { self.isPresentationSettled(controller, type: ScenicMaterialRouteFilterViewController.self) }
|
||||
let routeSheet = try XCTUnwrap(controller.presentedViewController as? ScenicMaterialRouteFilterViewController)
|
||||
let table = try XCTUnwrap(find(in: routeSheet.view, identifier: "scenic.materials.route.list") as? UITableView)
|
||||
let path = IndexPath(row: 3, section: 0)
|
||||
let row = try XCTUnwrap(table.cellForRow(at: path))
|
||||
assertReachable(row, window: window)
|
||||
capture(window, named: "空镜库-航线筛选")
|
||||
table.delegate?.tableView?(table, didSelectRowAt: path)
|
||||
try await settle(window) { controller.presentedViewController == nil && model.filteredGroups.isEmpty }
|
||||
XCTAssertEqual(model.selectedRouteID, model.routes[2].id)
|
||||
let reset = try button(in: controller.view, identifier: "scenic.materials.resetFilters")
|
||||
assertReachable(reset, window: window)
|
||||
capture(window, named: "空镜库-航线无结果")
|
||||
reset.sendActions(for: .touchUpInside)
|
||||
try await settle(window) { model.filteredGroups.count == originalCount }
|
||||
XCTAssertNil(model.selectedRouteID)
|
||||
|
||||
let day = try XCTUnwrap(model.filteredGroups.first?.capturedAt)
|
||||
let expected = model.filteredGroups.filter { model.calendar.isDate($0.capturedAt, inSameDayAs: day) }
|
||||
let hiddenID = try XCTUnwrap(model.filteredGroups.first { !model.calendar.isDate($0.capturedAt, inSameDayAs: day) }?.clips.first?.id)
|
||||
model.toggleSelection(id: hiddenID)
|
||||
controller.refreshDisplay(animated: false)
|
||||
try button(in: controller.view, identifier: "scenic.materials.dateFilter").sendActions(for: .touchUpInside)
|
||||
try await settle(window) { self.isPresentationSettled(controller, type: ScenicMaterialDateFilterViewController.self) }
|
||||
let dateSheet = try XCTUnwrap(controller.presentedViewController as? ScenicMaterialDateFilterViewController)
|
||||
let picker = try XCTUnwrap(find(in: dateSheet.view, identifier: "scenic.materials.date.picker") as? UIDatePicker)
|
||||
let start = try button(in: dateSheet.view, identifier: "scenic.materials.date.start")
|
||||
assertReachable(start, window: window)
|
||||
start.sendActions(for: .touchUpInside)
|
||||
picker.setDate(day, animated: false)
|
||||
picker.sendActions(for: .valueChanged)
|
||||
let end = try button(in: dateSheet.view, identifier: "scenic.materials.date.end")
|
||||
end.sendActions(for: .touchUpInside)
|
||||
picker.setDate(day, animated: false)
|
||||
picker.sendActions(for: .valueChanged)
|
||||
let formatter = DateFormatter()
|
||||
formatter.calendar = model.calendar
|
||||
formatter.timeZone = model.calendar.timeZone
|
||||
formatter.locale = Locale(identifier: "zh_CN")
|
||||
formatter.dateFormat = "M 月 d 日"
|
||||
let selectedDay = formatter.string(from: day)
|
||||
try await settle(window) {
|
||||
self.visibleLabel(in: start, text: "开始日期") != nil && self.visibleLabel(in: start, text: selectedDay) != nil
|
||||
&& self.visibleLabel(in: end, text: "结束日期") != nil && self.visibleLabel(in: end, text: selectedDay) != nil
|
||||
}
|
||||
for (endpoint, title) in [(start, "开始日期"), (end, "结束日期")] {
|
||||
assertReachable(endpoint, window: window)
|
||||
for text in [title, selectedDay] {
|
||||
let label = try XCTUnwrap(visibleLabel(in: endpoint, text: text), "日期端点文字未渲染:\(text)")
|
||||
XCTAssertGreaterThan(label.bounds.width, 0)
|
||||
XCTAssertGreaterThan(label.bounds.height, 0)
|
||||
XCTAssertTrue(endpoint.bounds.contains(label.convert(label.bounds, to: endpoint)), "日期端点文字超出按钮:\(text)")
|
||||
}
|
||||
}
|
||||
XCTAssertNil(model.dateRange)
|
||||
XCTAssertEqual(model.selectedIDs, [hiddenID])
|
||||
assertLayout(in: dateSheet.view)
|
||||
capture(window, named: "空镜库-起止日期筛选")
|
||||
let confirm = try button(in: dateSheet.view, identifier: "scenic.materials.date.confirm")
|
||||
assertReachable(confirm, window: window)
|
||||
confirm.sendActions(for: .touchUpInside)
|
||||
try await settle(window) { controller.presentedViewController == nil && model.dateRange != nil }
|
||||
XCTAssertEqual(model.filteredGroups.map(\.id), expected.map(\.id))
|
||||
XCTAssertEqual(model.dateRange?.start, model.calendar.startOfDay(for: day))
|
||||
XCTAssertEqual(model.dateRange?.end, model.calendar.startOfDay(for: day))
|
||||
XCTAssertTrue(model.selectedIDs.isEmpty)
|
||||
capture(window, named: "空镜库-日期筛选结果")
|
||||
}
|
||||
|
||||
/// 预览从真实卡片打开并关闭,暂停中的选择和下载批次不受 Sheet 生命周期影响。
|
||||
func testPreviewOpenAndClosePreservesPausedBatchAndSelection() async throws {
|
||||
let model = ScenicMaterialsViewModel()
|
||||
model.applyScenario(.paused)
|
||||
let controller = ScenicMaterialsViewController(viewModel: model)
|
||||
let window = makeWindow(root: controller)
|
||||
defer { close(window) }
|
||||
_ = try await waitForLibrary(controller, window: window)
|
||||
let clipID = try XCTUnwrap(model.filteredGroups.first?.clips.first?.id)
|
||||
let selected = model.selectedIDs
|
||||
let token = model.batchID
|
||||
let completed = model.completedIDs
|
||||
let preview = try button(in: controller.view, identifier: "scenic.materials.preview.\(clipID)")
|
||||
assertReachable(preview, window: window)
|
||||
preview.sendActions(for: .touchUpInside)
|
||||
try await settle(window) { self.isPresentationSettled(controller, type: ScenicMaterialPreviewViewController.self) }
|
||||
let sheet = try XCTUnwrap(controller.presentedViewController as? ScenicMaterialPreviewViewController)
|
||||
assertLayout(in: sheet.view)
|
||||
capture(window, named: "空镜库-视频预览")
|
||||
let play = try button(in: sheet.view, identifier: "scenic.materials.preview.play")
|
||||
assertReachable(play, window: window)
|
||||
play.sendActions(for: .touchUpInside)
|
||||
try await settle(window) {
|
||||
self.allViews(in: sheet.view).compactMap { $0 as? UILabel }.contains { $0.text?.hasPrefix("正在播放 3 秒本地演示") == true }
|
||||
}
|
||||
XCTAssertEqual(model.batchID, token)
|
||||
XCTAssertEqual(model.phase, .paused)
|
||||
let closeButton = try button(in: sheet.view, identifier: "scenic.materials.preview.close")
|
||||
assertReachable(closeButton, window: window)
|
||||
closeButton.sendActions(for: .touchUpInside)
|
||||
try await settle(window) { controller.presentedViewController == nil && controller.navigationController?.transitionCoordinator == nil }
|
||||
XCTAssertEqual(model.selectedIDs, selected)
|
||||
XCTAssertEqual(model.batchID, token)
|
||||
XCTAssertEqual(model.completedIDs, completed)
|
||||
XCTAssertEqual(model.phase, .paused)
|
||||
}
|
||||
|
||||
/// 实际下载按钮驱动单段演示到完成,继续选择后保留成功状态且不重复下载。
|
||||
func testDownloadButtonCompletesLocalDemoAndKeepsSuccessfulClipUnavailable() async throws {
|
||||
let controller = ScenicMaterialsViewController()
|
||||
let window = makeWindow(root: controller)
|
||||
defer { close(window) }
|
||||
let model = controller.viewModel
|
||||
_ = try await waitForLibrary(controller, window: window)
|
||||
let clipID = try XCTUnwrap(model.filteredGroups.first?.clips.first?.id)
|
||||
try button(in: controller.view, identifier: "scenic.materials.select.\(clipID)").sendActions(for: .touchUpInside)
|
||||
try await settle(window) { model.selectedCount == 1 }
|
||||
let download = try button(in: controller.view, identifier: "scenic.materials.primary")
|
||||
assertReachable(download, window: window)
|
||||
XCTAssertTrue(download.isEnabled)
|
||||
download.sendActions(for: .touchUpInside)
|
||||
XCTAssertEqual(model.phase, .downloading)
|
||||
XCTAssertEqual(model.batchItemIDs, [clipID])
|
||||
XCTAssertTrue(model.isSelectionLocked)
|
||||
capture(window, named: "空镜库-本地下载演示")
|
||||
try await settle(window, timeout: 6) { model.phase == .completed }
|
||||
XCTAssertEqual(model.completedIDs, [clipID])
|
||||
XCTAssertEqual(model.completedCount, 1)
|
||||
XCTAssertTrue(allViews(in: controller.view).compactMap { $0 as? UILabel }.contains { $0.text?.contains("未写入系统相册") == true })
|
||||
assertLayout(in: controller.view)
|
||||
capture(window, named: "空镜库-下载演示完成")
|
||||
try button(in: controller.view, identifier: "scenic.materials.primary").sendActions(for: .touchUpInside)
|
||||
XCTAssertEqual(model.phase, .idle)
|
||||
XCTAssertNil(model.batchID)
|
||||
XCTAssertEqual(model.completedIDs, [clipID])
|
||||
XCTAssertFalse(model.canSelect(id: clipID))
|
||||
}
|
||||
|
||||
/// 后台作废旧下载令牌,回前台保持暂停,手动继续仅处理剩余素材。
|
||||
func testBackgroundPausesRejectsStaleCallbacksAndRequiresManualResume() async throws {
|
||||
let model = ScenicMaterialsViewModel()
|
||||
model.applyScenario(.paused)
|
||||
let controller = ScenicMaterialsViewController(viewModel: model)
|
||||
let window = makeWindow(root: controller)
|
||||
defer { close(window) }
|
||||
_ = try await waitForLibrary(controller, window: window)
|
||||
let completed = model.completedIDs
|
||||
let pending = try XCTUnwrap(model.pendingIDs.first)
|
||||
try button(in: controller.view, identifier: "scenic.materials.primary").sendActions(for: .touchUpInside)
|
||||
let oldToken = try XCTUnwrap(model.batchID)
|
||||
XCTAssertEqual(model.phase, .downloading)
|
||||
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
|
||||
let pausedToken = try XCTUnwrap(model.batchID)
|
||||
XCTAssertNotEqual(oldToken, pausedToken)
|
||||
XCTAssertEqual(model.phase, .paused)
|
||||
model.receive(.completed, clipID: pending, batchID: oldToken)
|
||||
XCTAssertEqual(model.completedIDs, completed)
|
||||
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||
try await Task.sleep(nanoseconds: 450_000_000)
|
||||
XCTAssertEqual(model.phase, .paused)
|
||||
XCTAssertEqual(model.batchID, pausedToken)
|
||||
XCTAssertEqual(model.completedIDs, completed)
|
||||
capture(window, named: "空镜库-后台暂停待继续")
|
||||
try button(in: controller.view, identifier: "scenic.materials.primary").sendActions(for: .touchUpInside)
|
||||
XCTAssertNotEqual(model.batchID, pausedToken)
|
||||
XCTAssertEqual(model.pendingIDs, [pending])
|
||||
XCTAssertEqual(model.completedIDs, completed)
|
||||
try await settle(window, timeout: 6) { model.phase == .completed }
|
||||
XCTAssertEqual(model.completedIDs, completed.union([pending]))
|
||||
}
|
||||
|
||||
/// 部分失败重试仅恢复失败段,已有成功段及批次顺序保持不变。
|
||||
func testRetryFailureOnlyRunsFailedClipAndPreservesSuccessfulDownloads() async throws {
|
||||
let model = ScenicMaterialsViewModel()
|
||||
model.applyScenario(.partialFailure)
|
||||
let controller = ScenicMaterialsViewController(viewModel: model)
|
||||
let window = makeWindow(root: controller)
|
||||
defer { close(window) }
|
||||
_ = try await waitForLibrary(controller, window: window)
|
||||
let completed = model.completedIDs
|
||||
let failed = model.failedIDs
|
||||
let originalItems = model.batchItemIDs
|
||||
XCTAssertEqual(completed.count, 1)
|
||||
XCTAssertEqual(failed.count, 1)
|
||||
capture(window, named: "空镜库-部分失败可重试")
|
||||
let retry = try button(in: controller.view, identifier: "scenic.materials.primary")
|
||||
assertReachable(retry, window: window)
|
||||
retry.sendActions(for: .touchUpInside)
|
||||
XCTAssertEqual(model.phase, .downloading)
|
||||
XCTAssertEqual(Set(model.pendingIDs), failed)
|
||||
XCTAssertEqual(model.batchItemIDs, originalItems)
|
||||
XCTAssertEqual(model.completedIDs, completed)
|
||||
XCTAssertTrue(model.failedIDs.isEmpty)
|
||||
XCTAssertTrue(model.isSelectionLocked)
|
||||
try await settle(window, timeout: 6) { model.phase == .completed }
|
||||
XCTAssertEqual(model.completedIDs, completed.union(failed))
|
||||
XCTAssertEqual(model.completedCount, originalItems.count)
|
||||
capture(window, named: "空镜库-失败重试完成")
|
||||
}
|
||||
|
||||
/// 演示权限不足时下载按钮只显示本地说明,不创建批次或触碰系统相册权限。
|
||||
func testDeniedDemoPermissionShowsExplanationWithoutStartingBatch() async throws {
|
||||
let controller = ScenicMaterialsViewController(isDemoPhotoPermissionAllowed: false)
|
||||
let window = makeWindow(root: controller)
|
||||
defer { close(window) }
|
||||
let model = controller.viewModel
|
||||
_ = try await waitForLibrary(controller, window: window)
|
||||
let clipID = try XCTUnwrap(model.filteredGroups.first?.clips.first?.id)
|
||||
try button(in: controller.view, identifier: "scenic.materials.select.\(clipID)").sendActions(for: .touchUpInside)
|
||||
try await settle(window) { model.selectedCount == 1 }
|
||||
try button(in: controller.view, identifier: "scenic.materials.primary").sendActions(for: .touchUpInside)
|
||||
try await settle(window) { self.isPresentationSettled(controller, type: UIAlertController.self) }
|
||||
let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController)
|
||||
XCTAssertEqual(alert.title, "需要相册保存权限")
|
||||
XCTAssertTrue(alert.message?.contains("演示") == true)
|
||||
XCTAssertEqual(alert.actions.count, 2)
|
||||
XCTAssertNil(model.batchID)
|
||||
XCTAssertEqual(model.phase, .idle)
|
||||
XCTAssertEqual(model.selectedIDs, [clipID])
|
||||
capture(window, named: "空镜库-相册权限演示说明")
|
||||
alert.dismiss(animated: false)
|
||||
try await settle(window) { controller.presentedViewController == nil }
|
||||
XCTAssertNil(model.batchID)
|
||||
}
|
||||
|
||||
private func makeWindow(root controller: UIViewController) -> UIWindow {
|
||||
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
|
||||
let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first
|
||||
previousKeyWindow = scene?.windows.first { $0.isKeyWindow }
|
||||
let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds)
|
||||
window.frame = scene?.coordinateSpace.bounds ?? UIScreen.main.bounds
|
||||
window.overrideUserInterfaceStyle = .light
|
||||
window.rootViewController = controller is UINavigationController ? controller : UINavigationController(rootViewController: controller)
|
||||
window.makeKeyAndVisible()
|
||||
window.layoutIfNeeded()
|
||||
return window
|
||||
}
|
||||
|
||||
private func close(_ window: UIWindow) {
|
||||
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
|
||||
window.endEditing(true)
|
||||
window.rootViewController?.dismiss(animated: false)
|
||||
window.isHidden = true
|
||||
window.rootViewController = nil
|
||||
previousKeyWindow?.makeKeyAndVisible()
|
||||
}
|
||||
|
||||
private func waitForLibrary(_ controller: ScenicMaterialsViewController, window: UIWindow) async throws -> UICollectionView {
|
||||
let list = try XCTUnwrap(find(in: controller.view, identifier: "scenic.materials.list") as? UICollectionView)
|
||||
try await settle(window) { list.numberOfSections > 2 && list.cellForItem(at: IndexPath(item: 0, section: 1)) != nil }
|
||||
return list
|
||||
}
|
||||
|
||||
private func showGroupHeader(section: Int, list: UICollectionView, window: UIWindow) async throws {
|
||||
let path = IndexPath(item: 0, section: section)
|
||||
let attributes = try XCTUnwrap(list.collectionViewLayout.layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: path))
|
||||
list.setContentOffset(CGPoint(x: 0, y: max(-list.adjustedContentInset.top, attributes.frame.minY - 4)), animated: false)
|
||||
try await settle(window) { list.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: path) != nil }
|
||||
}
|
||||
|
||||
private func isPresentationSettled<T: UIViewController>(_ presenter: UIViewController, type: T.Type) -> Bool {
|
||||
guard let presented = presenter.presentedViewController as? T else { return false }
|
||||
return !presented.isBeingPresented && presented.transitionCoordinator == nil && presented.view.window != nil
|
||||
}
|
||||
|
||||
private func settle(_ window: UIWindow, timeout: TimeInterval = 4, condition: () -> Bool) async throws {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
while Date() < deadline {
|
||||
window.layoutIfNeeded()
|
||||
window.rootViewController?.view.layoutIfNeeded()
|
||||
if condition() {
|
||||
try await Task.sleep(nanoseconds: 300_000_000)
|
||||
window.layoutIfNeeded()
|
||||
return
|
||||
}
|
||||
try await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
XCTFail("空镜库 UI 未在限定时间内进入预期状态")
|
||||
}
|
||||
|
||||
private func allViews(in root: UIView) -> [UIView] { [root] + root.subviews.flatMap { allViews(in: $0) } }
|
||||
|
||||
private func find(in root: UIView, identifier: String) -> UIView? {
|
||||
allViews(in: root).first { $0.accessibilityIdentifier == identifier }
|
||||
}
|
||||
|
||||
private func button(in root: UIView, identifier: String) throws -> UIButton {
|
||||
try XCTUnwrap(find(in: root, identifier: identifier) as? UIButton, "缺少按钮 \(identifier)")
|
||||
}
|
||||
|
||||
private func isHiddenByAncestor(_ view: UIView) -> Bool {
|
||||
view.isHidden || view.alpha < 0.01 || (view.superview.map { isHiddenByAncestor($0) } ?? false)
|
||||
}
|
||||
|
||||
private func visibleLabel(in root: UIView, text: String) -> UILabel? {
|
||||
allViews(in: root).compactMap { $0 as? UILabel }.first {
|
||||
($0.text ?? $0.attributedText?.string) == text && !isHiddenByAncestor($0)
|
||||
&& !$0.bounds.isEmpty && $0.convert($0.bounds, to: root).intersects(root.bounds)
|
||||
}
|
||||
}
|
||||
|
||||
private func assertReachable(_ view: UIView, window: UIWindow, file: StaticString = #filePath, line: UInt = #line) {
|
||||
XCTAssertFalse(view.bounds.isEmpty, file: file, line: line)
|
||||
XCTAssertFalse(isHiddenByAncestor(view), file: file, line: line)
|
||||
let center = view.convert(CGPoint(x: view.bounds.midX, y: view.bounds.midY), to: window)
|
||||
XCTAssertTrue(window.bounds.contains(center), "控件超出窗口:\(view.accessibilityIdentifier ?? "")", file: file, line: line)
|
||||
let hit = window.hitTest(center, with: nil)
|
||||
XCTAssertTrue(hit === view || hit?.isDescendant(of: view) == true,
|
||||
"控件被遮挡:\(view.accessibilityIdentifier ?? "")", file: file, line: line)
|
||||
}
|
||||
|
||||
private func assertLayout(in root: UIView, file: StaticString = #filePath, line: UInt = #line) {
|
||||
let ambiguous = allViews(in: root).filter {
|
||||
!isHiddenByAncestor($0) && !$0.bounds.isEmpty && $0.convert($0.bounds, to: root).intersects(root.bounds)
|
||||
&& !$0.translatesAutoresizingMaskIntoConstraints && !String(describing: type(of: $0)).hasPrefix("_") && $0.hasAmbiguousLayout
|
||||
}
|
||||
XCTAssertTrue(ambiguous.isEmpty, "布局歧义:\(ambiguous.map { String(describing: type(of: $0)) + " " + ($0.accessibilityIdentifier ?? "") })", file: file, line: line)
|
||||
}
|
||||
|
||||
/// 真机截图保存在 xcresult 及应用临时目录,便于导出视觉证据。
|
||||
private func capture(_ window: UIWindow, named name: String) {
|
||||
window.layoutIfNeeded()
|
||||
let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in
|
||||
window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
|
||||
}
|
||||
let attachment = XCTAttachment(image: image)
|
||||
attachment.name = name
|
||||
attachment.lifetime = .keepAlways
|
||||
add(attachment)
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("scenic-materials-ui-proof", isDirectory: true)
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
try image.pngData()?.write(to: directory.appendingPathComponent(name + ".png"), options: .atomic)
|
||||
} catch {
|
||||
XCTFail("空镜库截图临时文件写入失败:\(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,365 @@
|
||||
import XCTest
|
||||
@testable import suixinkan
|
||||
|
||||
/// 验证独立空镜库的完整分组、日期范围和本机演示下载状态,不访问真实订单、相册或网络。
|
||||
final class ScenicMaterialsViewModelTests: XCTestCase {
|
||||
/// 演示库包含两条有素材航线和一条空航线,同一航线按拍摄时间倒序排列。
|
||||
func testDemoLibraryGroupsRoutesAndDatesIndependentlyOfOrders() {
|
||||
let model = makeModel()
|
||||
XCTAssertEqual(model.routes.count, 3)
|
||||
XCTAssertEqual(model.filteredGroups.map { $0.clips.count }, [5, 6, 3, 4, 5])
|
||||
XCTAssertEqual(model.filteredClips.count, 23)
|
||||
XCTAssertEqual(model.filteredGroups.prefix(3).map(\.routeID), Array(repeating: model.routes[0].id, count: 3))
|
||||
XCTAssertGreaterThan(model.filteredGroups[0].capturedAt, model.filteredGroups[1].capturedAt)
|
||||
XCTAssertEqual(model.capturedAtText(for: model.filteredGroups[0]), "10-23 17:20")
|
||||
XCTAssertEqual(model.minimumDate, date(2026, 7, 29))
|
||||
XCTAssertEqual(model.maximumDate, date(2026, 10, 26))
|
||||
XCTAssertEqual(model.routeFilterTitle, "全部航线")
|
||||
XCTAssertEqual(model.dateFilterTitle, "全部时间")
|
||||
}
|
||||
|
||||
/// 整组选择必须包含默认折叠的第六段,展开收起不增减选择。
|
||||
func testSelectWholeGroupIncludesCollapsedSixthClip() throws {
|
||||
let model = makeModel()
|
||||
let group = try XCTUnwrap(model.filteredGroups.first { $0.clips.count == 6 })
|
||||
XCTAssertEqual(model.visibleClips(in: group).count, 5)
|
||||
model.toggleGroup(id: group.id)
|
||||
XCTAssertEqual(model.selectedIDs, Set(group.clips.map(\.id)))
|
||||
XCTAssertEqual(model.selectedCount, 6)
|
||||
XCTAssertTrue(model.isGroupSelected(id: group.id))
|
||||
model.toggleExpandedGroup(id: group.id)
|
||||
XCTAssertEqual(model.visibleClips(in: group).count, 6)
|
||||
XCTAssertTrue(model.selectedIDs.contains(group.clips[5].id))
|
||||
model.toggleExpandedGroup(id: group.id)
|
||||
XCTAssertEqual(model.visibleClips(in: group).count, 5)
|
||||
XCTAssertEqual(model.selectedCount, 6)
|
||||
model.toggleGroup(id: group.id)
|
||||
XCTAssertTrue(model.selectedIDs.isEmpty)
|
||||
}
|
||||
|
||||
/// 不可用片段不能预览下载或被全组选中,空组也不表现为已全选。
|
||||
func testUnavailableClipsAreExcludedFromSelectionAndBatch() throws {
|
||||
let route = ScenicMaterialRoute(id: "r", name: "测试航线")
|
||||
let good = clip(id: "good", groupID: "g")
|
||||
let unavailable = clip(id: "unavailable", groupID: "g", available: false)
|
||||
let group = ScenicMaterialGroup(id: "g", routeID: route.id, capturedAt: date(2026, 10, 25), clips: [good, unavailable])
|
||||
let model = makeModel(routes: [route], groups: [group])
|
||||
model.toggleSelection(id: unavailable.id)
|
||||
model.toggleSelection(id: "unknown")
|
||||
XCTAssertTrue(model.selectedIDs.isEmpty)
|
||||
XCTAssertFalse(model.canSelect(id: unavailable.id))
|
||||
XCTAssertEqual(model.downloadState(for: unavailable.id), .unavailable)
|
||||
model.toggleGroup(id: group.id)
|
||||
XCTAssertEqual(model.selectedIDs, [good.id])
|
||||
XCTAssertTrue(model.isGroupSelected(id: group.id))
|
||||
XCTAssertFalse(model.isGroupSelected(id: "unknown"))
|
||||
XCTAssertTrue(model.startDownload())
|
||||
XCTAssertEqual(model.batchItemIDs, [good.id])
|
||||
let token = try XCTUnwrap(model.batchID)
|
||||
model.receive(.completed, clipID: unavailable.id, batchID: token)
|
||||
XCTAssertEqual(model.completedCount, 0)
|
||||
}
|
||||
|
||||
/// 切换航线移除隐藏选择,不把不可见素材带入下一次下载。
|
||||
func testChangingRoutePrunesHiddenSelectionAndUnknownRouteIsRejected() throws {
|
||||
let model = makeModel()
|
||||
let firstRouteGroup = model.filteredGroups[0]
|
||||
let secondRouteGroup = try XCTUnwrap(model.filteredGroups.first { $0.routeID == model.routes[1].id })
|
||||
model.toggleSelection(id: firstRouteGroup.clips[0].id)
|
||||
model.toggleSelection(id: secondRouteGroup.clips[0].id)
|
||||
XCTAssertEqual(model.selectedCount, 2)
|
||||
XCTAssertTrue(model.setRoute(id: model.routes[1].id))
|
||||
XCTAssertEqual(model.selectedIDs, [secondRouteGroup.clips[0].id])
|
||||
XCTAssertTrue(model.filteredGroups.allSatisfy { $0.routeID == model.routes[1].id })
|
||||
XCTAssertFalse(model.setRoute(id: "missing-route"))
|
||||
XCTAssertEqual(model.selectedRouteID, model.routes[1].id)
|
||||
model.resetFilters()
|
||||
XCTAssertEqual(model.filteredGroups.count, 5)
|
||||
XCTAssertEqual(model.selectedIDs, [secondRouteGroup.clips[0].id])
|
||||
}
|
||||
|
||||
/// 日期按同一时区的日历日计算,包含首尾日全部时刻。
|
||||
func testDateRangeIncludesBothBoundaryDaysAndPrunesHiddenSelection() {
|
||||
let model = makeModel()
|
||||
model.toggleSelection(id: model.filteredGroups[4].clips[0].id)
|
||||
model.toggleSelection(id: model.filteredGroups[0].clips[0].id)
|
||||
XCTAssertTrue(model.setDateRange(start: date(2026, 10, 22, 12), end: date(2026, 10, 23, 8)))
|
||||
XCTAssertEqual(model.dateRange, ScenicMaterialDateRange(start: date(2026, 10, 22), end: date(2026, 10, 23)))
|
||||
XCTAssertEqual(model.filteredGroups.count, 4)
|
||||
XCTAssertEqual(model.selectedCount, 1)
|
||||
XCTAssertEqual(model.dateFilterTitle, "10.22 – 10.23")
|
||||
XCTAssertTrue(model.setDateRange(start: date(2026, 10, 23), end: date(2026, 10, 23)))
|
||||
XCTAssertEqual(model.filteredGroups.count, 3)
|
||||
XCTAssertEqual(model.dateFilterTitle, "10.23")
|
||||
XCTAssertTrue(model.setDateRange(start: nil, end: nil))
|
||||
XCTAssertEqual(model.filteredGroups.count, 5)
|
||||
}
|
||||
|
||||
/// 保留期外及未来批次不进入列表,即使没有手动设置日期筛选也不可选择。
|
||||
func testRetentionWindowIncludesFirstAndLastDayAndExcludesOutsideDates() {
|
||||
let route = ScenicMaterialRoute(id: "route", name: "保留期航线")
|
||||
let groups = [
|
||||
group(id: "expired", routeID: route.id, capturedAt: date(2026, 7, 28, 23)),
|
||||
group(id: "first-day", routeID: route.id, capturedAt: date(2026, 7, 29, 0)),
|
||||
group(id: "today", routeID: route.id, capturedAt: date(2026, 10, 26, 23)),
|
||||
group(id: "future", routeID: route.id, capturedAt: date(2026, 10, 27))
|
||||
]
|
||||
let model = makeModel(routes: [route], groups: groups)
|
||||
XCTAssertEqual(model.filteredGroups.map(\.id), ["today", "first-day"])
|
||||
XCTAssertFalse(model.canSelect(id: "expired-clip"))
|
||||
XCTAssertFalse(model.canSelect(id: "future-clip"))
|
||||
XCTAssertTrue(model.setDateRange(start: model.minimumDate, end: model.maximumDate))
|
||||
XCTAssertEqual(model.filteredGroups.count, 2)
|
||||
}
|
||||
|
||||
/// 反向、未来、保留期外和不完整日期不会悄悄改变已应用的有效筛选。
|
||||
func testInvalidDateRangesKeepPreviouslyAppliedRange() throws {
|
||||
let model = makeModel()
|
||||
XCTAssertTrue(model.setDateRange(start: date(2026, 10, 22), end: date(2026, 10, 23)))
|
||||
let original = try XCTUnwrap(model.dateRange)
|
||||
XCTAssertFalse(model.setDateRange(start: date(2026, 10, 24), end: date(2026, 10, 23)))
|
||||
XCTAssertFalse(model.setDateRange(start: date(2026, 7, 28), end: date(2026, 10, 23)))
|
||||
XCTAssertFalse(model.setDateRange(start: date(2026, 10, 23), end: date(2026, 10, 27)))
|
||||
XCTAssertFalse(model.setDateRange(start: nil, end: date(2026, 10, 23)))
|
||||
XCTAssertFalse(model.setDateRange(start: date(2026, 10, 23), end: nil))
|
||||
XCTAssertEqual(model.dateRange, original)
|
||||
}
|
||||
|
||||
/// 航线和日期共同生效,筛选空结果能恢复完整库而不改写源数据。
|
||||
func testCombinedFiltersAndResetRecoverNoResults() {
|
||||
let model = makeModel()
|
||||
XCTAssertTrue(model.setRoute(id: model.routes[1].id))
|
||||
XCTAssertTrue(model.setDateRange(start: date(2026, 10, 22), end: date(2026, 10, 22)))
|
||||
XCTAssertTrue(model.filteredGroups.isEmpty)
|
||||
XCTAssertEqual(model.emptyTitle, "没有符合条件的素材")
|
||||
model.resetFilters()
|
||||
XCTAssertEqual(model.filteredGroups.count, 5)
|
||||
XCTAssertNil(model.selectedRouteID)
|
||||
XCTAssertNil(model.dateRange)
|
||||
}
|
||||
|
||||
/// 开始下载冻结已选完整范围;选择和筛选无效,展开收起仍可浏览。
|
||||
func testRunningBatchFreezesSelectionAndFiltersButAllowsExpansion() throws {
|
||||
let model = makeModel()
|
||||
let group = try XCTUnwrap(model.filteredGroups.first { $0.clips.count == 6 })
|
||||
model.toggleGroup(id: group.id)
|
||||
XCTAssertTrue(model.startDownload())
|
||||
let original = model.batchItemIDs
|
||||
let token = try XCTUnwrap(model.batchID)
|
||||
XCTAssertTrue(model.isSelectionLocked)
|
||||
XCTAssertFalse(model.canStartDownload)
|
||||
XCTAssertFalse(model.startDownload())
|
||||
XCTAssertFalse(model.setRoute(id: model.routes[2].id))
|
||||
XCTAssertFalse(model.setDateRange(start: model.maximumDate, end: model.maximumDate))
|
||||
model.toggleGroup(id: group.id)
|
||||
model.toggleSelection(id: group.clips[0].id)
|
||||
model.resetFilters()
|
||||
model.toggleExpandedGroup(id: group.id)
|
||||
XCTAssertEqual(model.visibleClips(in: group).count, 6)
|
||||
XCTAssertEqual(model.selectedIDs, Set(original))
|
||||
XCTAssertEqual(model.batchItemIDs, original)
|
||||
XCTAssertEqual(model.batchID, token)
|
||||
XCTAssertNil(model.selectedRouteID)
|
||||
XCTAssertNil(model.dateRange)
|
||||
}
|
||||
|
||||
/// 失败回执只结束该项,所有项有结果后才显示部分失败;重试不重复成功项。
|
||||
func testPartialFailureRetryKeepsSuccessfulItemsAndRejectsOldCallbacks() throws {
|
||||
let model = makeModel()
|
||||
let clips = Array(model.filteredClips.prefix(3))
|
||||
clips.forEach { model.toggleSelection(id: $0.id) }
|
||||
XCTAssertTrue(model.startDownload())
|
||||
let oldToken = try XCTUnwrap(model.batchID)
|
||||
model.receive(.completed, clipID: clips[0].id, batchID: oldToken)
|
||||
model.receive(.failed, clipID: clips[1].id, batchID: oldToken)
|
||||
XCTAssertEqual(model.phase, .downloading)
|
||||
XCTAssertEqual(model.pendingIDs, [clips[2].id])
|
||||
model.receive(.completed, clipID: clips[2].id, batchID: oldToken)
|
||||
XCTAssertEqual(model.phase, .partialFailure)
|
||||
XCTAssertEqual(model.completedCount, 2)
|
||||
XCTAssertEqual(model.failedCount, 1)
|
||||
XCTAssertEqual(model.selectedIDs, [clips[1].id])
|
||||
XCTAssertTrue(model.retryFailedDownloads())
|
||||
let newToken = try XCTUnwrap(model.batchID)
|
||||
XCTAssertNotEqual(newToken, oldToken)
|
||||
XCTAssertEqual(model.totalCount, 3)
|
||||
XCTAssertEqual(model.pendingIDs, [clips[1].id])
|
||||
model.receive(.completed, clipID: clips[1].id, batchID: oldToken)
|
||||
XCTAssertEqual(model.completedCount, 2)
|
||||
model.receive(.failed, clipID: clips[0].id, batchID: newToken)
|
||||
XCTAssertEqual(model.completedCount, 2)
|
||||
model.receive(.completed, clipID: clips[1].id, batchID: newToken)
|
||||
XCTAssertEqual(model.phase, .completed)
|
||||
XCTAssertEqual(model.completedCount, 3)
|
||||
XCTAssertEqual(model.downloadProgress, 1)
|
||||
XCTAssertTrue(model.selectedIDs.isEmpty)
|
||||
}
|
||||
|
||||
/// 暂停作废旧令牌;没有主动继续就保持暂停,继续仅处理尚未完成项。
|
||||
func testPauseResumeInvalidatesCallbacksAndPreservesCompletedFiles() throws {
|
||||
let model = makeModel()
|
||||
model.applyScenario(.selected)
|
||||
XCTAssertTrue(model.startDownload())
|
||||
let original = model.batchItemIDs
|
||||
let oldToken = try XCTUnwrap(model.batchID)
|
||||
model.receive(.completed, clipID: original[0], batchID: oldToken)
|
||||
model.receive(.progress(0.65), clipID: original[1], batchID: oldToken)
|
||||
model.pauseDownload()
|
||||
let pausedToken = try XCTUnwrap(model.batchID)
|
||||
XCTAssertNotEqual(pausedToken, oldToken)
|
||||
XCTAssertEqual(model.phase, .paused)
|
||||
XCTAssertEqual(model.downloadState(for: original[1]), .paused)
|
||||
model.receive(.completed, clipID: original[1], batchID: oldToken)
|
||||
model.receive(.completed, clipID: original[1], batchID: pausedToken)
|
||||
XCTAssertEqual(model.phase, .paused)
|
||||
XCTAssertEqual(model.completedCount, 1)
|
||||
XCTAssertFalse(model.setRoute(id: model.routes[1].id))
|
||||
XCTAssertTrue(model.continueDownload())
|
||||
XCTAssertNotEqual(model.batchID, pausedToken)
|
||||
XCTAssertEqual(model.pendingIDs, [original[1]])
|
||||
XCTAssertEqual(model.progressByID[original[1]], 0)
|
||||
XCTAssertEqual(model.completedCount, 1)
|
||||
}
|
||||
|
||||
/// 取消后旧回调失效,仅成功项保留,新批次不会把已成功文件重新下载。
|
||||
func testCancelPreservesOnlySuccessAndNewBatchExcludesCompleted() throws {
|
||||
let model = makeModel()
|
||||
let group = model.filteredGroups[0]
|
||||
model.toggleGroup(id: group.id)
|
||||
XCTAssertTrue(model.startDownload())
|
||||
let token = try XCTUnwrap(model.batchID)
|
||||
let successfulID = group.clips[0].id
|
||||
model.receive(.completed, clipID: successfulID, batchID: token)
|
||||
model.receive(.failed, clipID: group.clips[1].id, batchID: token)
|
||||
model.cancelDownload()
|
||||
XCTAssertEqual(model.phase, .idle)
|
||||
XCTAssertNil(model.batchID)
|
||||
XCTAssertTrue(model.selectedIDs.isEmpty)
|
||||
XCTAssertTrue(model.failedIDs.isEmpty)
|
||||
XCTAssertEqual(model.completedIDs, [successfulID])
|
||||
model.receive(.completed, clipID: group.clips[2].id, batchID: token)
|
||||
XCTAssertEqual(model.completedIDs, [successfulID])
|
||||
model.toggleGroup(id: group.id)
|
||||
XCTAssertEqual(model.selectedCount, 4)
|
||||
XCTAssertFalse(model.selectedIDs.contains(successfulID))
|
||||
XCTAssertTrue(model.startDownload())
|
||||
XCTAssertEqual(model.totalCount, 4)
|
||||
XCTAssertFalse(model.batchItemIDs.contains(successfulID))
|
||||
}
|
||||
|
||||
/// 进度不能倒退或被非有限值污染,重复终态不会把成功改回失败。
|
||||
func testProgressClampsAndTerminalCallbacksCannotRegressSuccess() throws {
|
||||
let model = makeModel()
|
||||
let id = model.filteredClips[0].id
|
||||
model.toggleSelection(id: id)
|
||||
XCTAssertTrue(model.startDownload())
|
||||
let token = try XCTUnwrap(model.batchID)
|
||||
model.receive(.progress(0.8), clipID: id, batchID: token)
|
||||
model.receive(.progress(0.3), clipID: id, batchID: token)
|
||||
model.receive(.progress(.nan), clipID: id, batchID: token)
|
||||
model.receive(.progress(.infinity), clipID: id, batchID: token)
|
||||
XCTAssertEqual(model.progressByID[id], 0.8)
|
||||
model.receive(.progress(2), clipID: id, batchID: token)
|
||||
XCTAssertEqual(model.progressByID[id], 1)
|
||||
XCTAssertEqual(model.phase, .downloading)
|
||||
model.receive(.completed, clipID: id, batchID: token)
|
||||
model.receive(.failed, clipID: id, batchID: token)
|
||||
model.receive(.progress(0.1), clipID: id, batchID: token)
|
||||
XCTAssertEqual(model.downloadState(for: id), .completed)
|
||||
XCTAssertEqual(model.phase, .completed)
|
||||
XCTAssertEqual(model.failedCount, 0)
|
||||
}
|
||||
|
||||
/// 完成后手动继续选择解锁筛选,但保留已经完成的本地演示标记。
|
||||
func testContinueSelectingKeepsCompletedHistoryAndUnlocksFilters() {
|
||||
let model = makeModel()
|
||||
model.applyScenario(.completed)
|
||||
let completed = model.completedIDs
|
||||
XCTAssertEqual(model.phase, .completed)
|
||||
XCTAssertEqual(model.completedCount, 2)
|
||||
XCTAssertTrue(model.isSelectionLocked)
|
||||
model.continueSelecting()
|
||||
XCTAssertEqual(model.phase, .idle)
|
||||
XCTAssertFalse(model.isSelectionLocked)
|
||||
XCTAssertEqual(model.completedIDs, completed)
|
||||
XCTAssertTrue(model.setRoute(id: model.routes[1].id))
|
||||
XCTAssertEqual(model.totalCount, 0)
|
||||
}
|
||||
|
||||
/// 正在执行和暂停中的批次不能通过继续选择绕过取消/恢复。
|
||||
func testContinueSelectingDoesNotDiscardActiveOrPausedBatch() throws {
|
||||
let model = makeModel()
|
||||
model.applyScenario(.downloading)
|
||||
let token = try XCTUnwrap(model.batchID)
|
||||
model.continueSelecting()
|
||||
XCTAssertEqual(model.phase, .downloading)
|
||||
XCTAssertEqual(model.batchID, token)
|
||||
model.pauseDownload()
|
||||
let paused = model.batchID
|
||||
model.continueSelecting()
|
||||
XCTAssertEqual(model.phase, .paused)
|
||||
XCTAssertEqual(model.batchID, paused)
|
||||
}
|
||||
|
||||
/// 空库与筛选空结果可分别演示,恢复正常时不保留上一演示状态。
|
||||
func testScenariosResetScopeAndSeparateEmptyLibraryFromNoResults() {
|
||||
let model = makeModel()
|
||||
model.applyScenario(.empty)
|
||||
XCTAssertEqual(model.emptyTitle, "暂无景区素材")
|
||||
XCTAssertTrue(model.allGroups.isEmpty)
|
||||
XCTAssertFalse(model.hasAnyMaterials)
|
||||
XCTAssertTrue(model.setRoute(id: model.routes[0].id))
|
||||
XCTAssertEqual(model.emptyTitle, "暂无景区素材")
|
||||
model.applyScenario(.noResults)
|
||||
XCTAssertEqual(model.allGroups.count, 5)
|
||||
XCTAssertTrue(model.filteredGroups.isEmpty)
|
||||
XCTAssertTrue(model.hasAnyMaterials)
|
||||
XCTAssertNotNil(model.selectedRouteID)
|
||||
XCTAssertEqual(model.emptyTitle, "没有符合条件的素材")
|
||||
model.applyScenario(.normal)
|
||||
XCTAssertEqual(model.filteredGroups.count, 5)
|
||||
XCTAssertNil(model.selectedRouteID)
|
||||
XCTAssertEqual(model.phase, .idle)
|
||||
XCTAssertTrue(model.completedIDs.isEmpty)
|
||||
}
|
||||
|
||||
/// 不同账号/景区的素材身份与下载状态不串用,不需要拍摄订单才能初始化。
|
||||
func testIndependentContextsDoNotShareMaterialIDsOrDownloadState() {
|
||||
let first = makeModel(context: ScenicMaterialContext(userID: "u1", scenicID: "s1", scenicName: "甲景区"))
|
||||
let second = makeModel(context: ScenicMaterialContext(userID: "u1", scenicID: "s2", scenicName: "乙景区"))
|
||||
let otherUser = makeModel(context: ScenicMaterialContext(userID: "u2", scenicID: "s1", scenicName: "甲景区"))
|
||||
first.applyScenario(.completed)
|
||||
XCTAssertEqual(first.completedIDs.count, 2)
|
||||
XCTAssertTrue(second.completedIDs.isEmpty)
|
||||
XCTAssertTrue(otherUser.completedIDs.isEmpty)
|
||||
XCTAssertTrue(Set(first.filteredClips.map(\.id)).isDisjoint(with: Set(second.filteredClips.map(\.id))))
|
||||
XCTAssertTrue(Set(first.filteredClips.map(\.id)).isDisjoint(with: Set(otherUser.filteredClips.map(\.id))))
|
||||
second.toggleSelection(id: first.filteredClips[0].id)
|
||||
XCTAssertEqual(second.selectedCount, 0)
|
||||
}
|
||||
|
||||
private func makeModel(context: ScenicMaterialContext = .demo, routes: [ScenicMaterialRoute]? = nil,
|
||||
groups: [ScenicMaterialGroup]? = nil) -> ScenicMaterialsViewModel {
|
||||
ScenicMaterialsViewModel(context: context, now: date(2026, 10, 26, 14), calendar: calendar, routes: routes, groups: groups)
|
||||
}
|
||||
|
||||
private var calendar: Calendar {
|
||||
var value = Calendar(identifier: .gregorian)
|
||||
value.timeZone = TimeZone(secondsFromGMT: 8 * 3_600)!
|
||||
value.locale = Locale(identifier: "zh_CN")
|
||||
return value
|
||||
}
|
||||
|
||||
private func date(_ year: Int, _ month: Int, _ day: Int, _ hour: Int = 0) -> Date {
|
||||
calendar.date(from: DateComponents(year: year, month: month, day: day, hour: hour))!
|
||||
}
|
||||
|
||||
private func clip(id: String, groupID: String, available: Bool = true) -> ScenicMaterialClip {
|
||||
ScenicMaterialClip(id: id, groupID: groupID, ordinal: 1, durationSeconds: 28, fileSizeBytes: 178_000_000,
|
||||
resolution: "4K", coverAssetName: "drone_demo_mountain", isAvailable: available)
|
||||
}
|
||||
|
||||
private func group(id: String, routeID: String, capturedAt: Date) -> ScenicMaterialGroup {
|
||||
ScenicMaterialGroup(id: id, routeID: routeID, capturedAt: capturedAt, clips: [clip(id: "\(id)-clip", groupID: id)])
|
||||
}
|
||||
}
|
||||