feat: 完善机巢任务状态展示与景区空境库入口

拍摄任务刷新时保留上次成功数据,失败状态按产品网页展示原因和不可召唤提示;新增受权限控制的景区空境库入口,使用当前景区空态。同步测试与接口说明。

验证:模拟器机巢相关 65 项测试、空境库及首页菜单相关 30 项测试通过。
This commit is contained in:
2026-10-29 17:47:28 +08:00
parent 1173207756
commit e827bf8725
18 changed files with 1055 additions and 98 deletions
@@ -75,11 +75,14 @@ struct DroneDockShootingTaskIdentity: Decodable, Equatable, Sendable {
let waylineStatus: Int?
/// 服务端航线状态文案;执行失败优先于笼统的订单任务执行中。
let waylineStatusLabel: String?
/// 服务端实际记录的任务结果原因,空值不视为具体失败说明。
let resultMessage: String?
/// 已确认嵌套任务字段映射。
private enum CodingKeys: String, CodingKey {
case id, orderNumber = "order_number", scenicID = "scenic_id", status, statusLabel = "status_label"
case waylineStatus = "wayline_status", waylineStatusLabel = "wayline_status_label"
case resultMessage = "result_message"
}
}
@@ -142,6 +145,10 @@ struct DroneDockShootingPlane: Decodable, Equatable, Sendable {
let id: Int?
/// 当前设备序列号。
let snNumber: String?
/// 服务端连接状态;实测 2 为离线,不从电量推导连接状态。
let onlineStatus: Int?
/// 文档工作状态:0 离线、1 空闲、2 拍摄中;不据此推断返航完成。
let workStatus: Int?
/// 服务端工作状态文案。
let workStatusLabel: String?
/// 服务端完整状态文案。
@@ -150,6 +157,7 @@ struct DroneDockShootingPlane: Decodable, Equatable, Sendable {
/// 当前设备字段映射。
private enum CodingKeys: String, CodingKey {
case id, snNumber = "sn_number", workStatusLabel = "work_status_label", statusText = "status_text"
case onlineStatus = "online_status", workStatus = "work_status"
}
}
@@ -34,6 +34,8 @@ enum DroneDockTaskDisplayAction: Equatable, Sendable {
case start
/// 恢复拍摄占位动作,本轮禁用。
case resume
/// 失败后的重新召唤占位动作;尚未接入重新准备流程,始终禁用。
case retry
/// 查看已明确完成任务的订单素材。
case materials
/// 当前无主动作。
@@ -54,6 +56,21 @@ struct DroneDockTaskPresentation: Equatable, Sendable {
let action: DroneDockTaskDisplayAction
/// 主动作名称,无动作时为 nil。
let actionTitle: String?
/// 是否可触发动作;未对接的开始和恢复始终为 false。
/// 是否可触发动作;未对接的开始、恢复和重新召唤始终为 false。
let isActionEnabled: Bool
/// 主动作下方的真实设备限制说明,未提供时不展示。
let actionNote: String?
/// 创建状态展示;动作提示默认为空,既有非失败状态保持原布局。
init(phase: DroneDockTaskDisplayPhase, title: String, message: String, deviceStatus: String,
action: DroneDockTaskDisplayAction, actionTitle: String?, isActionEnabled: Bool, actionNote: String? = nil) {
self.phase = phase
self.title = title
self.message = message
self.deviceStatus = deviceStatus
self.action = action
self.actionTitle = actionTitle
self.isActionEnabled = isActionEnabled
self.actionNote = actionNote
}
}
@@ -8,7 +8,7 @@ final class DroneDockShootingTaskViewModel {
let taskID: Int
/// 进入页面携带的订单摘要,仅作未返回展示字段时的订单文案备用。
let order: DroneDockHomeOrder
/// 当前通过身份检查的服务端快照。
/// 最近一次通过身份检查的服务端快照,刷新期间保留,成功后整体替换。
private(set) var response: DroneDockShootingResponse?
/// 同一页面最多存在一个读取请求。
private(set) var isLoading = false
@@ -31,7 +31,7 @@ final class DroneDockShootingTaskViewModel {
self.currentContext = currentContext
}
/// 页面可见时读取同一任务;失败、取消或身份失效不沿用之前的执行门禁与读数。
/// 页面可见时读取同一任务;刷新及普通失败保留旧快照,身份失效立即清除。
@MainActor
func refresh() async {
guard !isLoading, !identityInvalidated else { return }
@@ -39,16 +39,15 @@ final class DroneDockShootingTaskViewModel {
let requestGeneration = generation
isLoading = true
errorMessage = nil
response = nil
defer {
if generation == requestGeneration {
isLoading = false
if Task.isCancelled { response = nil }
}
}
guard accepts(requestGeneration) else { return }
guard context.canLoad, taskID > 0,
DroneDockHomeMetric.usableText(order.orderNumber) != nil else {
response = nil
errorMessage = "缺少有效任务、订单或景区信息,请返回工作台重新进入"
return
}
@@ -56,23 +55,29 @@ final class DroneDockShootingTaskViewModel {
let value = try await service.shooting(taskID: taskID, liveBattery: true)
guard accepts(requestGeneration) else { return }
guard matchesIdentity(value) else {
response = nil
throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取")
}
response = value
} catch {
guard accepts(requestGeneration) else { return }
response = nil
errorMessage = error is CancellationError ? nil : error.localizedDescription
}
}
/// 离开或进入后台时使旧请求失效;再次进入仍读取同一任务,不创建或召唤。
/// 使旧请求失效;同一身份离页或进入后台可保留快照,账号变化始终清除并停止旧任务读取。
@MainActor
func invalidate() {
func invalidate(preservingSnapshot: Bool = false) {
generation &+= 1
isLoading = false
response = nil
if !identityInvalidated { errorMessage = nil }
if !context.hasSameIdentity(as: currentContext()) { identityInvalidated = true }
if identityInvalidated {
response = nil
errorMessage = "账号或景区已变化,请返回工作台重新进入"
} else {
if !preservingSnapshot { response = nil }
errorMessage = nil
}
}
/// 优先使用当前接口标题,缺失时展示当前接口的点位和航线名称。
@@ -97,26 +102,32 @@ final class DroneDockShootingTaskViewModel {
/// 使用服务端阶段标题或任务状态,不从 GET 成功推导到达或拍摄完成。
var statusTitle: String {
if errorMessage != nil { return "任务状态读取失败" }
if isLoading { return "正在获取任务状态" }
if response == nil {
if errorMessage != nil { return "任务状态读取失败" }
if isLoading { return "正在获取任务状态" }
}
if resolvedDisplayPhase().0 == .failed { return "任务执行失败" }
return usable(response?.ui?.title) ?? usable(response?.task?.statusLabel)
?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认"
}
/// 保留服务端阶段说明与执行门禁原因;本模块不执行门禁给出的动作。
var statusMessage: String {
if let errorMessage { return errorMessage }
if isLoading { return "正在读取当前拍摄任务" }
if response == nil {
if let errorMessage { return errorMessage }
if isLoading { return "正在读取当前拍摄任务" }
}
if resolvedDisplayPhase().0 == .failed { return failureMessage }
return usable(response?.ui?.message) ?? usable(response?.executeGate?.message) ?? "—"
}
/// 组合可信阶段与本轮可用动作,不从请求成功、执行中或指令列表推断飞行进度。
var presentation: DroneDockTaskPresentation {
if isLoading {
if response == nil, isLoading {
return DroneDockTaskPresentation(phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: deviceStatusText, action: .none, actionTitle: nil, isActionEnabled: false)
}
if let errorMessage {
if response == nil, let errorMessage {
return DroneDockTaskPresentation(phase: .readError, title: "任务状态读取失败", message: errorMessage,
deviceStatus: deviceStatusText, action: .refresh, actionTitle: "重新读取", isActionEnabled: !identityInvalidated)
}
@@ -139,13 +150,19 @@ final class DroneDockShootingTaskViewModel {
action = .materials
actionTitle = "查看素材"
enabled = true
case .failed:
action = .retry
actionTitle = "重新召唤无人机"
enabled = false
default:
action = .refresh
actionTitle = "刷新状态"
enabled = !identityInvalidated
}
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle, isActionEnabled: enabled)
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle,
isActionEnabled: enabled && !isLoading && !identityInvalidated && (errorMessage == nil || action == .refresh),
actionNote: phase == .failed ? retryUnavailableNote : nil)
}
/// 后端六项展示读数,不解析文案反推设备状态或数值单位。
@@ -155,21 +172,21 @@ final class DroneDockShootingTaskViewModel {
windText: text("wind_speed"), rainText: text("rainfall"), signalText: text("signal"), satelliteText: text("satellite"))
}
/// 无有效快照时不展示旧读数;连接 false 自身不被转换为飞行阶段。
/// 仅无快照时使用未知读数;刷新期间继续展示最近一次成功快照。
var isTelemetryStale: Bool { response == nil }
/// 完整服务端 data,供页面展示和联调查看。
var dataJSON: String? { response?.dataJSON }
@MainActor
private func accepts(_ requestGeneration: Int) -> Bool {
guard generation == requestGeneration, !Task.isCancelled else { return false }
guard generation == requestGeneration else { return false }
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
identityInvalidated = true
invalidate()
errorMessage = "账号或景区已变化,请返回工作台重新进入"
return false
}
return true
return !Task.isCancelled
}
private func matchesIdentity(_ value: DroneDockShootingResponse) -> Bool {
@@ -222,12 +239,7 @@ final class DroneDockShootingTaskViewModel {
private func presentationTitle(for phase: DroneDockTaskDisplayPhase, conflict: Bool) -> String {
if conflict { return "状态待确认" }
let tasks = [response?.task, response?.orderFlightTask].compactMap { $0 }
if phase == .failed, let failed = tasks.first(where: { $0.waylineStatus == 91 }) {
return usable(failed.waylineStatusLabel) ?? "任务执行失败"
}
if phase == .failed, let failed = tasks.first(where: { $0.status == 40 }) {
return usable(failed.statusLabel) ?? "任务执行失败"
}
if phase == .failed { return "任务执行失败" }
if phase == .blocked, let cancelled = tasks.first(where: { $0.status == 50 }) {
return usable(cancelled.statusLabel) ?? "任务已取消"
}
@@ -251,6 +263,24 @@ final class DroneDockShootingTaskViewModel {
}
private func usable(_ value: String?) -> String? { DroneDockHomeMetric.usableText(value) }
/// 明确失败后优先展示任务结果原因,再保留执行门禁的实际限制,不用通用阶段标题充当原因。
private var failureMessage: String {
usable(response?.orderFlightTask?.resultMessage) ?? usable(response?.task?.resultMessage)
?? usable(response?.executeGate?.message) ?? usable(response?.ui?.message) ?? "暂未返回具体失败原因"
}
/// 重新召唤尚未接入;只补充明确设备状态,不将开始许可、空闲或失败推断为允许重试。
private var retryUnavailableNote: String {
let plane = response?.currentPlane
if plane?.onlineStatus == 2 || plane?.workStatus == 0 || usable(plane?.workStatusLabel) == "离线" {
return "无人机离线,暂不可召唤"
}
if let status = usable(plane?.workStatusLabel), ["返航中", "正在返航"].contains(status) {
return "无人机返航中,暂不可召唤"
}
return "暂不可重新召唤,请返回准备页确认设备状态"
}
}
/// 任务页六项读数的后端展示文本,保持服务端单位与零值。
@@ -16,6 +16,7 @@ enum HomeMenuCatalog {
HomeMenuItem(uri: "wallet", title: "我的钱包", iconName: "home_menu_wallet"),
HomeMenuItem(uri: "cloud_management", title: "相册云盘", iconName: "icloud.fill"),
HomeMenuItem(uri: "asset_management", title: "素材管理", iconName: "home_menu_material"),
HomeMenuItem(uri: "sceniclibrary", title: "景区空境库", iconName: "photo.on.rectangle.angled"),
HomeMenuItem(uri: "task_management", title: "任务管理", iconName: "checklist"),
HomeMenuItem(uri: "task_management_editor", title: "任务管理", iconName: "checklist"),
HomeMenuItem(uri: "schedule_management", title: "日程管理", iconName: "calendar"),
@@ -78,6 +78,14 @@ enum HomeRouteHandler {
viewController.navigationController?.pushViewController(SampleListViewController(), animated: true)
case "asset_management":
viewController.navigationController?.pushViewController(MaterialListViewController(), animated: true)
case "sceniclibrary":
let session = AppStore.shared.session
let context = ScenicMaterialContext(userID: session.userId,
scenicID: String(session.currentScenicId),
scenicName: session.currentScenicName)
// 素材接口尚未接入,正式入口使用当前景区空态,避免生成预览素材。
let viewModel = ScenicMaterialsViewModel(context: context, routes: [], groups: [])
viewController.navigationController?.pushViewController(ScenicMaterialsViewController(viewModel: viewModel), animated: true)
case "checkin_points":
viewController.navigationController?.pushViewController(PunchPointListViewController(), animated: true)
case "live_stream_management":
+11 -11
View File
@@ -2,17 +2,6 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>vipsky.oss-cn-shanghai.aliyuncs.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
<key>CFBundleURLTypes</key>
<array>
<dict>
@@ -36,6 +25,17 @@
<string>qqmap</string>
<string>comgooglemaps</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>vipsky.oss-cn-shanghai.aliyuncs.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
@@ -172,13 +172,14 @@ final class DroneDockShootingTaskViewController: BaseViewController {
let telemetry = viewModel.telemetry
telemetryView.apply(values: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText,
telemetry.rainText, telemetry.signalText, telemetry.satelliteText],
isStale: loading || viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric")
let value = loading ? DroneDockTaskPresentation(
isStale: viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric")
let value = loading && viewModel.response == nil ? DroneDockTaskPresentation(
phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation
statusView.apply(value)
statusView.apply(value, isRefreshing: loading)
statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading
navigationItem.rightBarButtonItem?.isEnabled = isPageVisible && isApplicationActive && !loading
navigationItem.rightBarButtonItem?.accessibilityValue = loading ? "正在刷新" : nil
}
private func primaryActionTriggered() {
@@ -191,7 +192,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
case .materials:
guard let navigationController, navigationController.topViewController === self else { return }
navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true)
case .start, .resume, .none:
case .start, .resume, .retry, .none:
break
}
}
@@ -199,7 +200,10 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func showStatusDetails() {
guard isPageVisible, isApplicationActive, presentedViewController == nil else { return }
let state = viewModel.presentation
let texts = [state.title, state.message, state.deviceStatus].filter { !$0.isEmpty && $0 != "—" }
var texts = [state.title, state.message, state.deviceStatus].filter { !$0.isEmpty && $0 != "—" }
if viewModel.response != nil, let error = viewModel.errorMessage {
texts.append("刷新失败,当前显示上次数据:\(error)")
}
var distinct: [String] = []
for text in texts where !distinct.contains(text) { distinct.append(text) }
let alert = UIAlertController(title: "任务状态详情", message: distinct.joined(separator: "\n\n"), preferredStyle: .alert)
@@ -222,6 +226,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.refreshTask = nil
self.isRequesting = false
self.applySnapshot()
if self.viewModel.response != nil, let error = self.viewModel.errorMessage {
self.showToast("刷新失败,当前显示上次数据:\(error)")
}
}
}
@@ -230,7 +237,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
refreshTask?.cancel()
refreshTask = nil
isRequesting = false
viewModel.invalidate()
viewModel.invalidate(preservingSnapshot: true)
applySnapshot()
}
@@ -0,0 +1,208 @@
import SnapKit
import UIKit
/// 对齐体验网页的任务失败组合:警示、原因、排查提示、重召占位及设备提示。
@MainActor
final class DroneDockTaskFailureView: UIView {
/// 点击原因区域查看完整后端说明,页面无需额外占用一个详情按钮。
var onDetails: (() -> Void)?
/// 内部排版参考比例,不对视图或点击区域使用整体缩放。
private(set) var effectiveScale: CGFloat = 1
/// 当前是否使用适配固定小高度的紧凑排版。
private(set) var usesCompactLayout = false
private let content = UIStackView()
private let notice = UIButton(type: .custom)
private let iconBackground = UIView()
private let icon = UIImageView(image: UIImage(systemName: "exclamationmark.circle.fill"))
private let body = UIStackView()
private let titleLabel = DroneDockStyle.label(size: 23, weight: .semibold)
private let reasonContainer = UIView()
private let reasonLabel = DroneDockStyle.label(size: 14, color: UIColor(hex: 0xF53242))
private let adviceLabel = DroneDockStyle.label("请排查错误后再次召唤无人机。", size: 14, color: UIColor(hex: 0x6A79A0))
private let retryButton = UIButton(type: .system)
private let noteLabel = DroneDockStyle.label(size: 12, color: UIColor(hex: 0x7E8BA9))
private var presentation: DroneDockTaskPresentation?
private var contentTop: Constraint?
private var noticeHeight: Constraint?
private var iconSize: Constraint?
private var bodyLeading: Constraint?
private var titleHeight: Constraint?
private var reasonHeight: Constraint?
private var adviceHeight: Constraint?
private var buttonHeight: Constraint?
private var noteHeight: Constraint?
/// 建立失败态专用层级,外部任务页仍决定该区域尺寸。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 更新真实失败原因及不可重召原因,不把开始拍摄许可当作重召许可。
func apply(_ value: DroneDockTaskPresentation) {
presentation = value
titleLabel.text = value.title
let reason = DroneDockHomeMetric.usableText(value.message).flatMap { $0 == "—" ? nil : $0 }
?? "服务端暂未提供具体原因"
reasonLabel.text = reason.hasPrefix("失败原因:") ? reason : "失败原因:\(reason)"
noteLabel.text = value.actionNote ?? "暂不可重新召唤,请返回准备页确认设备状态"
notice.accessibilityLabel = [value.title, reasonLabel.text, adviceLabel.text].compactMap { $0 }.joined(separator: "。")
setNeedsLayout()
}
/// 只收紧内部字号、行数和间距;主按钮保留至少 44 点高度。
override func layoutSubviews() {
updateLayout()
super.layoutSubviews()
}
private func setupUI() {
accessibilityIdentifier = "drone.task.remote.failure"
content.axis = .vertical
content.spacing = 10
addSubview(content)
content.addArrangedSubview(notice)
content.addArrangedSubview(retryButton)
content.addArrangedSubview(noteLabel)
notice.accessibilityIdentifier = "drone.task.remote.failureDetails"
notice.accessibilityHint = "查看完整失败原因"
notice.addTarget(self, action: #selector(showDetails), for: .touchUpInside)
notice.addSubview(iconBackground)
iconBackground.backgroundColor = UIColor(hex: 0xFFEDED)
iconBackground.isUserInteractionEnabled = false
iconBackground.addSubview(icon)
icon.tintColor = UIColor(hex: 0xFF303B)
icon.contentMode = .scaleAspectFit
body.axis = .vertical
body.spacing = 5
body.isUserInteractionEnabled = false
notice.addSubview(body)
body.addArrangedSubview(titleLabel)
body.addArrangedSubview(reasonContainer)
body.addArrangedSubview(adviceLabel)
titleLabel.textColor = UIColor(hex: 0x101523)
titleLabel.accessibilityIdentifier = "drone.task.remote.failureTitle"
reasonContainer.backgroundColor = UIColor(hex: 0xFFF0F2)
reasonContainer.layer.cornerRadius = 6
reasonContainer.addSubview(reasonLabel)
reasonLabel.accessibilityIdentifier = "drone.task.remote.failureReason"
adviceLabel.accessibilityIdentifier = "drone.task.remote.failureAdvice"
noteLabel.accessibilityIdentifier = "drone.task.remote.failureNote"
noteLabel.textAlignment = .center
[titleLabel, reasonLabel, adviceLabel, noteLabel].forEach { $0.lineBreakMode = .byTruncatingTail }
var configuration = UIButton.Configuration.filled()
configuration.title = "重新召唤无人机"
configuration.image = UIImage(systemName: "arrow.triangle.2.circlepath")
configuration.imagePadding = 12
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 21, weight: .regular)
configuration.background.backgroundColor = UIColor(hex: 0xE8EBF1)
configuration.background.cornerRadius = 8
configuration.baseForegroundColor = UIColor(hex: 0x939CB0)
configuration.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8)
retryButton.configuration = configuration
retryButton.configurationUpdateHandler = { button in
button.configuration?.baseForegroundColor = UIColor(hex: 0x939CB0)
button.configuration?.background.backgroundColor = UIColor(hex: 0xE8EBF1)
}
retryButton.isEnabled = false
retryButton.accessibilityIdentifier = "drone.task.remote.failureRetry"
}
private func setupConstraints() {
content.snp.makeConstraints { make in
contentTop = make.top.equalToSuperview().offset(16).constraint
make.leading.trailing.equalToSuperview().inset(18)
}
notice.snp.makeConstraints { make in noticeHeight = make.height.equalTo(90).constraint }
iconBackground.snp.makeConstraints { make in
make.top.leading.equalToSuperview()
iconSize = make.size.equalTo(41).constraint
}
icon.snp.makeConstraints { make in make.center.equalToSuperview(); make.size.equalToSuperview().multipliedBy(24.0 / 41.0) }
body.snp.makeConstraints { make in
make.top.trailing.equalToSuperview()
bodyLeading = make.leading.equalToSuperview().offset(53).constraint
}
titleLabel.snp.makeConstraints { make in titleHeight = make.height.equalTo(30).constraint }
reasonLabel.snp.makeConstraints { make in make.leading.trailing.equalToSuperview().inset(8); make.centerY.equalToSuperview() }
reasonContainer.snp.makeConstraints { make in reasonHeight = make.height.equalTo(30).priority(999).constraint }
adviceLabel.snp.makeConstraints { make in adviceHeight = make.height.equalTo(22).priority(999).constraint }
retryButton.snp.makeConstraints { make in buttonHeight = make.height.equalTo(50).constraint }
noteLabel.snp.makeConstraints { make in noteHeight = make.height.equalTo(18).constraint }
}
private func updateLayout() {
guard let presentation, bounds.width > 0, bounds.height > 0 else { return }
let width = max(1, bounds.width - 36)
let naturalReason = textHeight(reasonLabel.text, font: .systemFont(ofSize: 14), width: width - 53 - 16, lines: 3) + 10
let naturalHeight: CGFloat = 30 + naturalReason + 22 + 10 + 50 + 18 + 14 + 32
effectiveScale = min(1, max(0.8, bounds.height / naturalHeight))
usesCompactLayout = bounds.height < 190
let compact = usesCompactLayout
let extreme = bounds.height < 120
let scale = compact ? 0.8 : effectiveScale
let top: CGFloat = compact ? 6 : 16 * scale
let gap: CGFloat = compact ? 3 : 5 * scale
let diameter: CGFloat = compact ? 32 : 41 * scale
let iconGap: CGFloat = compact ? 8 : 12 * scale
let textWidth = max(1, width - diameter - iconGap)
titleLabel.font = .systemFont(ofSize: compact ? 20 : max(20, 23 * scale), weight: .semibold)
reasonLabel.font = .systemFont(ofSize: max(12, 14 * scale))
adviceLabel.font = .systemFont(ofSize: max(12, 14 * scale))
titleLabel.numberOfLines = 1
reasonLabel.numberOfLines = compact ? 1 : 3
adviceLabel.numberOfLines = 1
noteLabel.numberOfLines = 1
adviceLabel.isHidden = extreme
let title = textHeight(presentation.title, font: titleLabel.font, width: textWidth, lines: 1)
let reasonPadding: CGFloat = compact ? 6 : 10 * scale
var reason = textHeight(reasonLabel.text, font: reasonLabel.font, width: textWidth - 16,
lines: reasonLabel.numberOfLines) + reasonPadding
let advice = extreme ? 0 : textHeight(adviceLabel.text, font: adviceLabel.font, width: textWidth, lines: 1)
let note = textHeight(noteLabel.text, font: noteLabel.font, width: width, lines: 1)
let actionHeight: CGFloat = compact ? 44 : max(44, 50 * scale)
let actionGap: CGFloat = compact ? 5 : 10 * scale
let noteGap: CGFloat = compact ? 3 : 4
var bodyHeight: CGFloat { title + reason + advice + gap * (extreme ? 1 : 2) }
// 长原因先限制可见行数,完整文本仍可点开;不挤压固定页脚或按钮。
while top * 2 + max(44, bodyHeight) + actionGap + actionHeight + noteGap + note > bounds.height,
reasonLabel.numberOfLines > 1 {
reasonLabel.numberOfLines -= 1
reason = textHeight(reasonLabel.text, font: reasonLabel.font, width: textWidth - 16,
lines: reasonLabel.numberOfLines) + reasonPadding
}
contentTop?.update(offset: top)
noticeHeight?.update(offset: max(44, bodyHeight))
iconSize?.update(offset: diameter)
iconBackground.layer.cornerRadius = diameter / 2
bodyLeading?.update(offset: diameter + iconGap)
titleHeight?.update(offset: title)
reasonHeight?.update(offset: reason)
adviceHeight?.update(offset: max(1, advice))
buttonHeight?.update(offset: actionHeight)
noteHeight?.update(offset: note)
body.spacing = gap
content.setCustomSpacing(actionGap, after: notice)
content.setCustomSpacing(noteGap, after: retryButton)
retryButton.configuration?.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var result = attributes
result.font = .systemFont(ofSize: compact ? 16 : max(16, 18 * scale), weight: .semibold)
return result
}
}
private func textHeight(_ text: String?, font: UIFont, width: CGFloat, lines: Int) -> CGFloat {
let height = ((text ?? "") as NSString).boundingRect(
with: CGSize(width: max(1, width), height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font: font], context: nil).height
return ceil(min(max(font.lineHeight, height), font.lineHeight * CGFloat(lines)))
}
@objc private func showDetails() { onDetails?() }
}
@@ -22,6 +22,7 @@ final class DroneDockTaskStatusView: UIView {
private let actionRow = UIView()
private let primaryButton = UIButton(type: .system)
private let detailsButton = UIButton(type: .system)
private let failureView = DroneDockTaskFailureView()
private var presentation: DroneDockTaskPresentation?
private var contentTop: Constraint?
private var contentLeading: Constraint?
@@ -47,9 +48,17 @@ final class DroneDockTaskStatusView: UIView {
CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric)
}
/// 更新真实状态文案与动作许可,不补造百分比或自行推导飞行阶段。
func apply(_ presentation: DroneDockTaskPresentation) {
/// 更新真实状态与动作许可;刷新期间保留内容,只暂时禁用主操作。
func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false) {
self.presentation = presentation
let isFailure = presentation.phase == .failed
contentStack.isHidden = isFailure
failureView.isHidden = !isFailure
if isFailure {
failureView.apply(presentation)
setNeedsLayout()
return
}
titleLabel.text = presentation.title
messageLabel.text = presentation.message
deviceLabel.text = presentation.deviceStatus
@@ -59,7 +68,7 @@ final class DroneDockTaskStatusView: UIView {
let actionTitle = DroneDockHomeMetric.usableText(presentation.actionTitle)
primaryButton.isHidden = presentation.action == .none || actionTitle == nil
primaryButton.setTitle(actionTitle, for: .normal)
primaryButton.isEnabled = presentation.isActionEnabled && !primaryButton.isHidden
primaryButton.isEnabled = presentation.isActionEnabled && !primaryButton.isHidden && !isRefreshing
primaryButton.backgroundColor = primaryButton.isEnabled
? DroneDockStyle.primary : DroneDockStyle.primary.withAlphaComponent(0.35)
primaryButton.accessibilityIdentifier = presentation.action == .refresh
@@ -69,12 +78,22 @@ final class DroneDockTaskStatusView: UIView {
/// 尺寸改变时仅重排内部内容,保留至少 44 点操作区域,不使用 transform 缩放。
override func layoutSubviews() {
if presentation?.phase == .failed {
super.layoutSubviews()
failureView.layoutIfNeeded()
effectiveScale = failureView.effectiveScale
usesCompactLayout = failureView.usesCompactLayout
return
}
updateContentLayout()
super.layoutSubviews()
}
private func setupUI() {
backgroundColor = .white
addSubview(failureView)
failureView.isHidden = true
failureView.onDetails = { [weak self] in self?.onDetails?() }
contentStack.axis = .vertical
contentStack.alignment = .fill
contentStack.spacing = 10
@@ -115,6 +134,7 @@ final class DroneDockTaskStatusView: UIView {
}
private func setupConstraints() {
failureView.snp.makeConstraints { make in make.edges.equalToSuperview() }
contentStack.snp.makeConstraints { make in
contentTop = make.top.equalToSuperview().offset(12).constraint
contentLeading = make.leading.equalToSuperview().offset(16).constraint
@@ -4,7 +4,7 @@ import UIKit
/// 空镜库独立调试入口,不伪造正式首页权限,也不创建机巢工作台或订单。
@MainActor
enum ScenicMaterialsPreview {
/// 指定启动参数时展示独立素材库;正式首页入口等待实际权限 URI 配置。
/// 指定启动参数时展示演示素材;正式首页由 sceniclibrary 权限控制入口。
static func navigationController(arguments: [String]) -> UINavigationController? {
guard arguments.contains("--scenic-materials-preview") else { return nil }
let model = ScenicMaterialsViewModel()
@@ -37,7 +37,7 @@ final class ScenicMaterialsViewController: BaseViewController {
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func setupNavigationBar() {
title = "景区素材"
title = "景区空境库"
navigationItem.backButtonDisplayMode = .minimal
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()