Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Example/Example/SectionedDiffViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
}
15 changes: 12 additions & 3 deletions Sources/MarkdownView/Components/CodeView/SymbolActionView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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),
Expand All @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = []

/// 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.
Expand Down Expand Up @@ -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 }
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand Down
Loading
Loading