diff --git a/Example/Example/SectionedDiffViewController.swift b/Example/Example/SectionedDiffViewController.swift index 3e590fd..10d9405 100644 --- a/Example/Example/SectionedDiffViewController.swift +++ b/Example/Example/SectionedDiffViewController.swift @@ -19,6 +19,7 @@ final class SectionedDiffViewController: UIViewController { super.viewDidLoad() title = "Files Changed" view.backgroundColor = .systemBackground + updateSettingsMenu() diffController.fileLineCountProvider = { path in SectionedDiffFixture.originalLines(for: path)?.count @@ -46,4 +47,31 @@ final class SectionedDiffViewController: UIViewController { ]) diffController.didMove(toParent: self) } + + private func updateSettingsMenu() { + let showViewed = UIAction( + title: "Show Viewed Toggle", + image: UIImage(systemName: "checkmark.circle"), + state: diffController.showsFileViewedControl ? .on : .off + ) { [weak self] _ in + guard let self else { return } + diffController.showsFileViewedControl.toggle() + updateSettingsMenu() + } + let collapseViewed = UIAction( + title: "Collapse Viewed Files", + image: UIImage(systemName: "chevron.up"), + state: diffController.collapsesViewedFiles ? .on : .off + ) { [weak self] _ in + guard let self else { return } + diffController.collapsesViewedFiles.toggle() + updateSettingsMenu() + } + let settings = UIBarButtonItem( + image: UIImage(systemName: "gearshape"), + menu: UIMenu(children: [showViewed, collapseViewed]) + ) + settings.accessibilityLabel = "Diff settings" + navigationItem.rightBarButtonItem = settings + } } diff --git a/Sources/MarkdownView/Components/CodeView/SymbolActionView.swift b/Sources/MarkdownView/Components/CodeView/SymbolActionView.swift index 9ae2aac..501838f 100644 --- a/Sources/MarkdownView/Components/CodeView/SymbolActionView.swift +++ b/Sources/MarkdownView/Components/CodeView/SymbolActionView.swift @@ -79,10 +79,19 @@ // MARK: - State Toggle Support /// Replaces the current symbol with a new one using the `.replace` content transition. - func replaceSymbol(systemName: String) { - guard #available(iOS 17.0, visionOS 1.0, *) else { return } + func replaceSymbol(systemName: String, animated: Bool = true) { let newImage = UIImage(systemName: systemName, withConfiguration: symbolConfig)! - setSymbolImage(newImage, contentTransition: .replace) + if #available(iOS 17.0, visionOS 1.0, *), animated, !UIAccessibility.isReduceMotionEnabled { + setSymbolImage(newImage, contentTransition: .replace) + } else { + image = newImage + } + } + + override func accessibilityActivate() -> Bool { + guard action != nil else { return false } + handleTap() + return true } /// Adds an ongoing variable color effect (e.g., for active speaker). diff --git a/Sources/MarkdownView/Components/DiffFilesView/DiffFileHeaderView.swift b/Sources/MarkdownView/Components/DiffFilesView/DiffFileHeaderView.swift index 84f9c1a..203a724 100644 --- a/Sources/MarkdownView/Components/DiffFilesView/DiffFileHeaderView.swift +++ b/Sources/MarkdownView/Components/DiffFilesView/DiffFileHeaderView.swift @@ -21,6 +21,13 @@ import Foundation effect: UIBlurEffect(style: .systemChromeMaterial) ) private var tapHandler: (() -> Void)? + private let collapseButton = UIButton(type: .custom) + private let viewedControl = SymbolActionView( + systemName: "circle", + config: UIImage.SymbolConfiguration(pointSize: 22, weight: .regular) + ) + private var representedPath: String? + private var wasViewed = false override init(frame: CGRect) { super.init(frame: frame) @@ -36,9 +43,26 @@ import Foundation file: DiffFilePatch, theme: MarkdownTheme, isCollapsed: Bool, - onToggle: @escaping () -> Void + isViewed: Bool, + showsViewedControl: Bool, + onToggle: @escaping () -> Void, + onToggleViewed: @escaping () -> Void ) { tapHandler = onToggle + viewedControl.isHidden = !showsViewedControl + viewedControl.onTap(onToggleViewed) + viewedControl.tintColor = isViewed ? theme.diff.addedIndicatorText : theme.diff.fileMetadataText + if representedPath != file.displayPath || wasViewed != isViewed { + viewedControl.replaceSymbol( + systemName: isViewed ? "checkmark.circle.fill" : "circle", + animated: representedPath == file.displayPath + ) + } + viewedControl.accessibilityLabel = "Mark \(file.displayPath) as \(isViewed ? "not viewed" : "viewed")" + viewedControl.accessibilityValue = isViewed ? "Viewed" : "Not viewed" + viewedControl.accessibilityTraits = isViewed ? [.button, .selected] : .button + representedPath = file.displayPath + wasViewed = isViewed separator.backgroundColor = theme.diff.borderColor let radius = theme.diff.fileHeaderCornerRadius @@ -74,13 +98,14 @@ import Foundation ? CGAffineTransform(rotationAngle: Self.collapsedChevronRotation) : .identity - accessibilityLabel = "\(file.displayPath), \(file.additions) added, \(file.deletions) removed" - accessibilityHint = isCollapsed ? "Expands the file" : "Collapses the file" + collapseButton.accessibilityLabel = "\(file.displayPath), \(file.additions) added, \(file.deletions) removed" + collapseButton.accessibilityValue = isCollapsed ? "Collapsed" : "Expanded" + collapseButton.accessibilityHint = isCollapsed ? "Expands the file" : "Collapses the file" } private func configureSubviews() { - isAccessibilityElement = true - accessibilityTraits = .button + isAccessibilityElement = false + viewedControl.isAccessibilityElement = true backgroundBlur.translatesAutoresizingMaskIntoConstraints = false addSubview(backgroundBlur) @@ -109,17 +134,34 @@ import Foundation stack.alignment = .center stack.spacing = 8 stack.translatesAutoresizingMaskIntoConstraints = false - addSubview(stack) + stack.isUserInteractionEnabled = false + collapseButton.addSubview(stack) + collapseButton.addTarget(self, action: #selector(handleTap), for: .touchUpInside) + let controls = UIStackView(arrangedSubviews: [collapseButton, viewedControl]) + controls.axis = .horizontal + controls.alignment = .fill + controls.spacing = 8 + controls.translatesAutoresizingMaskIntoConstraints = false + addSubview(controls) + let viewedWidth = viewedControl.widthAnchor.constraint(equalToConstant: 44) + viewedWidth.priority = .init(999) + NSLayoutConstraint.activate([ + viewedWidth, + controls.leadingAnchor.constraint(equalTo: leadingAnchor, constant: DiffFilesViewConfiguration.headerPadding), + controls.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -DiffFilesViewConfiguration.headerPadding), + controls.topAnchor.constraint(equalTo: topAnchor), + controls.bottomAnchor.constraint(equalTo: bottomAnchor), + collapseButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 44), + ]) separator.translatesAutoresizingMaskIntoConstraints = false addSubview(separator) - let padding = DiffFilesViewConfiguration.headerPadding NSLayoutConstraint.activate([ - stack.leadingAnchor.constraint(equalTo: leadingAnchor, constant: padding), - stack.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -padding), - stack.topAnchor.constraint(equalTo: topAnchor), - stack.bottomAnchor.constraint(equalTo: bottomAnchor), + stack.leadingAnchor.constraint(equalTo: collapseButton.leadingAnchor), + stack.trailingAnchor.constraint(equalTo: collapseButton.trailingAnchor), + stack.topAnchor.constraint(equalTo: collapseButton.topAnchor), + stack.bottomAnchor.constraint(equalTo: collapseButton.bottomAnchor), separator.leadingAnchor.constraint(equalTo: leadingAnchor), separator.trailingAnchor.constraint(equalTo: trailingAnchor), @@ -128,19 +170,10 @@ import Foundation equalToConstant: DiffFilesViewConfiguration.hairlineWidth ), ]) - - addGestureRecognizer( - UITapGestureRecognizer(target: self, action: #selector(handleTap)) - ) } @objc private func handleTap() { tapHandler?() } - - override func accessibilityActivate() -> Bool { - tapHandler?() - return tapHandler != nil - } } #endif diff --git a/Sources/MarkdownView/Components/DiffFilesView/DiffFilesViewController.swift b/Sources/MarkdownView/Components/DiffFilesView/DiffFilesViewController.swift index af81534..3924128 100644 --- a/Sources/MarkdownView/Components/DiffFilesView/DiffFilesViewController.swift +++ b/Sources/MarkdownView/Components/DiffFilesView/DiffFilesViewController.swift @@ -84,6 +84,40 @@ import Foundation /// the file. public var fileCollapseHandler: ((String, Bool) -> Void)? + /// Shows a viewed toggle in each file header. Enabled by default. + public var showsFileViewedControl = true { + didSet { reloadEverything() } + } + + /// Checking a file collapses it; unchecking expands it. Changes apply + /// to subsequent viewed toggles, not files already reviewed. + public var collapsesViewedFiles = true + + /// Called after a viewed state changes, allowing hosts to persist it. + public var fileViewedHandler: ((String, Bool) -> Void)? + + /// Viewed paths survive `setPatch` for files still present. Hosts should + /// use a new controller for a different review, or unmark paths explicitly. + public private(set) var viewedFilePaths: Set = [] + + /// Marks a rendered file as viewed (or not viewed), including before the + /// view loads. Unknown paths and unchanged values are ignored. + public func setFileViewed(_ isViewed: Bool, at path: String) { + guard let file = document.files.first(where: { $0.displayPath == path }), + viewedFilePaths.contains(path) != isViewed else { return } + if isViewed { + viewedFilePaths.insert(path) + } else { + viewedFilePaths.remove(path) + } + if collapsesViewedFiles { + setCollapsed(isViewed, fileID: file.id) + } else { + reconfigureHeader(fileID: file.id) + } + fileViewedHandler?(path, isViewed) + } + /// Live line-selection updates: the display path of the file being /// selected in, and the selection (`nil` when it clears). A selection /// spans one hunk; selecting in another hunk clears the previous one. @@ -148,12 +182,14 @@ import Foundation fatalError("init(coder:) has not been implemented") } - /// Replaces the rendered patch, resetting collapse and expansion state. + /// Replaces the rendered patch and resets context expansion. Explicit + /// collapse choices and viewed paths are retained for progressive loads. public func setPatch(_ patch: String, language: String? = nil) { self.patch = patch document = DiffPatchDocument(patch: patch, language: language) ?? .init(files: [], language: language) documentGeneration += 1 + viewedFilePaths.formIntersection(document.files.map(\.displayPath)) collapsedFileIDs = Set(document.files.compactMap { file in if userCollapsedPaths.contains(file.displayPath) { return file.id } if userExpandedPaths.contains(file.displayPath) { return nil } @@ -310,13 +346,7 @@ import Foundation ) { [weak self] header, _, indexPath in guard let self, document.files.indices.contains(indexPath.section) else { return } let file = document.files[indexPath.section] - header.configure( - file: file, - theme: theme, - isCollapsed: collapsedFileIDs.contains(file.id) - ) { [weak self] in - self?.toggleCollapse(fileID: file.id) - } + configureHeader(header, file: file) } dataSource.supplementaryViewProvider = { collectionView, _, indexPath in @@ -377,20 +407,20 @@ import Foundation #if !os(visionOS) UIImpactFeedbackGenerator(style: .soft).impactOccurred() #endif - let isCollapsed = collapsedFileIDs.contains(fileID) + setCollapsed(!collapsedFileIDs.contains(fileID), fileID: fileID) + } + + private func setCollapsed(_ isCollapsed: Bool, fileID: Int) { + guard let file = document.file(withID: fileID) else { return } + let didChange = collapsedFileIDs.contains(fileID) != isCollapsed if isCollapsed { - collapsedFileIDs.remove(fileID) - } else { collapsedFileIDs.insert(fileID) - } - if let path = document.file(withID: fileID)?.displayPath { - if isCollapsed { - userExpandedPaths.insert(path) - userCollapsedPaths.remove(path) - } else { - userCollapsedPaths.insert(path) - userExpandedPaths.remove(path) - } + userCollapsedPaths.insert(file.displayPath) + userExpandedPaths.remove(file.displayPath) + } else { + collapsedFileIDs.remove(fileID) + userExpandedPaths.insert(file.displayPath) + userCollapsedPaths.remove(file.displayPath) } // Toggles snap deliberately (GitHub-app behavior). Every animated // variant misbehaves against translucent rows and pinned headers: @@ -401,25 +431,39 @@ import Foundation // Headers are supplementary views, so no item update reaches them; // reconfigure the visible one so its chevron follows the state. reconfigureHeader(fileID: fileID) - if let file = document.file(withID: fileID) { - fileCollapseHandler?(file.displayPath, !isCollapsed) + if didChange { + fileCollapseHandler?(file.displayPath, isCollapsed) } } private func reconfigureHeader(fileID: Int) { - guard let section = document.files.firstIndex(where: { $0.id == fileID }), + guard isViewLoaded, let section = document.files.firstIndex(where: { $0.id == fileID }), let header = collectionView.supplementaryView( forElementKind: UICollectionView.elementKindSectionHeader, at: IndexPath(item: 0, section: section) ) as? DiffFileHeaderView else { return } + configureHeader(header, file: document.files[section]) + } + + private func configureHeader(_ header: DiffFileHeaderView, file: DiffFilePatch) { header.configure( - file: document.files[section], + file: file, theme: theme, - isCollapsed: collapsedFileIDs.contains(fileID) - ) { [weak self] in - self?.toggleCollapse(fileID: fileID) - } + isCollapsed: collapsedFileIDs.contains(file.id), + isViewed: viewedFilePaths.contains(file.displayPath), + showsViewedControl: showsFileViewedControl, + onToggle: { [weak self] in + self?.toggleCollapse(fileID: file.id) + }, + onToggleViewed: { [weak self] in + guard let self else { return } + #if !os(visionOS) + UIImpactFeedbackGenerator(style: .soft).impactOccurred() + #endif + setFileViewed(!viewedFilePaths.contains(file.displayPath), at: file.displayPath) + } + ) } // MARK: - Line selection diff --git a/Tests/MarkdownViewTests/DiffFilesViewedTests.swift b/Tests/MarkdownViewTests/DiffFilesViewedTests.swift new file mode 100644 index 0000000..3b454bc --- /dev/null +++ b/Tests/MarkdownViewTests/DiffFilesViewedTests.swift @@ -0,0 +1,109 @@ +#if canImport(UIKit) + import UIKit + import XCTest + @testable import MarkdownView + + @MainActor + final class DiffFilesViewedTests: XCTestCase { + private let patch = """ + diff --git a/example.swift b/example.swift + --- a/example.swift + +++ b/example.swift + @@ -1 +1 @@ + -let value = 1 + +let value = 2 + """ + + func testViewedToggleCollapsesAndUncheckingExpandsBeforeViewLoads() { + let controller = DiffFilesViewController(patch: patch) + XCTAssertTrue(controller.showsFileViewedControl) + XCTAssertTrue(controller.collapsesViewedFiles) + var collapseStates: [Bool] = [] + var viewedStates: [Bool] = [] + controller.fileCollapseHandler = { path, collapsed in + XCTAssertEqual(path, "example.swift") + collapseStates.append(collapsed) + } + controller.fileViewedHandler = { path, viewed in + XCTAssertEqual(path, "example.swift") + viewedStates.append(viewed) + } + + controller.setFileViewed(true, at: "example.swift") + XCTAssertEqual(controller.viewedFilePaths, ["example.swift"]) + controller.setFileViewed(true, at: "example.swift") + controller.setFileViewed(false, at: "example.swift") + controller.setFileViewed(true, at: "missing.swift") + + XCTAssertTrue(controller.viewedFilePaths.isEmpty) + XCTAssertEqual(collapseStates, [true, false]) + XCTAssertEqual(viewedStates, [true, false]) + XCTAssertFalse(controller.isViewLoaded) + } + + func testAutomaticCollapseCanBeDisabled() { + let controller = DiffFilesViewController(patch: patch) + controller.collapsesViewedFiles = false + controller.fileCollapseHandler = { _, _ in + XCTFail("Reviewing must not change collapse state when disabled") + } + controller.setFileViewed(true, at: "example.swift") + XCTAssertEqual(controller.viewedFilePaths, ["example.swift"]) + controller.setFileViewed(false, at: "example.swift") + XCTAssertTrue(controller.viewedFilePaths.isEmpty) + } + + func testViewedPathsSurvivePatchRefreshAndRemovedFilesArePruned() { + let controller = DiffFilesViewController(patch: patch) + controller.setFileViewed(true, at: "example.swift") + controller.setPatch(patch) + XCTAssertEqual(controller.viewedFilePaths, ["example.swift"]) + controller.setPatch("") + XCTAssertTrue(controller.viewedFilePaths.isEmpty) + } + + func testHeaderExposesIndependentAccessibleActions() throws { + let document = try XCTUnwrap(DiffPatchDocument(patch: patch, language: "swift")) + let file = try XCTUnwrap(document.files.first) + let header = DiffFileHeaderView(frame: CGRect(x: 0, y: 0, width: 390, height: 48)) + var collapseTaps = 0 + var viewedTaps = 0 + func configure(viewed: Bool, visible: Bool = true) { + header.configure( + file: file, + theme: .default, + isCollapsed: viewed, + isViewed: viewed, + showsViewedControl: visible, + onToggle: { collapseTaps += 1 }, + onToggleViewed: { viewedTaps += 1 } + ) + } + configure(viewed: false) + let controls = try XCTUnwrap(header.subviews.compactMap { $0 as? UIStackView }.first) + let collapse = try XCTUnwrap(controls.arrangedSubviews.first as? UIButton) + let viewed = try XCTUnwrap(controls.arrangedSubviews.last as? SymbolActionView) + XCTAssertFalse(header.isAccessibilityElement) + XCTAssertTrue(viewed.isAccessibilityElement) + XCTAssertEqual(viewed.accessibilityValue, "Not viewed") + XCTAssertTrue(viewed.accessibilityActivate()) + XCTAssertEqual(viewedTaps, 1) + XCTAssertEqual(collapseTaps, 0) + let collapseActions = try XCTUnwrap(collapse.actions(forTarget: header, forControlEvent: .touchUpInside)) + XCTAssertEqual(collapseActions.count, 1) + let collapseAction = NSSelectorFromString(try XCTUnwrap(collapseActions.first)) + XCTAssertTrue(header.responds(to: collapseAction)) + // Package tests have no UIApplication host to dispatch sendActions. + // Invoke the registered selector directly to verify the actual wiring. + _ = header.perform(collapseAction) + XCTAssertEqual(collapseTaps, 1) + XCTAssertEqual(viewedTaps, 1) + + configure(viewed: true) + XCTAssertEqual(viewed.accessibilityValue, "Viewed") + XCTAssertTrue(viewed.accessibilityTraits.contains(.selected)) + configure(viewed: true, visible: false) + XCTAssertTrue(viewed.isHidden) + } + } +#endif