import PDFKit import SnapKit import UIKit import WebKit /// 白色卡片内的文件预览:PDF 使用 PDFKit,其他格式使用离线、受控的 WebView。 @MainActor final class TrainingDocumentPreviewView: UIView { /// 当前票据的文件已真正进入可阅读状态。 var onReady: ((UUID) -> Void)? /// 当前票据的文件无法渲染,交由课程页面停止计时并展示重试。 var onFailure: ((UUID, String) -> Void)? /// 用户明确点击文档外部链接。 var onOpenLink: ((URL) -> Void)? /// 文档排版高度变化时通知课程页更新卡片高度,由外层页面统一滚动。 var onContentHeightChange: ((CGFloat) -> Void)? /// 文档目录锚点的位置,由课程页在外层滚动区域中定位。 var onScrollToPosition: ((CGFloat) -> Void)? /// 包含卡片边框的完整内容高度,加载和错误状态使用紧凑占位高度。 private(set) var preferredContentHeight: CGFloat = 160 /// 当前文件是否已渲染成功,供页面与布局测试查询。 private(set) var isReady = false override var isHidden: Bool { didSet { if !isHidden { pdfView.notifyIfRenderedAndVisible() } } } private let resourceHandler = TrainingDocumentResourceHandler() private let messageProxy = TrainingDocumentMessageProxy() private let pdfView = TrainingPDFDocumentView() private let statusLabel = TrainingUI.text("正在加载附件…", size: 13, color: TrainingUI.muted) private var currentID: UUID? private var currentNavigation: WKNavigation? private var renderWatchdog: Task? private lazy var webView: WKWebView = { let configuration = WKWebViewConfiguration() configuration.websiteDataStore = .nonPersistent() configuration.setURLSchemeHandler(resourceHandler, forURLScheme: "training-document") configuration.userContentController.add(messageProxy, name: "trainingDocument") configuration.userContentController.addUserScript(WKUserScript(source: Self.pageLayoutScript, injectionTime: .atDocumentStart, forMainFrameOnly: true)) let view = WKWebView(frame: .zero, configuration: configuration) view.navigationDelegate = self view.isOpaque = false view.backgroundColor = .white view.scrollView.backgroundColor = .white view.scrollView.isScrollEnabled = false view.scrollView.bounces = false view.scrollView.contentInsetAdjustmentBehavior = .never return view }() /// 创建独立文档沙箱,不共享登录 Cookie、业务脚本或 JS Bridge。 init() { super.init(frame: .zero) backgroundColor = .white layer.cornerRadius = 11 layer.borderWidth = 1 layer.borderColor = TrainingUI.border.cgColor clipsToBounds = true accessibilityIdentifier = "training.reading.preview" pdfView.backgroundColor = .white pdfView.onContentHeightChange = { [weak self] height in guard let self, self.currentID != nil else { return } self.updateContentHeight(height) } pdfView.onOpenLink = { [weak self] url in if TrainingDocumentLoader.isAllowed(url) { self?.onOpenLink?(url) } } statusLabel.textAlignment = .center [pdfView, webView, statusLabel].forEach(addSubview) pdfView.snp.makeConstraints { $0.edges.equalToSuperview().inset(1) } webView.snp.makeConstraints { $0.edges.equalToSuperview().inset(1) } statusLabel.snp.makeConstraints { $0.center.equalToSuperview(); $0.leading.trailing.equalToSuperview().inset(20) } messageProxy.owner = self showStatus("正在加载附件…") } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 加载中、空态和失败态均停止显示旧文件。 func showStatus(_ message: String) { renderWatchdog?.cancel() renderWatchdog = nil currentID = nil currentNavigation = nil isReady = false setPreferredContentHeight(160) webView.stopLoading() resourceHandler.clear() webView.isHidden = true pdfView.isHidden = true pdfView.onVisiblePageDrawn = nil pdfView.document = nil statusLabel.text = message statusLabel.isHidden = false } /// 外层页面滚动后重新检查 PDF 已绘制页面是否真正进入阅读区域。 func notifyIfRenderedAndVisible() { pdfView.notifyIfRenderedAndVisible() } /// 用唯一票据隔离同一附件重试时迟到的文档事件。 func show(_ document: TrainingLocalDocument, requestID: UUID) { showStatus("正在打开附件…") currentID = requestID if document.kind == .pdf { guard let pdf = PDFDocument(url: document.fileURL), !pdf.isLocked, pdf.pageCount > 0 else { fail(requestID, message: TrainingDocumentError.invalidFile.localizedDescription) return } pdfView.onVisiblePageDrawn = { [weak self, weak pdf] in guard let self, let pdf, self.currentID == requestID, self.pdfView.document === pdf, self.window != nil, !self.pdfView.isHidden else { return } self.complete(requestID) } pdfView.document = pdf pdfView.isHidden = false layoutIfNeeded() pdfView.layoutIfNeeded() } else { resourceHandler.configure(document: document, requestID: requestID) webView.isHidden = false let value = "training-document://preview/index.html?type=\(document.kind.rawValue)&requestId=\(requestID.uuidString)" currentNavigation = webView.load(URLRequest(url: URL(string: value)!)) renderWatchdog = Task { @MainActor [weak self] in do { try await Task.sleep(for: .seconds(40)) } catch { return } self?.fail(requestID, message: "附件预览超时,请重试") } } } fileprivate func receive(_ message: WKScriptMessage) { guard message.frameInfo.isMainFrame, message.frameInfo.securityOrigin.protocol == "training-document", message.frameInfo.securityOrigin.host == "preview", let payload = message.body as? [String: Any], let rawID = payload["requestId"] as? String, let id = UUID(uuidString: rawID), currentID == id else { return } switch payload["type"] as? String { case "ready": if let height = payload["height"] as? NSNumber { updateContentHeight(CGFloat(height.doubleValue)) } complete(id) case "layout": if let height = payload["height"] as? NSNumber { updateContentHeight(CGFloat(height.doubleValue)) } case "scroll": if isReady, let value = payload["top"] as? NSNumber { let top = CGFloat(value.doubleValue) if top.isFinite, top >= 0 { onScrollToPosition?(min(top + 1, preferredContentHeight)) } } case "error": let message = (payload["message"] as? String).flatMap { $0.isEmpty || $0.count > 200 ? nil : $0 } fail(id, message: message ?? "附件预览失败,文件可能已损坏或格式不受支持,请重试") case "link": if let value = payload["url"] as? String, let url = URL(string: value), TrainingDocumentLoader.isAllowed(url) { onOpenLink?(url) } default: break } } private func updateContentHeight(_ height: CGFloat) { guard height.isFinite, height > 0 else { return } setPreferredContentHeight(max(82, ceil(height) + 2)) } private func setPreferredContentHeight(_ height: CGFloat) { guard abs(height - preferredContentHeight) >= 1 else { return } preferredContentHeight = height onContentHeightChange?(height) } private func complete(_ id: UUID) { guard currentID == id, !isReady else { return } renderWatchdog?.cancel() renderWatchdog = nil isReady = true statusLabel.isHidden = true onReady?(id) } private func fail(_ id: UUID, message: String) { guard currentID == id else { return } currentID = nil currentNavigation = nil renderWatchdog?.cancel() renderWatchdog = nil webView.stopLoading() resourceHandler.clear() isReady = false setPreferredContentHeight(160) statusLabel.text = message statusLabel.isHidden = false webView.isHidden = true pdfView.isHidden = true onFailure?(id, message) } // 只注入 iOS 宿主:观察内容本身而非 WebView 视口,短文件才能正确缩回。 // 锚点交给外层 UIScrollView,避免 scrollIntoView 在禁用手势后仍改变内部偏移。 private static let pageLayoutScript = """ (function () { 'use strict'; var requestId = new URLSearchParams(window.location.search).get('requestId'); function post(type, fields) { var message = Object.assign({ type: type, requestId: requestId }, fields); window.webkit.messageHandlers.trainingDocument.postMessage(message); } document.addEventListener('click', function (event) { var link = event.target instanceof Element ? event.target.closest('a') : null; var href = link && link.getAttribute('href'); if (!href || href.charAt(0) !== '#') { return; } event.preventDefault(); event.stopImmediatePropagation(); var identifier; try { identifier = decodeURIComponent(href.slice(1)); } catch (_) { return; } var target = document.getElementById(identifier); if (target) { post('scroll', { top: Math.max(0, target.getBoundingClientRect().top + window.scrollY) }); } }, true); function observe() { var content = document.getElementById('document'); if (!content) { return; } var scheduled = false; var previousHeight = 0; function measure() { scheduled = false; if (content.hidden) { return; } var height = Math.ceil(Math.max(content.scrollHeight, content.getBoundingClientRect().height)); if (height > 0 && height !== previousHeight) { previousHeight = height; post('layout', { height: height }); } } function schedule() { if (scheduled) { return; } scheduled = true; requestAnimationFrame(measure); } new ResizeObserver(schedule).observe(content); new MutationObserver(schedule).observe(content, { attributes: true, attributeFilter: ['hidden'] }); window.addEventListener('resize', schedule); schedule(); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', observe, { once: true }); } else { observe(); } }()); """ } extension TrainingDocumentPreviewView: WKNavigationDelegate { /// WebView 只加载 App 提供的本地预览壳,文档不能直接导航到远端网页。 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let url = navigationAction.request.url let local = url?.scheme == "training-document" && url?.host == "preview" && url?.path == "/index.html" decisionHandler(local ? .allow : .cancel) if navigationAction.navigationType == .linkActivated, let url, TrainingDocumentLoader.isAllowed(url) { onOpenLink?(url) } } /// 壳加载失败不会触发阅读成功事件。 func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { guard let currentNavigation, navigation === currentNavigation, (error as NSError).code != NSURLErrorCancelled else { return } if let id = currentID { fail(id, message: "附件预览加载失败,请重试") } } /// 当前壳已开始导航后失败,同样撤销预览状态。 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { guard let currentNavigation, navigation === currentNavigation, (error as NSError).code != NSURLErrorCancelled else { return } if let id = currentID { fail(id, message: "附件预览加载失败,请重试") } } /// 文档渲染进程退出时立即撤销可阅读状态。 func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { if currentNavigation != nil, !webView.isHidden, let id = currentID { fail(id, message: "附件预览已中断,请重试") } } } /// 弱引用消息转发,避免 WKUserContentController 长期持有预览视图。 @MainActor private final class TrainingDocumentMessageProxy: NSObject, WKScriptMessageHandler { weak var owner: TrainingDocumentPreviewView? func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { owner?.receive(message) } } /// 仅响应当前票据的私有文件和固定 App 资源,不代理任何远程地址。 @MainActor private final class TrainingDocumentResourceHandler: NSObject, WKURLSchemeHandler { private var document: TrainingLocalDocument? private var requestID: UUID? private var active: Set = [] func configure(document: TrainingLocalDocument, requestID: UUID) { self.document = document; self.requestID = requestID } func clear() { document = nil; requestID = nil; active.removeAll() } func webView(_ webView: WKWebView, start urlSchemeTask: any WKURLSchemeTask) { let token = ObjectIdentifier(urlSchemeTask) guard let url = urlSchemeTask.request.url, url.scheme == "training-document", url.host == "preview" else { urlSchemeTask.didFailWithError(URLError(.unsupportedURL)); return } let file: URL? let mime: String if let requestID, url.path == "/document/\(requestID.uuidString)/file", let document { file = document.fileURL mime = "application/octet-stream" } else { let path = url.path.dropFirst() guard !path.contains(".."), !path.hasPrefix("/"), !path.isEmpty, let root = Bundle.main.url(forResource: "TrainingDocumentPreview", withExtension: nil) else { urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist)); return } file = root.appendingPathComponent(String(path)) switch (String(path) as NSString).pathExtension { case "html": mime = "text/html" case "js": mime = "text/javascript" case "css": mime = "text/css" default: urlSchemeTask.didFailWithError(URLError(.unsupportedURL)); return } } guard let file else { urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist)); return } active.insert(token) Task { @MainActor [weak self] in let result = await Task.detached(priority: .userInitiated) { Result { try Data(contentsOf: file) } }.value guard let self, self.active.remove(token) != nil else { return } switch result { case .success(let data): let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [ "Content-Type": "\(mime); charset=utf-8", "Cache-Control": "no-store", "Access-Control-Allow-Origin": "*" ])! urlSchemeTask.didReceive(response) urlSchemeTask.didReceive(data) urlSchemeTask.didFinish() case .failure(let error): urlSchemeTask.didFailWithError(error) } } } func webView(_ webView: WKWebView, stop urlSchemeTask: any WKURLSchemeTask) { active.remove(ObjectIdentifier(urlSchemeTask)) } }