feat(training): 支持课程附件预览与整页阅读

This commit is contained in:
2026-10-20 13:36:58 +08:00
parent 091d17ff21
commit b149295e66
53 changed files with 4233 additions and 632 deletions
@@ -1,19 +1,26 @@
import SafariServices
import SnapKit
import UIKit
import WebKit
/// 正式课程按需阅读:正文分页、附件授权与服务端确认的前台读时。
/// 原生课程信息与附件文件预览,并上报服务端确认的有效前台读时。
@MainActor
final class TrainingCourseViewController: TrainingBaseViewController {
private let service: any TrainingDataServing
private let viewModel: TrainingRemoteReadingViewModel
private let webView: WKWebView
private let headerStack = UIStackView()
private let toolbar = UIStackView()
private let validateIdentity: @MainActor @Sendable () -> Bool
private let documentLoader: any TrainingDocumentLoading
private let scrollView = UIScrollView()
private let contentStack = UIStackView()
private let metadataStack = UIStackView()
private let taskTitleLabel = TrainingUI.text(size: 17, weight: .semibold)
private let courseNameLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
private let examInfoLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
private let introductionLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
private let attachmentButton = TrainingUI.button("", plain: true)
private let previewView = TrainingDocumentPreviewView()
private var previewHeightConstraint: Constraint?
private var localDocument: TrainingLocalDocument?
private let stepView = TrainingStepView(currentStep: .learning)
private let sectionsButton = TrainingUI.button("章节目录", secondary: true)
private let attachmentsButton = TrainingUI.button("课程附件", secondary: true)
private let bottomStack = UIStackView()
private let noticeLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
private let actionButton = TrainingUI.button("正在加载课程…")
@@ -22,9 +29,8 @@ final class TrainingCourseViewController: TrainingBaseViewController {
private var readingTask: Task<Void, Never>?
private var closingTask: Task<Void, Never>?
private var closingGeneration = 0
private var contentNavigation: WKNavigation?
private var appIsActive = UIApplication.shared.applicationState == .active
private var isOpeningResource = false
private var isOpeningExternalLink = false
private var contentIsReady = false
private var contentLoadFailed = false
private var pageIsVisible = false
@@ -39,22 +45,22 @@ final class TrainingCourseViewController: TrainingBaseViewController {
/// 当前任务标识,成绩页可复用已有课程页面。
var taskID: String { viewModel.taskID }
/// 使用正式数据源读取课程,课程 HTML 禁用脚本执行。
init(taskID: String, service: any TrainingDataServing) {
/// 使用正式接口与独立文件下载器读取课程附件,支持测试注入本地文件。
init(taskID: String, service: any TrainingDataServing, documentLoader: any TrainingDocumentLoading = TrainingDocumentLoader()) {
self.service = service
self.documentLoader = documentLoader
let session = AppStore.shared.session
let scope = session.accountCachePrefix
let scenicID = session.currentScenicId
let storeID = session.currentStoreId
let token = session.token
viewModel = TrainingRemoteReadingViewModel(taskID: taskID, service: service, validateIdentity: {
let validate: @MainActor @Sendable () -> Bool = {
let current = AppStore.shared.session
return current.accountCachePrefix == scope && current.currentScenicId == scenicID
&& current.currentStoreId == storeID && current.token == token
})
let configuration = WKWebViewConfiguration()
configuration.defaultWebpagePreferences.allowsContentJavaScript = false
webView = WKWebView(frame: .zero, configuration: configuration)
}
validateIdentity = validate
viewModel = TrainingRemoteReadingViewModel(taskID: taskID, service: service, validateIdentity: validate)
super.init(nibName: nil, bundle: nil)
}
@@ -65,16 +71,27 @@ final class TrainingCourseViewController: TrainingBaseViewController {
override func setupUI() {
view.backgroundColor = TrainingUI.background
webView.navigationDelegate = self
webView.backgroundColor = TrainingUI.background
webView.isOpaque = false
toolbar.spacing = 10
toolbar.distribution = .fillEqually
toolbar.addArrangedSubview(sectionsButton)
toolbar.addArrangedSubview(attachmentsButton)
headerStack.axis = .vertical
headerStack.spacing = 20
headerStack.addArrangedSubview(toolbar)
scrollView.delegate = self
scrollView.accessibilityIdentifier = "training.reading.scroll"
scrollView.alwaysBounceVertical = true
contentStack.axis = .vertical
contentStack.spacing = 14
metadataStack.axis = .vertical
metadataStack.spacing = 8
metadataStack.isHidden = true
[taskTitleLabel, courseNameLabel, examInfoLabel, introductionLabel].forEach(metadataStack.addArrangedSubview)
taskTitleLabel.accessibilityIdentifier = "training.reading.taskTitle"
courseNameLabel.accessibilityIdentifier = "training.reading.courseName"
examInfoLabel.accessibilityIdentifier = "training.reading.examInfo"
introductionLabel.accessibilityIdentifier = "training.reading.introduction"
attachmentButton.contentHorizontalAlignment = .leading
attachmentButton.accessibilityIdentifier = "training.reading.documentPicker"
attachmentButton.showsMenuAsPrimaryAction = true
attachmentButton.isHidden = true
contentStack.addArrangedSubview(metadataStack)
contentStack.addArrangedSubview(attachmentButton)
contentStack.addArrangedSubview(previewView)
stepView.isHidden = true
bottomStack.axis = .vertical
bottomStack.spacing = 8
bottomStack.layoutMargins = UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 12)
@@ -83,31 +100,69 @@ final class TrainingCourseViewController: TrainingBaseViewController {
bottomStack.addArrangedSubview(noticeLabel)
bottomStack.addArrangedSubview(actionButton)
actionButton.accessibilityIdentifier = "training.reading.action"
sectionsButton.accessibilityIdentifier = "training.reading.sections"
attachmentsButton.accessibilityIdentifier = "training.reading.attachments"
view.addSubview(headerStack)
view.addSubview(webView)
view.addSubview(stepView)
view.addSubview(scrollView)
scrollView.addSubview(contentStack)
view.addSubview(bottomStack)
previewView.onReady = { [weak self] previewID in
guard let self else { return }
guard self.validateIdentity() else { self.identityChanged(); return }
guard let id = self.viewModel.currentAttachmentID,
self.viewModel.markAttachmentRendered(id: id, previewID: previewID) else { return }
self.contentIsReady = true
self.contentLoadFailed = false
self.applyState()
self.resumeReading()
}
previewView.onFailure = { [weak self] previewID, message in
guard let self, self.viewModel.attachmentPreviewID == previewID,
let id = self.viewModel.currentAttachmentID else { return }
self.viewModel.reportAttachmentFailure(id: id, previewID: previewID, message: message)
self.contentIsReady = false
self.contentLoadFailed = true
self.pauseReading()
self.applyState()
}
previewView.onOpenLink = { [weak self] url in self?.openExternalLink(url) }
previewView.onContentHeightChange = { [weak self] height in
guard let self else { return }
self.previewHeightConstraint?.update(offset: height)
self.view.layoutIfNeeded()
let minimum = -self.scrollView.adjustedContentInset.top
let maximum = max(minimum, self.scrollView.contentSize.height - self.scrollView.bounds.height
+ self.scrollView.adjustedContentInset.bottom)
if self.scrollView.contentOffset.y > maximum {
self.scrollView.setContentOffset(CGPoint(x: 0, y: maximum), animated: false)
}
self.previewView.notifyIfRenderedAndVisible()
if self.isContentVisible { self.resumeReading() }
}
previewView.onScrollToPosition = { [weak self] top in self?.scrollToDocumentPosition(top) }
applyState()
}
override func setupConstraints() {
headerStack.snp.makeConstraints {
stepView.snp.makeConstraints {
$0.top.equalTo(view.safeAreaLayoutGuide).offset(8)
$0.leading.trailing.equalToSuperview().inset(13)
}
webView.snp.makeConstraints {
$0.top.equalTo(headerStack.snp.bottom).offset(8)
scrollView.snp.makeConstraints {
$0.top.equalTo(stepView.snp.bottom).offset(8)
$0.leading.trailing.equalTo(view.safeAreaLayoutGuide)
$0.bottom.equalTo(bottomStack.snp.top)
}
contentStack.snp.makeConstraints {
$0.edges.equalTo(scrollView.contentLayoutGuide).inset(UIEdgeInsets(top: 14, left: 13, bottom: 14, right: 13))
$0.width.equalTo(scrollView.frameLayoutGuide).offset(-26)
}
previewView.snp.makeConstraints {
previewHeightConstraint = $0.height.equalTo(previewView.preferredContentHeight).constraint
}
bottomStack.snp.makeConstraints { $0.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) }
}
override func bindActions() {
actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside)
sectionsButton.addTarget(self, action: #selector(sectionsTapped), for: .touchUpInside)
attachmentsButton.addTarget(self, action: #selector(attachmentsTapped), for: .touchUpInside)
NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange, NotificationName.userDidLogout] {
@@ -125,9 +180,8 @@ final class TrainingCourseViewController: TrainingBaseViewController {
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self,
userRequestID == nil else { return }
if viewModel.task == nil { loadCourse() }
else if viewModel.currentSection == nil, let id = viewModel.currentSectionID { selectSection(id) }
else if localDocument == nil, let id = viewModel.currentAttachmentID { selectAttachment(id) }
else {
if contentNavigation == nil { renderCurrentSection() }
await viewModel.refreshProgress()
applyState()
resumeReading()
@@ -145,78 +199,151 @@ final class TrainingCourseViewController: TrainingBaseViewController {
override func onSessionDidExpire() { identityChanged() }
private var isContentVisible: Bool {
pageIsVisible && contentIsReady && !contentLoadFailed && !isOpeningResource && presentedViewController == nil
let visibleFrame = previewView.convert(previewView.bounds, to: view).intersection(scrollView.frame)
return pageIsVisible && contentIsReady && viewModel.isAttachmentRendered && previewView.isReady
&& visibleFrame.height >= 40 && !contentLoadFailed && !isOpeningExternalLink && presentedViewController == nil
&& navigationController?.topViewController === self && appIsActive && UIApplication.shared.applicationState == .active
}
private func loadCourse() {
guard let request = beginUserRequest(showsLoading: true) else { return }
pauseReading()
contentIsReady = false
contentLoadFailed = false
contentNavigation = nil
resetDocument()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await performUserRequest(request) { await self.viewModel.load() }
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return }
renderCurrentSection()
applyState()
await performUserRequest(request) {
await self.viewModel.load()
await self.loadSelectedDocument()
}
self.applyMetadata()
self.applyState()
}
}
private func selectSection(_ id: String) {
guard let request = beginUserRequest(showsLoading: !viewModel.isSectionCached(id: id)) else { return }
isOpeningResource = false
pauseReading()
contentIsReady = false
contentLoadFailed = false
contentNavigation = nil
private func selectAttachment(_ id: String) {
guard let request = beginUserRequest(showsLoading: true) else { return }
resetDocument()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await performUserRequest(request) { await self.viewModel.selectSection(id: id) }
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return }
renderCurrentSection()
applyState()
await performUserRequest(request) {
await self.viewModel.selectAttachment(id: id)
await self.loadSelectedDocument()
}
self.applyMetadata()
self.applyState()
}
}
private func renderCurrentSection() {
guard !viewModel.isInvalidated, let task = viewModel.task?.summary,
let course = viewModel.course, let section = viewModel.currentSection else { return }
let metadata = task.mode == .exam
? "学习 + 考试 · \(course.sectionCount) 节 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格"
: "仅学习 · \(course.sectionCount) 节"
contentNavigation = webView.loadHTMLString("""
<!doctype html><html lang="zh-CN"><head><meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
<style>
*{box-sizing:border-box}body{font:15px -apple-system,BlinkMacSystemFont,sans-serif;color:#34435b;background:#f5f8fc;margin:0;padding:0 13px 14px;line-height:1.95;overflow-wrap:anywhere}
h1{font-size:17px;font-weight:600;line-height:1.6;color:#172033;margin:14px 0 6px}h2{font-size:15.5px;font-weight:600;color:#172033;margin:0 0 10px}img{max-width:100%;height:auto}table{max-width:100%;display:block;overflow:auto}a{color:#2379ff}
.muted{font-size:12.5px;color:#8491a6;line-height:1.65;margin:6px 0}.reading{background:white;border:1px solid #e3ebf5;border-radius:11px;padding:14px;margin-top:14px}
</style></head><body>
<h1>\(escape(task.title))</h1><p class='muted'>\(escape(course.title))</p><p class='muted'>\(metadata)</p><p class='muted'>\(escape(course.introduction))</p>
<p class='muted'>第 \(section.order) / \(course.sectionCount) 节</p><div class='reading'><h2>\(escape(section.title))</h2>\(section.contentHTML)</div></body></html>
""", baseURL: nil)
private func resetDocument() {
pauseReading()
contentIsReady = false
contentLoadFailed = false
previewView.showStatus("正在加载附件…")
localDocument?.removeTemporaryFile()
localDocument = nil
scrollView.setContentOffset(CGPoint(x: 0, y: -scrollView.adjustedContentInset.top), animated: false)
}
private func escape(_ text: String) -> String {
text.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
private func scrollToDocumentPosition(_ top: CGFloat) {
view.layoutIfNeeded()
let target = previewView.convert(CGPoint(x: 0, y: top), to: scrollView).y - scrollView.adjustedContentInset.top
let minimum = -scrollView.adjustedContentInset.top
let maximum = max(minimum, scrollView.contentSize.height - scrollView.bounds.height + scrollView.adjustedContentInset.bottom)
scrollView.setContentOffset(CGPoint(x: 0, y: min(maximum, max(minimum, target))), animated: true)
}
private func loadSelectedDocument() async {
guard !Task.isCancelled, pageIsVisible, !viewModel.isInvalidated else { return }
applyMetadata()
guard let attachment = viewModel.currentAttachment, let link = viewModel.currentAttachmentLink,
let previewID = viewModel.attachmentPreviewID else {
contentLoadFailed = viewModel.errorMessage != nil
previewView.showStatus(viewModel.errorMessage ?? "暂未上传课程附件")
return
}
do {
let document = try await documentLoader.load(attachment: attachment, link: link)
guard !Task.isCancelled, pageIsVisible, !viewModel.isInvalidated,
viewModel.attachmentPreviewID == previewID else { document.removeTemporaryFile(); return }
guard validateIdentity() else {
document.removeTemporaryFile()
identityChanged()
return
}
localDocument = document
previewView.show(document, requestID: previewID)
} catch {
guard !Task.isCancelled, pageIsVisible, !viewModel.isInvalidated,
viewModel.attachmentPreviewID == previewID else { return }
contentLoadFailed = true
viewModel.reportAttachmentFailure(id: attachment.id, previewID: previewID, message: error.localizedDescription)
previewView.showStatus(error.localizedDescription)
}
}
private func applyMetadata() {
guard let task = viewModel.task?.summary, let course = viewModel.course else { return }
metadataStack.isHidden = false
taskTitleLabel.text = task.title
courseNameLabel.text = course.title
courseNameLabel.isHidden = course.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
examInfoLabel.text = task.mode == .exam ? "学习 + 考试 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格" : "仅学习"
introductionLabel.text = course.introduction
introductionLabel.isHidden = course.introduction.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
attachmentButton.isHidden = viewModel.currentAttachment == nil
var configuration = attachmentButton.configuration
configuration?.title = viewModel.currentAttachment?.name
let canSwitch = viewModel.attachments.count > 1 || viewModel.hasMoreAttachments
configuration?.image = canSwitch ? UIImage(systemName: "chevron.down") : nil
configuration?.imagePlacement = .trailing
configuration?.imagePadding = 8
configuration?.contentInsets = .zero
configuration?.titleLineBreakMode = .byWordWrapping
attachmentButton.configuration = configuration
attachmentButton.isUserInteractionEnabled = canSwitch && userRequestID == nil
var actions = viewModel.attachments.map { attachment in
UIAction(title: attachment.name, state: attachment.id == viewModel.currentAttachmentID ? .on : .off) { [weak self] _ in
guard attachment.id != self?.viewModel.currentAttachmentID else { return }
self?.selectAttachment(attachment.id)
}
}
if viewModel.hasMoreAttachments {
actions.append(UIAction(title: "加载更多附件") { [weak self] _ in self?.loadMoreAttachments() })
}
attachmentButton.menu = UIMenu(children: actions)
}
private func loadMoreAttachments() {
guard let request = beginUserRequest(showsLoading: true) else { return }
Task { @MainActor [weak self] in
guard let self else { return }
await performUserRequest(request) { await self.viewModel.loadAttachments(loadMore: true) }
applyMetadata()
if let message = viewModel.attachmentListErrorMessage { showToast(message) }
}
}
private func applyState() {
guard !viewModel.isInvalidated else { leaveUnavailableCourse(); return }
if let task = viewModel.task?.summary {
stepView.configure(mode: task.mode)
if stepView.superview == nil { headerStack.addArrangedSubview(stepView) }
stepView.isHidden = false
}
let canInteract = userRequestID == nil
sectionsButton.isUserInteractionEnabled = canInteract
attachmentsButton.isUserInteractionEnabled = canInteract
actionButton.isUserInteractionEnabled = canInteract
attachmentButton.isUserInteractionEnabled = canInteract && (viewModel.attachments.count > 1 || viewModel.hasMoreAttachments)
guard canInteract else { return }
sectionsButton.isEnabled = !viewModel.sections.isEmpty
attachmentsButton.isEnabled = (viewModel.course?.attachmentCount ?? 0) > 0
if contentLoadFailed || viewModel.attachmentErrorMessage != nil || viewModel.task == nil {
noticeLabel.text = viewModel.errorMessage ?? "正在加载课程…"
setActionTitle(contentLoadFailed || viewModel.errorMessage != nil ? "重新加载附件" : "正在加载课程…")
actionButton.isEnabled = !viewModel.isLoading && (contentLoadFailed || viewModel.errorMessage != nil)
return
}
if viewModel.hasLoadedAttachments && viewModel.attachments.isEmpty {
noticeLabel.text = "暂未上传课程附件"
setActionTitle("返回培训中心")
actionButton.isEnabled = true
return
}
if let progress = viewModel.progress, progress.readingCompleted {
noticeLabel.text = viewModel.readingErrorMessage ?? "课程阅读已完成"
if viewModel.task?.summary.mode == .exam && progress.canStartExam { setActionTitle("开始考试") }
@@ -226,10 +353,10 @@ final class TrainingCourseViewController: TrainingBaseViewController {
readingTimer = nil
return
}
if contentLoadFailed || viewModel.currentSection == nil {
noticeLabel.text = viewModel.errorMessage ?? (contentLoadFailed ? "课程正文加载失败,请重试" : "正在加载课程…")
setActionTitle(contentLoadFailed || viewModel.errorMessage != nil ? "重新加载课程" : "正在加载课程…")
actionButton.isEnabled = !viewModel.isLoading && (contentLoadFailed || viewModel.errorMessage != nil)
if !contentIsReady {
noticeLabel.text = "正在打开课程附件…"
setActionTitle("正在加载附件…")
actionButton.isEnabled = false
return
}
if !viewModel.canStudy {
@@ -345,28 +472,36 @@ final class TrainingCourseViewController: TrainingBaseViewController {
contentTask?.cancel()
readingTask?.cancel()
closingTask?.cancel()
contentNavigation = nil
previewView.showStatus("")
localDocument?.removeTemporaryFile()
localDocument = nil
viewModel.invalidate()
leaveUnavailableCourse()
}
@objc private func actionTapped() {
guard userRequestID == nil else { return }
if let progress = viewModel.progress, progress.readingCompleted {
if contentLoadFailed || viewModel.attachmentErrorMessage != nil || viewModel.task == nil {
if let id = viewModel.currentAttachmentID { selectAttachment(id) }
else { loadCourse() }
} else if viewModel.attachments.isEmpty { returnToCenter() }
else if let progress = viewModel.progress, progress.readingCompleted {
pauseReading()
if viewModel.task?.summary.mode == .exam && progress.canStartExam {
navigationController?.pushViewController(TrainingExamViewController(taskID: taskID, service: service), animated: true)
} else { returnToCenter() }
} else if contentLoadFailed || viewModel.currentSection == nil {
if let sectionID = viewModel.currentSectionID { selectSection(sectionID) }
else { loadCourse() }
} else if !viewModel.canStudy { returnToCenter() }
else if viewModel.readingErrorMessage != nil {
resumeReading(retrying: true)
} else if viewModel.errorMessage != nil {
if let sectionID = viewModel.currentSectionID { selectSection(sectionID) }
else { loadCourse() }
}
else if viewModel.readingErrorMessage != nil { resumeReading(retrying: true) }
else if viewModel.errorMessage != nil { loadCourse() }
}
private func openExternalLink(_ url: URL) {
guard TrainingDocumentLoader.isAllowed(url), presentedViewController == nil else { return }
isOpeningExternalLink = true
pauseReading()
let controller = SFSafariViewController(url: url)
controller.delegate = self
present(controller, animated: true)
}
private func returnToCenter() {
@@ -378,251 +513,34 @@ final class TrainingCourseViewController: TrainingBaseViewController {
private func leaveUnavailableCourse() {
readingTimer?.invalidate()
readingTimer = nil
contentNavigation = nil
webView.stopLoading()
webView.loadHTMLString("", baseURL: nil)
previewView.showStatus("")
localDocument?.removeTemporaryFile()
localDocument = nil
if let presentedViewController {
presentedViewController.dismiss(animated: false) { [weak self] in self?.returnToCenter() }
} else { returnToCenter() }
}
@objc private func sectionsTapped() {
guard userRequestID == nil, !viewModel.sections.isEmpty else { return }
isOpeningResource = true
pauseReading()
let picker = TrainingCoursePickerViewController(title: "章节目录", rows: sectionRows(), hasMore: viewModel.hasMoreSections,
selectedID: viewModel.currentSectionID, select: { [weak self] id in self?.selectSection(id) },
loadMore: { [weak self] in
guard let self else { return ([], false) }
guard viewModel.hasMoreSections, let request = beginUserRequest(showsLoading: true) else {
return (sectionRows(), viewModel.hasMoreSections)
}
await performUserRequest(request) { await self.viewModel.loadMoreSections() }
applyState()
if let error = viewModel.errorMessage { showToast(error) }
return (sectionRows(), viewModel.hasMoreSections)
}, close: { [weak self] in self?.finishResourcePresentation() })
presentPicker(picker)
}
deinit { localDocument?.removeTemporaryFile() }
private func sectionRows() -> [TrainingCoursePickerRow] {
viewModel.sections.map { TrainingCoursePickerRow(id: $0.id, title: "\($0.order). \($0.title)") }
}
@objc private func attachmentsTapped() {
guard let request = beginUserRequest(showsLoading: !viewModel.hasLoadedAttachments) else { return }
isOpeningResource = true
pauseReading()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await performUserRequest(request) { await self.viewModel.loadAttachments() }
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return }
if viewModel.isInvalidated { applyState(); return }
if let error = viewModel.errorMessage { isOpeningResource = false; showToast(error); applyState(); return }
let picker = TrainingCoursePickerViewController(title: "课程附件", rows: attachmentRows(), hasMore: viewModel.hasMoreAttachments,
select: { [weak self] id in self?.openAttachment(id) }, loadMore: { [weak self] in
guard let self else { return ([], false) }
guard viewModel.hasMoreAttachments, let request = beginUserRequest(showsLoading: true) else {
return (attachmentRows(), viewModel.hasMoreAttachments)
}
await performUserRequest(request) { await self.viewModel.loadAttachments(loadMore: true) }
applyState()
if let error = viewModel.errorMessage { showToast(error) }
return (attachmentRows(), viewModel.hasMoreAttachments)
}, close: { [weak self] in self?.finishResourcePresentation() })
presentPicker(picker)
}
}
private func attachmentRows() -> [TrainingCoursePickerRow] {
viewModel.attachments.map { TrainingCoursePickerRow(id: $0.id, title: $0.name) }
}
private func presentPicker(_ picker: TrainingCoursePickerViewController) {
let navigation = UINavigationController(rootViewController: picker)
navigation.modalPresentationStyle = .pageSheet
navigation.sheetPresentationController?.detents = [.medium(), .large()]
navigation.sheetPresentationController?.prefersGrabberVisible = true
navigation.presentationController?.delegate = picker
present(navigation, animated: true)
}
private func openAttachment(_ id: String) {
guard let request = beginUserRequest(showsLoading: true) else { return }
isOpeningResource = true
pauseReading()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
let link = await performUserRequest(request) { await self.viewModel.authorizeAttachment(id: id) }
guard pageIsVisible, navigationController?.topViewController === self, !Task.isCancelled else { return }
guard let link else {
isOpeningResource = false
if let error = viewModel.errorMessage { showToast(error) }
applyState()
return
}
let controller = SFSafariViewController(url: link.url)
controller.delegate = self
present(controller, animated: true)
}
}
private func finishResourcePresentation() {
isOpeningResource = false
private func finishExternalLinkPresentation() {
isOpeningExternalLink = false
resumeReading()
}
}
extension TrainingCourseViewController: WKNavigationDelegate {
/// 当前正文渲染完成且页面可见后才开始有效阅读。
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard let contentNavigation, navigation === contentNavigation else { return }
contentIsReady = true
contentLoadFailed = false
applyState()
resumeReading()
}
/// 正文初始加载失败时停止计时,保留重试入口。
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
guard let contentNavigation, navigation === contentNavigation else { return }
contentIsReady = false
contentLoadFailed = true
pauseReading()
applyState()
}
/// 正文导航失败时不把失败页面停留计入学习。
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
guard let contentNavigation, navigation === contentNavigation else { return }
contentIsReady = false
contentLoadFailed = true
pauseReading()
applyState()
}
/// 仅允许本机 HTML 初始加载;用户点击的 HTTPS 链接交给 Safari。
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .other, navigationAction.request.url?.absoluteString == "about:blank" {
decisionHandler(.allow)
return
}
decisionHandler(.cancel)
guard navigationAction.navigationType == .linkActivated,
let url = navigationAction.request.url, url.scheme?.lowercased() == "https", url.host != nil else { return }
isOpeningResource = true
pauseReading()
let controller = SFSafariViewController(url: url)
controller.delegate = self
present(controller, animated: true)
extension TrainingCourseViewController: UIScrollViewDelegate {
/// 原生课程信息滚动到覆盖整个预览区时暂停,文件再次可见时才恢复。
func scrollViewDidScroll(_ scrollView: UIScrollView) {
previewView.notifyIfRenderedAndVisible()
if isContentVisible { resumeReading() }
else if viewModel.isReading { pauseReading() }
}
}
extension TrainingCourseViewController: SFSafariViewControllerDelegate {
/// 关闭外部链接后,仅在正文重新可见时建立新的阅读片段。
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
controller.dismiss(animated: true) { [weak self] in self?.finishResourcePresentation() }
controller.dismiss(animated: true) { [weak self] in self?.finishExternalLinkPresentation() }
}
}
/// 目录或附件选择器的一行展示数据,不携带业务行为。
private struct TrainingCoursePickerRow: Hashable {
let id: String
let title: String
}
/// 原生可滚动资源选择器;用户按需加载更多,选中或关闭后明确通知课程页面。
@MainActor
private final class TrainingCoursePickerViewController: UIViewController, UITableViewDelegate, UIAdaptivePresentationControllerDelegate {
/// 差异化列表中的资源项与主动分页入口。
private enum Item: Hashable { case resource(String), more }
private var rows: [TrainingCoursePickerRow]
private var hasMore: Bool
private let selectedID: String?
private let select: (String) -> Void
private let loadMore: () async -> ([TrainingCoursePickerRow], Bool)
private let close: () -> Void
private let tableView = UITableView(frame: .zero, style: .insetGrouped)
private var dataSource: UITableViewDiffableDataSource<Int, Item>!
private var isLoadingMore = false
/// 使用页面提供的展示行、明确选择动作与分页动作构造选择器。
init(title: String, rows: [TrainingCoursePickerRow], hasMore: Bool, selectedID: String? = nil,
select: @escaping (String) -> Void, loadMore: @escaping () async -> ([TrainingCoursePickerRow], Bool), close: @escaping () -> Void) {
self.rows = rows
self.hasMore = hasMore
self.selectedID = selectedID
self.select = select
self.loadMore = loadMore
self.close = close
super.init(nibName: nil, bundle: nil)
self.title = title
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = TrainingUI.background
navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .done, primaryAction: UIAction { [weak self] _ in
guard let self else { return }
dismiss(animated: true, completion: close)
})
tableView.delegate = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 52
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "resource")
view.addSubview(tableView)
tableView.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
dataSource = UITableViewDiffableDataSource<Int, Item>(tableView: tableView) { [weak self] table, indexPath, item in
guard let self else { return nil }
let cell = table.dequeueReusableCell(withIdentifier: "resource", for: indexPath)
var content = UIListContentConfiguration.cell()
switch item {
case .resource(let id):
content.text = rows.first(where: { $0.id == id })?.title
content.textProperties.numberOfLines = 0
cell.accessoryType = id == selectedID ? .checkmark : .none
case .more:
content.text = isLoadingMore ? "正在加载…" : "加载更多"
content.textProperties.color = TrainingUI.primary
cell.accessoryType = .none
}
cell.contentConfiguration = content
return cell
}
applyRows()
}
private func applyRows() {
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
snapshot.appendSections([0])
snapshot.appendItems(rows.map { .resource($0.id) })
if hasMore { snapshot.appendItems([.more]) }
if hasMore, dataSource.snapshot().indexOfItem(.more) != nil { snapshot.reconfigureItems([.more]) }
dataSource.apply(snapshot, animatingDifferences: true)
}
/// 选择后等待模态页面完全关闭,再让课程加载正文或授权附件。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard !isLoadingMore, let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .resource(let id): dismiss(animated: true) { [select] in select(id) }
case .more:
isLoadingMore = true
applyRows()
Task { @MainActor [weak self] in
guard let self else { return }
(rows, hasMore) = await loadMore()
isLoadingMore = false
applyRows()
}
}
}
/// 下拉关闭选择器时恢复正文可见性,由课程页面重新核验计时条件。
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { close() }
}