The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import ExpoModulesCore |
| 2 | import UIKit |
| 3 | |
| 4 | private struct ReviewDiffNativeRow: Decodable, Sendable { |
| 5 | let kind: String |
| 6 | let id: String |
| 7 | let fileId: String? |
| 8 | let filePath: String? |
| 9 | let previousPath: String? |
| 10 | let changeType: String? |
| 11 | let additions: Int? |
| 12 | let deletions: Int? |
| 13 | let text: String? |
| 14 | let content: String? |
| 15 | let change: String? |
| 16 | let oldLineNumber: Int? |
| 17 | let newLineNumber: Int? |
| 18 | let wordDiffRanges: [ReviewDiffNativeWordDiffRange]? |
| 19 | let commentText: String? |
| 20 | let commentRangeLabel: String? |
| 21 | let commentSectionTitle: String? |
| 22 | /** A notice drawn in the warning colors. */ |
| 23 | let tone: String? |
| 24 | /** A notice that reports taps through `onPressNotice`. */ |
| 25 | let actionable: Bool? |
| 26 | /** Where a cut line's note starts in `content`, in UTF-16 units. */ |
| 27 | let noteStart: Int? |
| 28 | } |
| 29 | |
| 30 | private struct ReviewDiffNativeWordDiffRange: Decodable, Sendable { |
| 31 | let start: Int |
| 32 | let end: Int |
| 33 | } |
| 34 | |
| 35 | private struct ReviewDiffNativeToken: Decodable, Sendable { |
| 36 | let content: String |
| 37 | let color: String? |
| 38 | let fontStyle: Int? |
| 39 | } |
| 40 | |
| 41 | private struct ReviewDiffNativeTokenPatch: Decodable, Sendable { |
| 42 | let resetKey: String? |
| 43 | let chunkIndex: Int? |
| 44 | let tokensByRowId: [String: [ReviewDiffNativeToken]]? |
| 45 | } |
| 46 | |
| 47 | private struct ReviewDiffNativeThemePayload: Decodable { |
| 48 | let background: String? |
| 49 | let text: String? |
| 50 | let mutedText: String? |
| 51 | let headerBackground: String? |
| 52 | let border: String? |
| 53 | let hunkBackground: String? |
| 54 | let hunkText: String? |
| 55 | let addBackground: String? |
| 56 | let deleteBackground: String? |
| 57 | let addBar: String? |
| 58 | let deleteBar: String? |
| 59 | let addText: String? |
| 60 | let deleteText: String? |
| 61 | let warningText: String? |
| 62 | let warningBackground: String? |
| 63 | } |
| 64 | |
| 65 | private struct ReviewDiffNativeTheme { |
| 66 | let background: UIColor |
| 67 | let text: UIColor |
| 68 | let mutedText: UIColor |
| 69 | let headerBackground: UIColor |
| 70 | let border: UIColor |
| 71 | let hunkBackground: UIColor |
| 72 | let hunkText: UIColor |
| 73 | let addBackground: UIColor |
| 74 | let deleteBackground: UIColor |
| 75 | let addBar: UIColor |
| 76 | let deleteBar: UIColor |
| 77 | let addText: UIColor |
| 78 | let deleteText: UIColor |
| 79 | let warningText: UIColor |
| 80 | let warningBackground: UIColor |
| 81 | |
| 82 | static func resolve(_ scheme: String) -> ReviewDiffNativeTheme { |
| 83 | resolve(scheme, payload: nil) |
| 84 | } |
| 85 | |
| 86 | static func resolve( |
| 87 | _ scheme: String, |
| 88 | payload: ReviewDiffNativeThemePayload? |
| 89 | ) -> ReviewDiffNativeTheme { |
| 90 | let fallback = fallback(scheme) |
| 91 | guard let payload else { |
| 92 | return fallback |
| 93 | } |
| 94 | |
| 95 | return ReviewDiffNativeTheme( |
| 96 | background: UIColor(reviewDiffHex: payload.background) ?? fallback.background, |
| 97 | text: UIColor(reviewDiffHex: payload.text) ?? fallback.text, |
| 98 | mutedText: UIColor(reviewDiffHex: payload.mutedText) ?? fallback.mutedText, |
| 99 | headerBackground: UIColor(reviewDiffHex: payload.headerBackground) ?? fallback.headerBackground, |
| 100 | border: UIColor(reviewDiffHex: payload.border) ?? fallback.border, |
| 101 | hunkBackground: UIColor(reviewDiffHex: payload.hunkBackground) ?? fallback.hunkBackground, |
| 102 | hunkText: UIColor(reviewDiffHex: payload.hunkText) ?? fallback.hunkText, |
| 103 | addBackground: UIColor(reviewDiffHex: payload.addBackground) ?? fallback.addBackground, |
| 104 | deleteBackground: UIColor(reviewDiffHex: payload.deleteBackground) ?? fallback.deleteBackground, |
| 105 | addBar: UIColor(reviewDiffHex: payload.addBar) ?? fallback.addBar, |
| 106 | deleteBar: UIColor(reviewDiffHex: payload.deleteBar) ?? fallback.deleteBar, |
| 107 | addText: UIColor(reviewDiffHex: payload.addText) ?? fallback.addText, |
| 108 | deleteText: UIColor(reviewDiffHex: payload.deleteText) ?? fallback.deleteText, |
| 109 | warningText: UIColor(reviewDiffHex: payload.warningText) ?? fallback.warningText, |
| 110 | warningBackground: UIColor(reviewDiffHex: payload.warningBackground) |
| 111 | ?? fallback.warningBackground |
| 112 | ) |
| 113 | } |
| 114 | |
| 115 | private static func fallback(_ scheme: String) -> ReviewDiffNativeTheme { |
| 116 | if scheme == "dark" { |
| 117 | return ReviewDiffNativeTheme( |
| 118 | background: UIColor(red: 0.07, green: 0.07, blue: 0.07, alpha: 1), |
| 119 | text: UIColor(red: 0.90, green: 0.90, blue: 0.90, alpha: 1), |
| 120 | mutedText: UIColor(red: 0.52, green: 0.52, blue: 0.52, alpha: 1), |
| 121 | headerBackground: UIColor(red: 0.10, green: 0.10, blue: 0.10, alpha: 1), |
| 122 | border: UIColor(red: 0.16, green: 0.16, blue: 0.16, alpha: 1), |
| 123 | hunkBackground: UIColor(red: 0.03, green: 0.14, blue: 0.18, alpha: 1), |
| 124 | hunkText: UIColor(red: 0.41, green: 0.82, blue: 1.00, alpha: 1), |
| 125 | addBackground: UIColor(red: 0.02, green: 0.16, blue: 0.10, alpha: 1), |
| 126 | deleteBackground: UIColor(red: 0.18, green: 0.05, blue: 0.08, alpha: 1), |
| 127 | addBar: UIColor(red: 0.02, green: 0.82, blue: 0.54, alpha: 1), |
| 128 | deleteBar: UIColor(red: 1.00, green: 0.36, blue: 0.50, alpha: 1), |
| 129 | addText: UIColor(red: 0.10, green: 0.84, blue: 0.56, alpha: 1), |
| 130 | deleteText: UIColor(red: 1.00, green: 0.38, blue: 0.52, alpha: 1), |
| 131 | warningText: UIColor(red: 0.98, green: 0.80, blue: 0.40, alpha: 1), |
| 132 | warningBackground: UIColor(red: 0.20, green: 0.15, blue: 0.05, alpha: 1) |
| 133 | ) |
| 134 | } |
| 135 | |
| 136 | return ReviewDiffNativeTheme( |
| 137 | background: UIColor.white, |
| 138 | text: UIColor(red: 0.16, green: 0.16, blue: 0.16, alpha: 1), |
| 139 | mutedText: UIColor(red: 0.47, green: 0.47, blue: 0.47, alpha: 1), |
| 140 | headerBackground: UIColor.white, |
| 141 | border: UIColor(red: 0.88, green: 0.88, blue: 0.90, alpha: 1), |
| 142 | hunkBackground: UIColor(red: 0.83, green: 0.92, blue: 0.98, alpha: 1), |
| 143 | hunkText: UIColor(red: 0.00, green: 0.45, blue: 0.74, alpha: 1), |
| 144 | addBackground: UIColor(red: 0.85, green: 0.94, blue: 0.92, alpha: 1), |
| 145 | deleteBackground: UIColor(red: 0.96, green: 0.85, blue: 0.90, alpha: 1), |
| 146 | addBar: UIColor(red: 0.02, green: 0.80, blue: 0.52, alpha: 1), |
| 147 | deleteBar: UIColor(red: 1.00, green: 0.34, blue: 0.48, alpha: 1), |
| 148 | addText: UIColor(red: 0.00, green: 0.56, blue: 0.34, alpha: 1), |
| 149 | deleteText: UIColor(red: 0.90, green: 0.10, blue: 0.24, alpha: 1), |
| 150 | warningText: UIColor(red: 0.55, green: 0.36, blue: 0.00, alpha: 1), |
| 151 | warningBackground: UIColor(red: 1.00, green: 0.96, blue: 0.84, alpha: 1) |
| 152 | ) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | private struct ReviewDiffNativeStylePayload: Decodable { |
| 157 | let wordWrap: Bool? |
| 158 | let rowHeight: Double? |
| 159 | let contentWidth: Double? |
| 160 | let changeBarWidth: Double? |
| 161 | let gutterWidth: Double? |
| 162 | let codePadding: Double? |
| 163 | let textVerticalInset: Double? |
| 164 | let fileHeaderHeight: Double? |
| 165 | let fileHeaderHorizontalMargin: Double? |
| 166 | let fileHeaderVerticalMargin: Double? |
| 167 | let fileHeaderCornerRadius: Double? |
| 168 | let fileHeaderHorizontalPadding: Double? |
| 169 | let fileHeaderPathRightPadding: Double? |
| 170 | let fileHeaderCountColumnWidth: Double? |
| 171 | let fileHeaderCountGap: Double? |
| 172 | let codeFontSize: Double? |
| 173 | let codeFontWeight: String? |
| 174 | let lineNumberFontSize: Double? |
| 175 | let lineNumberFontWeight: String? |
| 176 | let hunkFontSize: Double? |
| 177 | let hunkFontWeight: String? |
| 178 | let fileHeaderFontSize: Double? |
| 179 | let fileHeaderFontWeight: String? |
| 180 | let fileHeaderMetaFontSize: Double? |
| 181 | let fileHeaderMetaFontWeight: String? |
| 182 | let fileHeaderSubtextFontSize: Double? |
| 183 | let fileHeaderSubtextFontWeight: String? |
| 184 | let fileHeaderStatusFontSize: Double? |
| 185 | let fileHeaderStatusFontWeight: String? |
| 186 | let emptyStateFontSize: Double? |
| 187 | let emptyStateFontWeight: String? |
| 188 | } |
| 189 | |
| 190 | private struct ReviewDiffNativeStyle: Equatable { |
| 191 | let wordWrap: Bool |
| 192 | let rowHeight: CGFloat |
| 193 | let contentWidth: CGFloat |
| 194 | let changeBarWidth: CGFloat |
| 195 | let gutterWidth: CGFloat |
| 196 | let codePadding: CGFloat |
| 197 | let textVerticalInset: CGFloat |
| 198 | let fileHeaderHeight: CGFloat |
| 199 | let fileHeaderHorizontalMargin: CGFloat |
| 200 | let fileHeaderVerticalMargin: CGFloat |
| 201 | let fileHeaderCornerRadius: CGFloat |
| 202 | let fileHeaderHorizontalPadding: CGFloat |
| 203 | let fileHeaderPathRightPadding: CGFloat |
| 204 | let fileHeaderCountColumnWidth: CGFloat |
| 205 | let fileHeaderCountGap: CGFloat |
| 206 | let codeFontSize: CGFloat |
| 207 | let codeFontWeight: UIFont.Weight |
| 208 | let lineNumberFontSize: CGFloat |
| 209 | let lineNumberFontWeight: UIFont.Weight |
| 210 | let hunkFontSize: CGFloat |
| 211 | let hunkFontWeight: UIFont.Weight |
| 212 | let fileHeaderFontSize: CGFloat |
| 213 | let fileHeaderFontWeight: UIFont.Weight |
| 214 | let fileHeaderMetaFontSize: CGFloat |
| 215 | let fileHeaderMetaFontWeight: UIFont.Weight |
| 216 | let fileHeaderSubtextFontSize: CGFloat |
| 217 | let fileHeaderSubtextFontWeight: UIFont.Weight |
| 218 | let fileHeaderStatusFontSize: CGFloat |
| 219 | let fileHeaderStatusFontWeight: UIFont.Weight |
| 220 | let emptyStateFontSize: CGFloat |
| 221 | let emptyStateFontWeight: UIFont.Weight |
| 222 | |
| 223 | static func resolve(_ payload: ReviewDiffNativeStylePayload?) -> ReviewDiffNativeStyle { |
| 224 | ReviewDiffNativeStyle( |
| 225 | wordWrap: payload?.wordWrap ?? false, |
| 226 | rowHeight: metric(payload?.rowHeight, fallback: 24), |
| 227 | contentWidth: metric(payload?.contentWidth, fallback: 2800), |
| 228 | changeBarWidth: nonNegativeMetric(payload?.changeBarWidth, fallback: 4), |
| 229 | gutterWidth: metric(payload?.gutterWidth, fallback: 50), |
| 230 | codePadding: metric(payload?.codePadding, fallback: 8), |
| 231 | textVerticalInset: metric(payload?.textVerticalInset, fallback: 3), |
| 232 | fileHeaderHeight: metric(payload?.fileHeaderHeight, fallback: 54), |
| 233 | fileHeaderHorizontalMargin: metric(payload?.fileHeaderHorizontalMargin, fallback: 8), |
| 234 | fileHeaderVerticalMargin: metric(payload?.fileHeaderVerticalMargin, fallback: 6), |
| 235 | fileHeaderCornerRadius: metric(payload?.fileHeaderCornerRadius, fallback: 10), |
| 236 | fileHeaderHorizontalPadding: metric(payload?.fileHeaderHorizontalPadding, fallback: 12), |
| 237 | fileHeaderPathRightPadding: metric(payload?.fileHeaderPathRightPadding, fallback: 128), |
| 238 | fileHeaderCountColumnWidth: metric(payload?.fileHeaderCountColumnWidth, fallback: 42), |
| 239 | fileHeaderCountGap: metric(payload?.fileHeaderCountGap, fallback: 6), |
| 240 | codeFontSize: metric(payload?.codeFontSize, fallback: 12), |
| 241 | codeFontWeight: fontWeight(payload?.codeFontWeight, fallback: .bold), |
| 242 | lineNumberFontSize: metric(payload?.lineNumberFontSize, fallback: 11), |
| 243 | lineNumberFontWeight: fontWeight(payload?.lineNumberFontWeight, fallback: .bold), |
| 244 | hunkFontSize: metric(payload?.hunkFontSize, fallback: 12), |
| 245 | hunkFontWeight: fontWeight(payload?.hunkFontWeight, fallback: .bold), |
| 246 | fileHeaderFontSize: metric(payload?.fileHeaderFontSize, fallback: 13), |
| 247 | fileHeaderFontWeight: fontWeight(payload?.fileHeaderFontWeight, fallback: .bold), |
| 248 | fileHeaderMetaFontSize: metric(payload?.fileHeaderMetaFontSize, fallback: 12), |
| 249 | fileHeaderMetaFontWeight: fontWeight(payload?.fileHeaderMetaFontWeight, fallback: .bold), |
| 250 | fileHeaderSubtextFontSize: metric(payload?.fileHeaderSubtextFontSize, fallback: 11), |
| 251 | fileHeaderSubtextFontWeight: fontWeight(payload?.fileHeaderSubtextFontWeight, fallback: .medium), |
| 252 | fileHeaderStatusFontSize: metric(payload?.fileHeaderStatusFontSize, fallback: 10), |
| 253 | fileHeaderStatusFontWeight: fontWeight(payload?.fileHeaderStatusFontWeight, fallback: .semibold), |
| 254 | emptyStateFontSize: metric(payload?.emptyStateFontSize, fallback: 13), |
| 255 | emptyStateFontWeight: fontWeight(payload?.emptyStateFontWeight, fallback: .semibold) |
| 256 | ) |
| 257 | } |
| 258 | |
| 259 | private static func metric(_ value: Double?, fallback: CGFloat) -> CGFloat { |
| 260 | guard let value, value.isFinite, value > 0 else { |
| 261 | return fallback |
| 262 | } |
| 263 | return CGFloat(value) |
| 264 | } |
| 265 | |
| 266 | private static func nonNegativeMetric(_ value: Double?, fallback: CGFloat) -> CGFloat { |
| 267 | guard let value, value.isFinite, value >= 0 else { |
| 268 | return fallback |
| 269 | } |
| 270 | return CGFloat(value) |
| 271 | } |
| 272 | |
| 273 | private static func fontWeight(_ value: String?, fallback: UIFont.Weight) -> UIFont.Weight { |
| 274 | switch value?.lowercased() { |
| 275 | case "ultralight", "ultra-light": |
| 276 | return .ultraLight |
| 277 | case "thin": |
| 278 | return .thin |
| 279 | case "light": |
| 280 | return .light |
| 281 | case "regular": |
| 282 | return .regular |
| 283 | case "medium": |
| 284 | return .medium |
| 285 | case "semibold", "semi-bold": |
| 286 | return .semibold |
| 287 | case "bold": |
| 288 | return .bold |
| 289 | case "heavy": |
| 290 | return .heavy |
| 291 | case "black": |
| 292 | return .black |
| 293 | default: |
| 294 | return fallback |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | func applyingOverrides(rowHeight: CGFloat?, contentWidth: CGFloat?) -> ReviewDiffNativeStyle { |
| 299 | ReviewDiffNativeStyle( |
| 300 | wordWrap: wordWrap, |
| 301 | rowHeight: rowHeight ?? self.rowHeight, |
| 302 | contentWidth: contentWidth ?? self.contentWidth, |
| 303 | changeBarWidth: changeBarWidth, |
| 304 | gutterWidth: gutterWidth, |
| 305 | codePadding: codePadding, |
| 306 | textVerticalInset: textVerticalInset, |
| 307 | fileHeaderHeight: fileHeaderHeight, |
| 308 | fileHeaderHorizontalMargin: fileHeaderHorizontalMargin, |
| 309 | fileHeaderVerticalMargin: fileHeaderVerticalMargin, |
| 310 | fileHeaderCornerRadius: fileHeaderCornerRadius, |
| 311 | fileHeaderHorizontalPadding: fileHeaderHorizontalPadding, |
| 312 | fileHeaderPathRightPadding: fileHeaderPathRightPadding, |
| 313 | fileHeaderCountColumnWidth: fileHeaderCountColumnWidth, |
| 314 | fileHeaderCountGap: fileHeaderCountGap, |
| 315 | codeFontSize: codeFontSize, |
| 316 | codeFontWeight: codeFontWeight, |
| 317 | lineNumberFontSize: lineNumberFontSize, |
| 318 | lineNumberFontWeight: lineNumberFontWeight, |
| 319 | hunkFontSize: hunkFontSize, |
| 320 | hunkFontWeight: hunkFontWeight, |
| 321 | fileHeaderFontSize: fileHeaderFontSize, |
| 322 | fileHeaderFontWeight: fileHeaderFontWeight, |
| 323 | fileHeaderMetaFontSize: fileHeaderMetaFontSize, |
| 324 | fileHeaderMetaFontWeight: fileHeaderMetaFontWeight, |
| 325 | fileHeaderSubtextFontSize: fileHeaderSubtextFontSize, |
| 326 | fileHeaderSubtextFontWeight: fileHeaderSubtextFontWeight, |
| 327 | fileHeaderStatusFontSize: fileHeaderStatusFontSize, |
| 328 | fileHeaderStatusFontWeight: fileHeaderStatusFontWeight, |
| 329 | emptyStateFontSize: emptyStateFontSize, |
| 330 | emptyStateFontWeight: emptyStateFontWeight |
| 331 | ) |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { |
| 336 | private let payloadDecodeQueue = DispatchQueue( |
| 337 | label: "com.t3tools.review-diff.payload-decode", |
| 338 | qos: .userInitiated |
| 339 | ) |
| 340 | private let scrollView = UIScrollView() |
| 341 | private let contentView = ReviewDiffContentView() |
| 342 | private var rows: [ReviewDiffNativeRow] = [] |
| 343 | private var appearanceScheme: String = "light" |
| 344 | private var themePayload: ReviewDiffNativeThemePayload? |
| 345 | private var stylePayload: ReviewDiffNativeStylePayload? |
| 346 | private var rowHeightOverride: CGFloat? |
| 347 | private var contentWidthOverride: CGFloat? |
| 348 | private var lastMetricsDebugKey = "" |
| 349 | private var lastVisibleRangeDebugKey = "" |
| 350 | private var tokensResetKey = "" |
| 351 | private var contentResetKey = "" |
| 352 | private var initialRowIndex: Int? |
| 353 | private var initialFileId: String? |
| 354 | private var hasAppliedInitialRowIndex = false |
| 355 | private var lastVisibleFileId: String? |
| 356 | private var pendingScrollFileId: String? |
| 357 | private var pendingScrollAnimated = false |
| 358 | private var isProgrammaticScrollActive = false |
| 359 | private var rowsDecodeGeneration = 0 |
| 360 | private var rowsDecodeCancellation: ReviewDiffRowPreparation? |
| 361 | private var tokensDecodeGeneration = 0 |
| 362 | private var tokensDecodeCancellation: ReviewDiffRowPreparation? |
| 363 | |
| 364 | let onDebug = EventDispatcher() |
| 365 | let onVisibleFileChange = EventDispatcher() |
| 366 | let onToggleFile = EventDispatcher() |
| 367 | let onToggleViewedFile = EventDispatcher() |
| 368 | let onPressLine = EventDispatcher() |
| 369 | let onToggleComment = EventDispatcher() |
| 370 | let onPressNotice = EventDispatcher() |
| 371 | let onPullToRefresh = EventDispatcher() |
| 372 | |
| 373 | private let pullRefreshControl = UIRefreshControl() |
| 374 | |
| 375 | public required init(appContext: AppContext? = nil) { |
| 376 | super.init(appContext: appContext) |
| 377 | |
| 378 | clipsToBounds = true |
| 379 | backgroundColor = contentView.theme.background |
| 380 | scrollView.contentInsetAdjustmentBehavior = .never |
| 381 | scrollView.delegate = self |
| 382 | scrollView.clipsToBounds = true |
| 383 | scrollView.alwaysBounceVertical = true |
| 384 | scrollView.alwaysBounceHorizontal = false |
| 385 | scrollView.showsVerticalScrollIndicator = true |
| 386 | scrollView.showsHorizontalScrollIndicator = false |
| 387 | scrollView.backgroundColor = contentView.theme.background |
| 388 | pullRefreshControl.addTarget(self, action: #selector(handlePullToRefresh), for: .valueChanged) |
| 389 | addSubview(scrollView) |
| 390 | |
| 391 | contentView.backgroundColor = contentView.theme.background |
| 392 | contentView.onToggleFile = { [weak self] fileId in |
| 393 | self?.onToggleFile(["fileId": fileId]) |
| 394 | } |
| 395 | contentView.onToggleViewedFile = { [weak self] fileId in |
| 396 | self?.onToggleViewedFile(["fileId": fileId]) |
| 397 | } |
| 398 | contentView.onPressLine = { [weak self] payload in |
| 399 | self?.onPressLine(payload) |
| 400 | } |
| 401 | contentView.onToggleComment = { [weak self] commentId in |
| 402 | self?.onToggleComment(["commentId": commentId]) |
| 403 | } |
| 404 | contentView.onPressNotice = { [weak self] payload in |
| 405 | self?.onPressNotice(payload) |
| 406 | } |
| 407 | contentView.onDrawMetrics = { [weak self] metrics in |
| 408 | self?.emitDebug("draw-metrics", metrics) |
| 409 | } |
| 410 | scrollView.addSubview(contentView) |
| 411 | } |
| 412 | |
| 413 | deinit { |
| 414 | rowsDecodeCancellation?.cancel() |
| 415 | tokensDecodeCancellation?.cancel() |
| 416 | } |
| 417 | |
| 418 | public override func layoutSubviews() { |
| 419 | super.layoutSubviews() |
| 420 | let anchor = contentView.viewportWidth != bounds.width ? contentView.viewportRowAnchor() : nil |
| 421 | scrollView.frame = bounds |
| 422 | updateContentMetrics(rowAnchor: anchor) |
| 423 | } |
| 424 | |
| 425 | public func scrollViewDidScroll(_ scrollView: UIScrollView) { |
| 426 | if scrollView.isTracking || scrollView.isDragging || scrollView.isDecelerating { |
| 427 | contentView.isVerticalScrollActive = true |
| 428 | } |
| 429 | updateViewportFrame() |
| 430 | } |
| 431 | |
| 432 | public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { |
| 433 | // A direct gesture takes ownership from any interrupted programmatic jump. |
| 434 | // Resume visible-file events immediately so the inspector follows the finger. |
| 435 | isProgrammaticScrollActive = false |
| 436 | contentView.isVerticalScrollActive = true |
| 437 | } |
| 438 | |
| 439 | public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { |
| 440 | guard !decelerate else { |
| 441 | return |
| 442 | } |
| 443 | |
| 444 | finishVerticalScroll() |
| 445 | } |
| 446 | |
| 447 | public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { |
| 448 | finishVerticalScroll() |
| 449 | } |
| 450 | |
| 451 | public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { |
| 452 | finishVerticalScroll() |
| 453 | } |
| 454 | |
| 455 | func setRowsJson(_ rowsJson: String) { |
| 456 | contentView.cancelRowPreparation() |
| 457 | rowsDecodeCancellation?.cancel() |
| 458 | let cancellation = ReviewDiffRowPreparation() |
| 459 | rowsDecodeCancellation = cancellation |
| 460 | rowsDecodeGeneration += 1 |
| 461 | let generation = rowsDecodeGeneration |
| 462 | |
| 463 | payloadDecodeQueue.async { [weak self] in |
| 464 | // Check weak liveness without retaining the view or reading its UIKit state. |
| 465 | guard !cancellation.isCancelled, self != nil else { return } |
| 466 | guard let data = rowsJson.data(using: .utf8) else { |
| 467 | return |
| 468 | } |
| 469 | |
| 470 | do { |
| 471 | let decodedRows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data) |
| 472 | DispatchQueue.main.async { [weak self] in |
| 473 | guard let self, generation == self.rowsDecodeGeneration else { |
| 474 | return |
| 475 | } |
| 476 | self.contentView.prepareRows(decodedRows, on: self.payloadDecodeQueue, isCurrent: { [weak self] in |
| 477 | generation == self?.rowsDecodeGeneration |
| 478 | }, completion: { [weak self] in |
| 479 | guard let self, generation == self.rowsDecodeGeneration else { return } |
| 480 | self.rows = decodedRows |
| 481 | self.contentView.rows = decodedRows |
| 482 | self.hasAppliedInitialRowIndex = false |
| 483 | self.lastVisibleFileId = nil |
| 484 | self.emitDebug("rows-decoded", [ |
| 485 | "rows": decodedRows.count, |
| 486 | "firstKind": decodedRows.first?.kind ?? "none", |
| 487 | ]) |
| 488 | self.updateContentMetrics() |
| 489 | self.applyPendingScrollIfNeeded() |
| 490 | }) |
| 491 | } |
| 492 | } catch { |
| 493 | let message = error.localizedDescription |
| 494 | DispatchQueue.main.async { [weak self] in |
| 495 | guard let self, generation == self.rowsDecodeGeneration else { |
| 496 | return |
| 497 | } |
| 498 | self.rows = [] |
| 499 | self.contentView.rows = [] |
| 500 | self.hasAppliedInitialRowIndex = false |
| 501 | self.lastVisibleFileId = nil |
| 502 | self.pendingScrollFileId = nil |
| 503 | self.updateContentMetrics() |
| 504 | self.emitDebug("rows-decode-failed", ["error": message]) |
| 505 | } |
| 506 | } |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | func setTokensJson(_ tokensJson: String) { |
| 511 | tokensDecodeCancellation?.cancel() |
| 512 | let cancellation = ReviewDiffRowPreparation() |
| 513 | tokensDecodeCancellation = cancellation |
| 514 | tokensDecodeGeneration += 1 |
| 515 | let generation = tokensDecodeGeneration |
| 516 | |
| 517 | payloadDecodeQueue.async { [weak self] in |
| 518 | // Entered decoding may finish; only skip full payloads already obsolete in the queue. |
| 519 | guard !cancellation.isCancelled, self != nil else { return } |
| 520 | guard let data = tokensJson.data(using: .utf8) else { |
| 521 | return |
| 522 | } |
| 523 | |
| 524 | do { |
| 525 | let decodedTokens = try JSONDecoder().decode( |
| 526 | [String: [ReviewDiffNativeToken]].self, |
| 527 | from: data |
| 528 | ) |
| 529 | DispatchQueue.main.async { [weak self] in |
| 530 | guard let self, generation == self.tokensDecodeGeneration else { |
| 531 | return |
| 532 | } |
| 533 | self.contentView.tokensByRowId = decodedTokens |
| 534 | } |
| 535 | } catch { |
| 536 | let message = error.localizedDescription |
| 537 | DispatchQueue.main.async { [weak self] in |
| 538 | guard let self, generation == self.tokensDecodeGeneration else { |
| 539 | return |
| 540 | } |
| 541 | self.contentView.tokensByRowId = [:] |
| 542 | self.emitDebug("tokens-decode-failed", ["error": message]) |
| 543 | } |
| 544 | } |
| 545 | } |
| 546 | } |
| 547 | |
| 548 | func setTokensPatchJson(_ tokensPatchJson: String, completion: @escaping (Bool) -> Void) { |
| 549 | let contentResetKey = self.contentResetKey |
| 550 | |
| 551 | payloadDecodeQueue.async { [weak self] in |
| 552 | guard let data = tokensPatchJson.data(using: .utf8) else { |
| 553 | DispatchQueue.main.async { completion(false) } |
| 554 | return |
| 555 | } |
| 556 | |
| 557 | do { |
| 558 | let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data) |
| 559 | DispatchQueue.main.async { [weak self] in |
| 560 | guard let self else { |
| 561 | completion(false) |
| 562 | return |
| 563 | } |
| 564 | guard contentResetKey == self.contentResetKey else { |
| 565 | completion(false) |
| 566 | return |
| 567 | } |
| 568 | // A highlighter request from the previous file can finish after the view has |
| 569 | // already reset. Never let that stale patch roll the native token state back. |
| 570 | if let resetKey = patch.resetKey, resetKey != self.tokensResetKey { |
| 571 | completion(false) |
| 572 | return |
| 573 | } |
| 574 | |
| 575 | let tokensByRowId = patch.tokensByRowId ?? [:] |
| 576 | if tokensByRowId.isEmpty { |
| 577 | completion(true) |
| 578 | return |
| 579 | } |
| 580 | |
| 581 | self.contentView.mergeTokensByRowId(tokensByRowId) |
| 582 | completion(true) |
| 583 | if let chunkIndex = patch.chunkIndex { |
| 584 | self.emitDebug("tokens-patch-decoded", [ |
| 585 | "resetKey": patch.resetKey ?? "", |
| 586 | "chunkIndex": chunkIndex, |
| 587 | "rows": tokensByRowId.count, |
| 588 | "tokens": tokensByRowId.values.reduce(0) { $0 + $1.count }, |
| 589 | "totalRows": self.contentView.tokensByRowId.count, |
| 590 | ]) |
| 591 | } |
| 592 | } |
| 593 | } catch { |
| 594 | let message = error.localizedDescription |
| 595 | DispatchQueue.main.async { [weak self] in |
| 596 | self?.emitDebug("tokens-patch-decode-failed", ["error": message]) |
| 597 | completion(false) |
| 598 | } |
| 599 | } |
| 600 | } |
| 601 | } |
| 602 | |
| 603 | func setTokensResetKey(_ tokensResetKey: String) { |
| 604 | guard tokensResetKey != self.tokensResetKey else { |
| 605 | return |
| 606 | } |
| 607 | |
| 608 | self.tokensResetKey = tokensResetKey |
| 609 | contentView.tokensByRowId = [:] |
| 610 | emitDebug("tokens-reset", [ |
| 611 | "resetKey": tokensResetKey, |
| 612 | ]) |
| 613 | } |
| 614 | |
| 615 | // Code surfaces fill the screen so UIKit can sample content below the glass bar. |
| 616 | // Keep the same visible row when header or safe-area reservations change. |
| 617 | func setContentInsetTop(_ inset: CGFloat) { |
| 618 | scrollView.automaticallyAdjustsScrollIndicatorInsets = false |
| 619 | let inset = max(0, inset) |
| 620 | let delta = inset - scrollView.contentInset.top |
| 621 | guard delta != 0 else { return } |
| 622 | scrollView.contentInset.top = inset |
| 623 | contentView.topContentInset = inset |
| 624 | scrollView.verticalScrollIndicatorInsets.top = inset |
| 625 | scrollView.contentOffset.y -= delta |
| 626 | updateViewportFrame() |
| 627 | } |
| 628 | |
| 629 | func setContentInsetBottom(_ inset: CGFloat) { |
| 630 | scrollView.contentInset.bottom = max(0, inset) |
| 631 | scrollView.verticalScrollIndicatorInsets.bottom = max(0, inset) |
| 632 | } |
| 633 | |
| 634 | func setContentResetKey(_ contentResetKey: String) { |
| 635 | guard contentResetKey != self.contentResetKey else { |
| 636 | return |
| 637 | } |
| 638 | |
| 639 | self.contentResetKey = contentResetKey |
| 640 | lastVisibleRangeDebugKey = "" |
| 641 | contentView.cancelRowPreparation() |
| 642 | rowsDecodeCancellation?.cancel() |
| 643 | rowsDecodeCancellation = nil |
| 644 | rowsDecodeGeneration += 1 |
| 645 | tokensDecodeGeneration += 1 |
| 646 | tokensDecodeCancellation?.cancel() |
| 647 | contentView.tokensByRowId = [:] |
| 648 | rows = [] |
| 649 | contentView.rows = [] |
| 650 | hasAppliedInitialRowIndex = false |
| 651 | pendingScrollFileId = initialFileId |
| 652 | isProgrammaticScrollActive = false |
| 653 | scrollView.setContentOffset(CGPoint(x: 0, y: -scrollView.contentInset.top), animated: false) |
| 654 | updateContentMetrics() |
| 655 | updateViewportFrame() |
| 656 | lastVisibleFileId = nil |
| 657 | applyInitialRowIndexIfNeeded() |
| 658 | } |
| 659 | |
| 660 | func setCollapsedFileIdsJson(_ collapsedFileIdsJson: String) { |
| 661 | let nextCollapsedFileIds = decodeFileIdSet(collapsedFileIdsJson) |
| 662 | let changedFileIds = contentView.collapsedFileIds.symmetricDifference(nextCollapsedFileIds) |
| 663 | let scrollAnchor: ReviewDiffScrollAnchor? |
| 664 | if changedFileIds.count == 1, let changedFileId = changedFileIds.first { |
| 665 | scrollAnchor = contentView.scrollAnchor(forFileId: changedFileId) |
| 666 | } else { |
| 667 | scrollAnchor = nil |
| 668 | } |
| 669 | |
| 670 | contentView.collapsedFileIds = nextCollapsedFileIds |
| 671 | updateContentMetrics() |
| 672 | |
| 673 | if let scrollAnchor, |
| 674 | let headerOffset = contentView.fileHeaderOffset(forFileId: scrollAnchor.fileId) { |
| 675 | let targetOffset = headerOffset - scrollAnchor.screenY |
| 676 | let minOffset = -scrollView.contentInset.top |
| 677 | let maxOffset = max( |
| 678 | scrollView.contentSize.height - scrollView.bounds.height + scrollView.contentInset.bottom, |
| 679 | minOffset |
| 680 | ) |
| 681 | let clampedOffset = min(max(targetOffset, minOffset), maxOffset) |
| 682 | scrollView.setContentOffset(CGPoint(x: 0, y: clampedOffset), animated: false) |
| 683 | updateViewportFrame() |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | func setViewedFileIdsJson(_ viewedFileIdsJson: String) { |
| 688 | contentView.viewedFileIds = decodeFileIdSet(viewedFileIdsJson) |
| 689 | } |
| 690 | |
| 691 | func setSelectedRowIdsJson(_ selectedRowIdsJson: String) { |
| 692 | contentView.selectedRowIds = decodeFileIdSet(selectedRowIdsJson) |
| 693 | } |
| 694 | |
| 695 | func setCollapsedCommentIdsJson(_ collapsedCommentIdsJson: String) { |
| 696 | contentView.collapsedCommentIds = decodeFileIdSet(collapsedCommentIdsJson) |
| 697 | updateContentMetrics() |
| 698 | } |
| 699 | |
| 700 | private func decodeFileIdSet(_ json: String) -> Set<String> { |
| 701 | guard let data = json.data(using: .utf8) else { |
| 702 | return [] |
| 703 | } |
| 704 | |
| 705 | do { |
| 706 | return Set(try JSONDecoder().decode([String].self, from: data)) |
| 707 | } catch { |
| 708 | emitDebug("file-id-set-decode-failed", [ |
| 709 | "error": error.localizedDescription, |
| 710 | ]) |
| 711 | return [] |
| 712 | } |
| 713 | } |
| 714 | |
| 715 | func setAppearanceScheme(_ appearanceScheme: String) { |
| 716 | self.appearanceScheme = appearanceScheme |
| 717 | applyTheme() |
| 718 | } |
| 719 | |
| 720 | func setThemeJson(_ themeJson: String) { |
| 721 | guard let data = themeJson.data(using: .utf8) else { |
| 722 | themePayload = nil |
| 723 | applyTheme() |
| 724 | return |
| 725 | } |
| 726 | |
| 727 | do { |
| 728 | themePayload = try JSONDecoder().decode(ReviewDiffNativeThemePayload.self, from: data) |
| 729 | } catch { |
| 730 | themePayload = nil |
| 731 | emitDebug("theme-decode-failed", [ |
| 732 | "error": error.localizedDescription, |
| 733 | ]) |
| 734 | } |
| 735 | |
| 736 | applyTheme() |
| 737 | } |
| 738 | |
| 739 | private func updateContentMetrics(rowAnchor: ReviewDiffViewportRowAnchor? = nil) { |
| 740 | let anchor = rowAnchor ?? (contentView.viewportWidth != bounds.width |
| 741 | ? contentView.viewportRowAnchor() : nil) |
| 742 | let style = contentView.style |
| 743 | contentView.viewportWidth = bounds.width |
| 744 | let height = max(bounds.height, contentView.contentHeight) |
| 745 | let width = bounds.width |
| 746 | scrollView.contentSize = CGSize(width: bounds.width, height: height) |
| 747 | if let anchor, let offset = contentView.offset(for: anchor) { |
| 748 | let minOffset = -scrollView.contentInset.top |
| 749 | let maxOffset = max(height - scrollView.bounds.height + scrollView.contentInset.bottom, minOffset) |
| 750 | let target = min(max(offset - scrollView.contentInset.top, minOffset), maxOffset) |
| 751 | if abs(target - scrollView.contentOffset.y) > 0.01 { |
| 752 | scrollView.setContentOffset(CGPoint(x: 0, y: target), animated: false) |
| 753 | if isProgrammaticScrollActive { finishVerticalScroll() } |
| 754 | } |
| 755 | } |
| 756 | contentView.frame = CGRect( |
| 757 | x: 0, |
| 758 | y: scrollView.contentOffset.y, |
| 759 | width: max(width, 1), |
| 760 | height: max(bounds.height, 1) |
| 761 | ) |
| 762 | contentView.verticalOffset = scrollView.contentOffset.y |
| 763 | contentView.invalidateVisibleViewport() |
| 764 | contentView.setNeedsDisplay() |
| 765 | applyInitialRowIndexIfNeeded() |
| 766 | applyPendingScrollIfNeeded() |
| 767 | emitVisibleFileIfNeeded() |
| 768 | emitVisibleRange(reason: "layout") |
| 769 | |
| 770 | let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(contentView.contentHeight))" |
| 771 | if debugKey != lastMetricsDebugKey { |
| 772 | lastMetricsDebugKey = debugKey |
| 773 | emitDebug("metrics", [ |
| 774 | "rows": rows.count, |
| 775 | "boundsWidth": Double(bounds.width), |
| 776 | "boundsHeight": Double(bounds.height), |
| 777 | "contentHeight": Double(contentView.contentHeight), |
| 778 | "contentWidth": Double(style.contentWidth), |
| 779 | "fileHeaderHeight": Double(style.fileHeaderHeight), |
| 780 | "rowHeight": Double(style.rowHeight), |
| 781 | ]) |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | private func emitDebug(_ message: String, _ details: [String: Any]) { |
| 786 | var payload = details |
| 787 | payload["message"] = message |
| 788 | onDebug(payload) |
| 789 | } |
| 790 | |
| 791 | private func finishVerticalScroll() { |
| 792 | isProgrammaticScrollActive = false |
| 793 | contentView.isVerticalScrollActive = false |
| 794 | updateViewportFrame() |
| 795 | emitVisibleRange(reason: "scroll-end") |
| 796 | } |
| 797 | |
| 798 | private func emitVisibleFileIfNeeded() { |
| 799 | // Keep the explicit destination selected while UIKit animates through the files |
| 800 | // between the old and new offsets. Emitting every intermediate header forces a |
| 801 | // React render per crossing and makes the navigator visibly flash. |
| 802 | guard !isProgrammaticScrollActive else { |
| 803 | return |
| 804 | } |
| 805 | |
| 806 | // The top of the combined diff is the explicit "All files" destination. |
| 807 | // Treat it as a first-class selection instead of immediately resolving the |
| 808 | // first file header and undoing the navigator's optimistic selection. |
| 809 | let visibleTop = scrollView.contentOffset.y + scrollView.contentInset.top |
| 810 | if visibleTop <= 0.5 { |
| 811 | guard lastVisibleFileId != nil else { |
| 812 | return |
| 813 | } |
| 814 | lastVisibleFileId = nil |
| 815 | onVisibleFileChange(["fileId": NSNull()]) |
| 816 | return |
| 817 | } |
| 818 | |
| 819 | guard let fileId = contentView.visibleFileId(atVerticalOffset: visibleTop), |
| 820 | fileId != lastVisibleFileId else { |
| 821 | return |
| 822 | } |
| 823 | |
| 824 | lastVisibleFileId = fileId |
| 825 | onVisibleFileChange(["fileId": fileId]) |
| 826 | } |
| 827 | |
| 828 | private func emitVisibleRange(reason: String) { |
| 829 | guard bounds.width > 0, bounds.height > 0, |
| 830 | let range = contentView.currentVisibleRowRange() else { |
| 831 | return |
| 832 | } |
| 833 | |
| 834 | let debugKey = "\(range.firstRowIndex):\(range.lastRowIndex):\(Int(scrollView.bounds.height))" |
| 835 | guard debugKey != lastVisibleRangeDebugKey else { |
| 836 | return |
| 837 | } |
| 838 | |
| 839 | lastVisibleRangeDebugKey = debugKey |
| 840 | emitDebug("visible-range", [ |
| 841 | "reason": reason, |
| 842 | "firstRowIndex": range.firstRowIndex, |
| 843 | "lastRowIndex": range.lastRowIndex, |
| 844 | "totalRows": rows.count, |
| 845 | ]) |
| 846 | } |
| 847 | |
| 848 | private func applyTheme() { |
| 849 | contentView.theme = ReviewDiffNativeTheme.resolve(appearanceScheme, payload: themePayload) |
| 850 | backgroundColor = contentView.theme.background |
| 851 | scrollView.backgroundColor = contentView.theme.background |
| 852 | contentView.backgroundColor = contentView.theme.background |
| 853 | contentView.invalidateVisibleViewport() |
| 854 | } |
| 855 | |
| 856 | func setStyleJson(_ styleJson: String) { |
| 857 | guard let data = styleJson.data(using: .utf8) else { |
| 858 | stylePayload = nil |
| 859 | applyStyle() |
| 860 | return |
| 861 | } |
| 862 | |
| 863 | do { |
| 864 | stylePayload = try JSONDecoder().decode(ReviewDiffNativeStylePayload.self, from: data) |
| 865 | } catch { |
| 866 | stylePayload = nil |
| 867 | emitDebug("style-decode-failed", [ |
| 868 | "error": error.localizedDescription, |
| 869 | ]) |
| 870 | } |
| 871 | |
| 872 | applyStyle() |
| 873 | } |
| 874 | |
| 875 | func setRowHeight(_ rowHeight: CGFloat) { |
| 876 | rowHeightOverride = rowHeight.isFinite && rowHeight > 0 ? rowHeight : nil |
| 877 | applyStyle() |
| 878 | } |
| 879 | |
| 880 | func setContentWidth(_ contentWidth: CGFloat) { |
| 881 | contentWidthOverride = contentWidth.isFinite && contentWidth > 0 ? contentWidth : nil |
| 882 | applyStyle() |
| 883 | } |
| 884 | |
| 885 | func setInitialRowIndex(_ initialRowIndex: Double) { |
| 886 | let nextIndex: Int? = initialRowIndex.isFinite && initialRowIndex >= 0 |
| 887 | ? Int(initialRowIndex.rounded(.down)) |
| 888 | : nil |
| 889 | guard nextIndex != self.initialRowIndex else { |
| 890 | return |
| 891 | } |
| 892 | |
| 893 | self.initialRowIndex = nextIndex |
| 894 | hasAppliedInitialRowIndex = false |
| 895 | applyInitialRowIndexIfNeeded() |
| 896 | } |
| 897 | |
| 898 | func scrollToFile(_ fileId: String, animated: Bool) { |
| 899 | pendingScrollFileId = fileId |
| 900 | pendingScrollAnimated = animated |
| 901 | applyPendingScrollIfNeeded() |
| 902 | } |
| 903 | |
| 904 | func setInitialFileId(_ fileId: String) { |
| 905 | let nextFileId = fileId.isEmpty ? nil : fileId |
| 906 | guard nextFileId != initialFileId else { return } |
| 907 | initialFileId = nextFileId |
| 908 | pendingScrollFileId = nextFileId |
| 909 | pendingScrollAnimated = false |
| 910 | // Apply after the prop batch and content metrics, before the first range event. |
| 911 | setNeedsLayout() |
| 912 | } |
| 913 | |
| 914 | func scrollToTop(animated: Bool) { |
| 915 | pendingScrollFileId = nil |
| 916 | pendingScrollAnimated = false |
| 917 | setVerticalContentOffset(0, animated: animated) |
| 918 | } |
| 919 | |
| 920 | func setScrollEnabled(_ enabled: Bool) { |
| 921 | scrollView.isScrollEnabled = enabled |
| 922 | } |
| 923 | |
| 924 | func setBounces(_ bounces: Bool) { |
| 925 | scrollView.bounces = bounces |
| 926 | scrollView.alwaysBounceVertical = bounces |
| 927 | } |
| 928 | |
| 929 | func setRefreshEnabled(_ enabled: Bool) { |
| 930 | if !enabled { pullRefreshControl.endRefreshing() } |
| 931 | scrollView.refreshControl = enabled ? pullRefreshControl : nil |
| 932 | } |
| 933 | |
| 934 | @objc private func handlePullToRefresh() { |
| 935 | onPullToRefresh([:]) |
| 936 | } |
| 937 | |
| 938 | func setRefreshing(_ refreshing: Bool) { |
| 939 | if refreshing { |
| 940 | if !pullRefreshControl.isRefreshing { |
| 941 | pullRefreshControl.beginRefreshing() |
| 942 | } |
| 943 | } else if pullRefreshControl.isRefreshing { |
| 944 | pullRefreshControl.endRefreshing() |
| 945 | } |
| 946 | } |
| 947 | |
| 948 | private func applyStyle() { |
| 949 | let anchor = contentView.viewportRowAnchor() |
| 950 | contentView.style = ReviewDiffNativeStyle |
| 951 | .resolve(stylePayload) |
| 952 | .applyingOverrides(rowHeight: rowHeightOverride, contentWidth: contentWidthOverride) |
| 953 | updateContentMetrics(rowAnchor: anchor) |
| 954 | } |
| 955 | |
| 956 | private func updateViewportFrame() { |
| 957 | contentView.frame = CGRect( |
| 958 | x: 0, |
| 959 | y: scrollView.contentOffset.y, |
| 960 | width: max(bounds.width, 1), |
| 961 | height: max(bounds.height, 1) |
| 962 | ) |
| 963 | contentView.verticalOffset = scrollView.contentOffset.y |
| 964 | contentView.invalidateVisibleViewport() |
| 965 | emitVisibleFileIfNeeded() |
| 966 | } |
| 967 | |
| 968 | private func applyPendingScrollIfNeeded() { |
| 969 | guard let fileId = pendingScrollFileId, |
| 970 | bounds.height > 0 else { |
| 971 | return |
| 972 | } |
| 973 | |
| 974 | guard let headerOffset = contentView.fileHeaderOffset(forFileId: fileId) else { |
| 975 | if !rows.isEmpty { |
| 976 | pendingScrollFileId = nil |
| 977 | } |
| 978 | return |
| 979 | } |
| 980 | |
| 981 | let animated = pendingScrollAnimated |
| 982 | pendingScrollFileId = nil |
| 983 | pendingScrollAnimated = false |
| 984 | setVerticalContentOffset(headerOffset, animated: animated) |
| 985 | } |
| 986 | |
| 987 | private func setVerticalContentOffset(_ targetOffset: CGFloat, animated: Bool) { |
| 988 | let topInset = scrollView.contentInset.top |
| 989 | let maxOffset = max( |
| 990 | scrollView.contentSize.height - scrollView.bounds.height + scrollView.contentInset.bottom, |
| 991 | -topInset |
| 992 | ) |
| 993 | let clampedOffset = min(max(targetOffset - topInset, -topInset), maxOffset) |
| 994 | let shouldAnimate = animated && abs(scrollView.contentOffset.y - clampedOffset) > 0.5 |
| 995 | isProgrammaticScrollActive = shouldAnimate |
| 996 | contentView.isVerticalScrollActive = shouldAnimate |
| 997 | scrollView.setContentOffset(CGPoint(x: 0, y: clampedOffset), animated: shouldAnimate) |
| 998 | if !shouldAnimate { |
| 999 | finishVerticalScroll() |
| 1000 | } |
| 1001 | } |
| 1002 | |
| 1003 | private func applyInitialRowIndexIfNeeded() { |
| 1004 | guard !hasAppliedInitialRowIndex, |
| 1005 | let initialRowIndex, |
| 1006 | bounds.height > 0, |
| 1007 | let rowFrame = contentView.frameForRow(at: initialRowIndex) else { |
| 1008 | return |
| 1009 | } |
| 1010 | |
| 1011 | let visibleHeight = bounds.height - scrollView.contentInset.top - scrollView.contentInset.bottom |
| 1012 | let targetScreenY = max(0, (visibleHeight - rowFrame.height) * 0.3) |
| 1013 | hasAppliedInitialRowIndex = true |
| 1014 | setVerticalContentOffset(rowFrame.minY - targetScreenY, animated: false) |
| 1015 | } |
| 1016 | } |
| 1017 | |
| 1018 | private enum ReviewDiffHorizontalPanKind { |
| 1019 | case code |
| 1020 | case fileHeaderPath |
| 1021 | } |
| 1022 | |
| 1023 | private struct ReviewDiffFileHeaderPathLayout { |
| 1024 | let displayPath: String |
| 1025 | let rect: CGRect |
| 1026 | } |
| 1027 | |
| 1028 | private struct ReviewDiffFileHeaderInteractiveRects { |
| 1029 | let chevron: CGRect |
| 1030 | let icon: CGRect |
| 1031 | let checkbox: CGRect |
| 1032 | } |
| 1033 | |
| 1034 | private struct ReviewDiffStickyFileHeaderIndex { |
| 1035 | let position: Int |
| 1036 | let rowIndex: Int |
| 1037 | } |
| 1038 | |
| 1039 | private struct ReviewDiffStickyFileHeaderTarget { |
| 1040 | let rowIndex: Int |
| 1041 | let row: ReviewDiffNativeRow |
| 1042 | let rect: CGRect |
| 1043 | } |
| 1044 | |
| 1045 | private struct ReviewDiffViewportRowAnchor { |
| 1046 | let rowIndex: Int |
| 1047 | let intraRowOffset: CGFloat |
| 1048 | } |
| 1049 | |
| 1050 | private struct ReviewDiffScrollAnchor { |
| 1051 | let fileId: String |
| 1052 | let screenY: CGFloat |
| 1053 | } |
| 1054 | |
| 1055 | private final class ReviewDiffRowPreparation { |
| 1056 | private let lock = NSLock() |
| 1057 | private var cancelled = false |
| 1058 | |
| 1059 | func cancel() { |
| 1060 | lock.lock() |
| 1061 | cancelled = true |
| 1062 | lock.unlock() |
| 1063 | } |
| 1064 | |
| 1065 | var isCancelled: Bool { |
| 1066 | lock.lock() |
| 1067 | defer { lock.unlock() } |
| 1068 | return cancelled |
| 1069 | } |
| 1070 | } |
| 1071 | |
| 1072 | private struct ReviewDiffGeometryConfiguration: Equatable { |
| 1073 | let style: ReviewDiffNativeStyle |
| 1074 | let viewportWidth: CGFloat |
| 1075 | let collapsedFileIds: Set<String> |
| 1076 | let collapsedCommentIds: Set<String> |
| 1077 | |
| 1078 | func height(for row: ReviewDiffNativeRow) -> CGFloat { |
| 1079 | if row.kind == "file" { return style.fileHeaderHeight } |
| 1080 | if collapsedFileIds.contains(row.resolvedFileId) { return 0 } |
| 1081 | if row.kind == "notice" { return max(style.rowHeight * 2, 44) } |
| 1082 | if row.kind == "comment" { return collapsedCommentIds.contains(row.id) ? 44 : 124 } |
| 1083 | return style.rowHeight |
| 1084 | } |
| 1085 | } |
| 1086 | |
| 1087 | private struct ReviewDiffRowGeometryInput { |
| 1088 | let configuration: ReviewDiffGeometryConfiguration |
| 1089 | let font: UIFont |
| 1090 | let hunkFont: UIFont |
| 1091 | let characterWidth: CGFloat |
| 1092 | let layoutWidth: CGFloat? |
| 1093 | let cached: [String: ReviewDiffCodeLayout] |
| 1094 | } |
| 1095 | |
| 1096 | private struct ReviewDiffRowGeometry { |
| 1097 | let offsets: [CGFloat] |
| 1098 | let fileHeaderIndices: [Int] |
| 1099 | let contentWidths: [String: CGFloat] |
| 1100 | let nativeLayouts: [String: ReviewDiffCodeLayout] |
| 1101 | let height: CGFloat |
| 1102 | let characterWidth: CGFloat |
| 1103 | let wrapColumns: Int? |
| 1104 | } |
| 1105 | |
| 1106 | private extension ReviewDiffNativeRow { |
| 1107 | var resolvedFileId: String { |
| 1108 | if let fileId { return fileId } |
| 1109 | if let range = id.range(of: ":header") ?? id.range(of: ":hunk:") ?? id.range(of: ":line:") { |
| 1110 | return String(id[..<range.lowerBound]) |
| 1111 | } |
| 1112 | return filePath ?? id |
| 1113 | } |
| 1114 | } |
| 1115 | |
| 1116 | private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { |
| 1117 | var rows: [ReviewDiffNativeRow] = [] { |
| 1118 | didSet { |
| 1119 | stopHorizontalDeceleration() |
| 1120 | horizontalOffsetsByFileId.removeAll() |
| 1121 | headerPathOffsetsByFileId.removeAll() |
| 1122 | activePanFileId = nil |
| 1123 | activePanKind = nil |
| 1124 | codeDecorationVersion += 1 |
| 1125 | tokenAttributedStringsByRowId.removeAll() |
| 1126 | if let geometry = preparedRowGeometry { |
| 1127 | preparedRowGeometry = nil |
| 1128 | applyRowGeometry(geometry) |
| 1129 | } else { |
| 1130 | cancelRowPreparation() |
| 1131 | rebuildRowLayout() |
| 1132 | } |
| 1133 | setNeedsDisplayForVisibleBounds() |
| 1134 | } |
| 1135 | } |
| 1136 | var tokensByRowId: [String: [ReviewDiffNativeToken]] = [:] { |
| 1137 | didSet { |
| 1138 | codeDecorationVersion += 1 |
| 1139 | tokenAttributedStringsByRowId.removeAll() |
| 1140 | clampHorizontalOffsets() |
| 1141 | setNeedsDisplayForVisibleBounds() |
| 1142 | } |
| 1143 | } |
| 1144 | |
| 1145 | func mergeTokensByRowId(_ tokensPatch: [String: [ReviewDiffNativeToken]]) { |
| 1146 | // One mutation lets didSet invalidate decoration and display once per batch. |
| 1147 | tokensByRowId.merge(tokensPatch) { _, tokens in tokens } |
| 1148 | } |
| 1149 | |
| 1150 | var collapsedFileIds: Set<String> = [] { |
| 1151 | didSet { |
| 1152 | rebuildRowLayout() |
| 1153 | clampHorizontalOffsets() |
| 1154 | setNeedsDisplayForVisibleBounds() |
| 1155 | } |
| 1156 | } |
| 1157 | var viewedFileIds: Set<String> = [] { |
| 1158 | didSet { |
| 1159 | setNeedsDisplayForVisibleBounds() |
| 1160 | } |
| 1161 | } |
| 1162 | var selectedRowIds: Set<String> = [] { |
| 1163 | didSet { |
| 1164 | setNeedsDisplayForVisibleBounds() |
| 1165 | } |
| 1166 | } |
| 1167 | var collapsedCommentIds: Set<String> = [] { |
| 1168 | didSet { |
| 1169 | rebuildRowLayout() |
| 1170 | setNeedsDisplayForVisibleBounds() |
| 1171 | } |
| 1172 | } |
| 1173 | var style = ReviewDiffNativeStyle.resolve(nil) { |
| 1174 | didSet { |
| 1175 | codeDecorationVersion += 1 |
| 1176 | tokenAttributedStringsByRowId.removeAll() |
| 1177 | rebuildRowLayout() |
| 1178 | clampHorizontalOffsets() |
| 1179 | setNeedsDisplayForVisibleBounds() |
| 1180 | } |
| 1181 | } |
| 1182 | var viewportWidth: CGFloat = 0 { |
| 1183 | didSet { |
| 1184 | if style.wordWrap, viewportWidth != oldValue { |
| 1185 | rebuildRowLayout() |
| 1186 | } |
| 1187 | clampHorizontalOffsets() |
| 1188 | setNeedsDisplayForVisibleBounds() |
| 1189 | } |
| 1190 | } |
| 1191 | var verticalOffset: CGFloat = 0 |
| 1192 | var topContentInset: CGFloat = 0 |
| 1193 | var theme = ReviewDiffNativeTheme.resolve("light") { |
| 1194 | didSet { |
| 1195 | tokenColorsByHex.removeAll() |
| 1196 | codeDecorationVersion += 1 |
| 1197 | tokenAttributedStringsByRowId.removeAll() |
| 1198 | setNeedsDisplayForVisibleBounds() |
| 1199 | } |
| 1200 | } |
| 1201 | private(set) var contentHeight: CGFloat = 0 |
| 1202 | |
| 1203 | private var rowOffsets: [CGFloat] = [] |
| 1204 | private var fileHeaderRowIndices: [Int] = [] |
| 1205 | private var contentWidthsByFileId: [String: CGFloat] = [:] |
| 1206 | private var tokenColorsByHex: [String: UIColor] = [:] |
| 1207 | private var tokenAttributedStringsByRowId: [String: NSAttributedString] = [:] |
| 1208 | private var codeCharacterWidth: CGFloat = 8 |
| 1209 | private var codeWrapColumns: Int? |
| 1210 | private var codeLayoutsByRowId: [String: ReviewDiffCodeLayout] = [:] |
| 1211 | private var codeLayoutWidth: CGFloat? |
| 1212 | private var codeLayoutFont: UIFont? |
| 1213 | private var codeDecorationVersion = 0 |
| 1214 | private var rowPreparation: ReviewDiffRowPreparation? |
| 1215 | private var preparedRowGeometry: ReviewDiffRowGeometry? |
| 1216 | |
| 1217 | private var geometryConfiguration: ReviewDiffGeometryConfiguration { |
| 1218 | ReviewDiffGeometryConfiguration( |
| 1219 | style: style, viewportWidth: viewportWidth, |
| 1220 | collapsedFileIds: collapsedFileIds, collapsedCommentIds: collapsedCommentIds |
| 1221 | ) |
| 1222 | } |
| 1223 | private var panStartHorizontalOffset: CGFloat = 0 |
| 1224 | private var activePanFileId: String? |
| 1225 | private var activePanKind: ReviewDiffHorizontalPanKind? |
| 1226 | private var horizontalOffsetsByFileId: [String: CGFloat] = [:] |
| 1227 | private var headerPathOffsetsByFileId: [String: CGFloat] = [:] |
| 1228 | private var decelerationDisplayLink: CADisplayLink? |
| 1229 | private var deceleratingFileId: String? |
| 1230 | private var horizontalVelocity: CGFloat = 0 |
| 1231 | private var lastDecelerationTimestamp: CFTimeInterval = 0 |
| 1232 | private var lastDrawMetricsTimestamp: CFTimeInterval = 0 |
| 1233 | var isVerticalScrollActive = false |
| 1234 | var onToggleFile: ((String) -> Void)? |
| 1235 | var onToggleViewedFile: ((String) -> Void)? |
| 1236 | var onPressLine: (([String: Any]) -> Void)? |
| 1237 | var onToggleComment: ((String) -> Void)? |
| 1238 | var onPressNotice: (([String: Any]) -> Void)? |
| 1239 | var onDrawMetrics: (([String: Any]) -> Void)? |
| 1240 | |
| 1241 | private var stickyWidth: CGFloat { |
| 1242 | style.changeBarWidth + style.gutterWidth |
| 1243 | } |
| 1244 | |
| 1245 | private var codeStartX: CGFloat { |
| 1246 | stickyWidth + style.codePadding |
| 1247 | } |
| 1248 | |
| 1249 | /// Height before word wrap. Laid-out rows use height(at:), which includes wrapped lines. |
| 1250 | private func height(for row: ReviewDiffNativeRow) -> CGFloat { |
| 1251 | geometryConfiguration.height(for: row) |
| 1252 | } |
| 1253 | |
| 1254 | /// Laid-out height, including wrapped lines. Requires a layout built from the current rows. |
| 1255 | private func height(at index: Int) -> CGFloat { |
| 1256 | let nextOffset = index + 1 < rowOffsets.count ? rowOffsets[index + 1] : contentHeight |
| 1257 | return nextOffset - rowOffsets[index] |
| 1258 | } |
| 1259 | |
| 1260 | private var codeWrapLineHeight: CGFloat { |
| 1261 | ceil(codeFont.lineHeight) |
| 1262 | } |
| 1263 | |
| 1264 | private func codeLayoutWidthLimit(font: UIFont) -> CGFloat? { |
| 1265 | guard style.wordWrap else { return ReviewDiffCodeLayout.unboundedWidth } |
| 1266 | let width = viewportWidth - codeStartX - style.codePadding |
| 1267 | let characterWidth = monospaceCharacterWidth(font: font) |
| 1268 | return characterWidth > 0 && width >= characterWidth ? width : nil |
| 1269 | } |
| 1270 | |
| 1271 | func frameForRow(at index: Int) -> CGRect? { |
| 1272 | guard rows.indices.contains(index), rowOffsets.indices.contains(index) else { |
| 1273 | return nil |
| 1274 | } |
| 1275 | |
| 1276 | return CGRect( |
| 1277 | x: 0, |
| 1278 | y: rowOffsets[index], |
| 1279 | width: max(viewportWidth, 1), |
| 1280 | height: height(at: index) |
| 1281 | ) |
| 1282 | } |
| 1283 | |
| 1284 | // Pixel offsets cannot identify the same code row after wrapping or font changes. |
| 1285 | func viewportRowAnchor() -> ReviewDiffViewportRowAnchor? { |
| 1286 | let top = max(0, verticalOffset + topContentInset) |
| 1287 | guard let index = rowIndex(at: top) else { return nil } |
| 1288 | return ReviewDiffViewportRowAnchor(rowIndex: index, intraRowOffset: top - rowOffsets[index]) |
| 1289 | } |
| 1290 | |
| 1291 | func offset(for anchor: ReviewDiffViewportRowAnchor) -> CGFloat? { |
| 1292 | guard let frame = frameForRow(at: anchor.rowIndex), frame.height > 0 else { return nil } |
| 1293 | let intraRowOffset = anchor.intraRowOffset < frame.height |
| 1294 | ? anchor.intraRowOffset : max(0, frame.height - 1) |
| 1295 | return frame.minY + intraRowOffset |
| 1296 | } |
| 1297 | |
| 1298 | func cancelRowPreparation() { |
| 1299 | rowPreparation?.cancel() |
| 1300 | rowPreparation = nil |
| 1301 | preparedRowGeometry = nil |
| 1302 | } |
| 1303 | |
| 1304 | /// Prepare immutable geometry on the decode worker; publication only swaps its buffers. |
| 1305 | func prepareRows( |
| 1306 | _ rows: [ReviewDiffNativeRow], |
| 1307 | on queue: DispatchQueue, |
| 1308 | isCurrent: @escaping () -> Bool, |
| 1309 | completion: @escaping () -> Void |
| 1310 | ) { |
| 1311 | cancelRowPreparation() |
| 1312 | let preparation = ReviewDiffRowPreparation() |
| 1313 | rowPreparation = preparation |
| 1314 | let configuration = geometryConfiguration |
| 1315 | let font = codeFont |
| 1316 | let characterWidth = monospaceCharacterWidth(font: font) |
| 1317 | let width = codeLayoutWidthLimit(font: font) |
| 1318 | let hunkFont = self.hunkFont |
| 1319 | let cached = codeLayoutWidth == width && codeLayoutFont == font ? codeLayoutsByRowId : [:] |
| 1320 | let input = ReviewDiffRowGeometryInput( |
| 1321 | configuration: configuration, font: font, hunkFont: hunkFont, |
| 1322 | characterWidth: characterWidth, layoutWidth: width, cached: cached |
| 1323 | ) |
| 1324 | queue.async { [weak self] in |
| 1325 | guard let geometry = Self.buildRowGeometry( |
| 1326 | rows, input: input, isCancelled: { preparation.isCancelled } |
| 1327 | ) else { return } |
| 1328 | DispatchQueue.main.async { [weak self] in |
| 1329 | guard let self, !preparation.isCancelled, isCurrent() else { return } |
| 1330 | if self.geometryConfiguration != configuration { |
| 1331 | self.prepareRows(rows, on: queue, isCurrent: isCurrent, completion: completion) |
| 1332 | return |
| 1333 | } |
| 1334 | self.rowPreparation = nil |
| 1335 | self.codeLayoutWidth = width |
| 1336 | self.codeLayoutFont = font |
| 1337 | self.preparedRowGeometry = geometry |
| 1338 | completion() |
| 1339 | } |
| 1340 | } |
| 1341 | } |
| 1342 | |
| 1343 | private func rebuildRowLayout() { |
| 1344 | let font = codeFont |
| 1345 | let characterWidth = monospaceCharacterWidth(font: font) |
| 1346 | let layoutWidth = codeLayoutWidthLimit(font: font) |
| 1347 | let cached = codeLayoutWidth == layoutWidth && codeLayoutFont == font ? codeLayoutsByRowId : [:] |
| 1348 | let input = ReviewDiffRowGeometryInput( |
| 1349 | configuration: geometryConfiguration, font: font, hunkFont: hunkFont, |
| 1350 | characterWidth: characterWidth, layoutWidth: layoutWidth, cached: cached |
| 1351 | ) |
| 1352 | guard let geometry = Self.buildRowGeometry(rows, input: input) else { return } |
| 1353 | codeLayoutWidth = layoutWidth |
| 1354 | codeLayoutFont = font |
| 1355 | applyRowGeometry(geometry) |
| 1356 | } |
| 1357 | |
| 1358 | private static func buildRowGeometry( |
| 1359 | _ rows: [ReviewDiffNativeRow], |
| 1360 | input: ReviewDiffRowGeometryInput, |
| 1361 | isCancelled: () -> Bool = { false } |
| 1362 | ) -> ReviewDiffRowGeometry? { |
| 1363 | var nextOffsets: [CGFloat] = [] |
| 1364 | var nextFileHeaderRowIndices: [Int] = [] |
| 1365 | nextOffsets.reserveCapacity(rows.count) |
| 1366 | var maxWidthsByFileId: [String: CGFloat] = [:] |
| 1367 | var nextCodeLayouts: [String: ReviewDiffCodeLayout] = [:] |
| 1368 | var offset: CGFloat = 0 |
| 1369 | let style = input.configuration.style |
| 1370 | let characterWidth = input.characterWidth |
| 1371 | let wrapColumns = style.wordWrap ? input.layoutWidth.map { Int($0 / characterWidth) } : nil |
| 1372 | |
| 1373 | for (index, row) in rows.enumerated() { |
| 1374 | // Bound obsolete work without locking once per row; never read UIView state here. |
| 1375 | if index.isMultiple(of: 256), isCancelled() { return nil } |
| 1376 | nextOffsets.append(offset) |
| 1377 | if row.kind == "file" { |
| 1378 | nextFileHeaderRowIndices.append(index) |
| 1379 | } |
| 1380 | var rowHeight = input.configuration.height(for: row) |
| 1381 | let fileId = row.resolvedFileId |
| 1382 | switch row.kind { |
| 1383 | case "line": |
| 1384 | let width = lineWidth( |
| 1385 | for: row, input: input, wrapColumns: wrapColumns, |
| 1386 | height: &rowHeight, layouts: &nextCodeLayouts |
| 1387 | ) |
| 1388 | maxWidthsByFileId[fileId] = max(maxWidthsByFileId[fileId] ?? 0, width) |
| 1389 | case "hunk": |
| 1390 | // Hunk context can hold tabs and draws in its own font. |
| 1391 | let width = ceil(((row.text ?? "") as NSString).size(withAttributes: [.font: input.hunkFont, .ligature: 0]).width) |
| 1392 | maxWidthsByFileId[fileId] = max(maxWidthsByFileId[fileId] ?? 0, width) |
| 1393 | default: |
| 1394 | break |
| 1395 | } |
| 1396 | offset += rowHeight |
| 1397 | } |
| 1398 | guard !isCancelled() else { return nil } |
| 1399 | return ReviewDiffRowGeometry( |
| 1400 | offsets: nextOffsets, fileHeaderIndices: nextFileHeaderRowIndices, |
| 1401 | contentWidths: maxWidthsByFileId.mapValues { ceil($0) + style.codePadding * 2 }, |
| 1402 | nativeLayouts: nextCodeLayouts, height: offset, |
| 1403 | characterWidth: characterWidth, wrapColumns: wrapColumns |
| 1404 | ) |
| 1405 | } |
| 1406 | |
| 1407 | private static func lineWidth( |
| 1408 | for row: ReviewDiffNativeRow, |
| 1409 | input: ReviewDiffRowGeometryInput, |
| 1410 | wrapColumns: Int?, |
| 1411 | height: inout CGFloat, |
| 1412 | layouts: inout [String: ReviewDiffCodeLayout] |
| 1413 | ) -> CGFloat { |
| 1414 | let characterWidth = input.characterWidth |
| 1415 | let font = input.font |
| 1416 | var width = CGFloat(row.content?.utf16.count ?? 0) * characterWidth |
| 1417 | if let layoutWidth = input.layoutWidth, let content = row.content { |
| 1418 | if ReviewDiffCodeLayout.isPrintableASCII(content) { |
| 1419 | let length = content.utf8.count |
| 1420 | let starts = ReviewDiffCodeLineStarts(length: length, columns: wrapColumns) |
| 1421 | width = CGFloat(min(length, starts.columns)) * characterWidth |
| 1422 | if height > 0 { |
| 1423 | height = max(height, font.lineHeight) + CGFloat(starts.count - 1) * ceil(font.lineHeight) |
| 1424 | } |
| 1425 | } else { |
| 1426 | let layout: ReviewDiffCodeLayout |
| 1427 | if let previous = input.cached[row.id], previous.text == content { |
| 1428 | layout = previous |
| 1429 | } else { |
| 1430 | layout = ReviewDiffCodeLayout( |
| 1431 | text: content, font: font, width: layoutWidth, characterWidth: characterWidth |
| 1432 | ) |
| 1433 | } |
| 1434 | layouts[row.id] = layout |
| 1435 | width = layout.usedWidth |
| 1436 | if height > 0 { |
| 1437 | height = max(height, layout.firstLineHeight) + layout.extraHeight |
| 1438 | } |
| 1439 | } |
| 1440 | } |
| 1441 | return width |
| 1442 | } |
| 1443 | |
| 1444 | private func applyRowGeometry(_ geometry: ReviewDiffRowGeometry) { |
| 1445 | codeCharacterWidth = geometry.characterWidth |
| 1446 | codeWrapColumns = geometry.wrapColumns |
| 1447 | codeLayoutsByRowId = geometry.nativeLayouts |
| 1448 | contentWidthsByFileId = geometry.contentWidths |
| 1449 | rowOffsets = geometry.offsets |
| 1450 | fileHeaderRowIndices = geometry.fileHeaderIndices |
| 1451 | contentHeight = geometry.height |
| 1452 | } |
| 1453 | |
| 1454 | private var codeFont: UIFont { |
| 1455 | UIFont.monospacedSystemFont(ofSize: style.codeFontSize, weight: style.codeFontWeight) |
| 1456 | } |
| 1457 | |
| 1458 | private var lineNumberFont: UIFont { |
| 1459 | UIFont.monospacedSystemFont(ofSize: style.lineNumberFontSize, weight: style.lineNumberFontWeight) |
| 1460 | } |
| 1461 | |
| 1462 | private var hunkFont: UIFont { |
| 1463 | UIFont.monospacedSystemFont(ofSize: style.hunkFontSize, weight: style.hunkFontWeight) |
| 1464 | } |
| 1465 | |
| 1466 | private var fileHeaderFont: UIFont { |
| 1467 | UIFont.systemFont(ofSize: style.fileHeaderFontSize, weight: style.fileHeaderFontWeight) |
| 1468 | } |
| 1469 | |
| 1470 | private var fileHeaderMetaFont: UIFont { |
| 1471 | UIFont.systemFont(ofSize: style.fileHeaderMetaFontSize, weight: style.fileHeaderMetaFontWeight) |
| 1472 | } |
| 1473 | |
| 1474 | private var fileHeaderSubtextFont: UIFont { |
| 1475 | UIFont.systemFont(ofSize: style.fileHeaderSubtextFontSize, weight: style.fileHeaderSubtextFontWeight) |
| 1476 | } |
| 1477 | |
| 1478 | private var fileHeaderStatusFont: UIFont { |
| 1479 | UIFont.systemFont(ofSize: style.fileHeaderStatusFontSize, weight: style.fileHeaderStatusFontWeight) |
| 1480 | } |
| 1481 | |
| 1482 | private var emptyStateFont: UIFont { |
| 1483 | UIFont.systemFont(ofSize: style.emptyStateFontSize, weight: style.emptyStateFontWeight) |
| 1484 | } |
| 1485 | |
| 1486 | private lazy var horizontalPanGesture: UIPanGestureRecognizer = { |
| 1487 | let gesture = UIPanGestureRecognizer(target: self, action: #selector(handleHorizontalPan(_:))) |
| 1488 | gesture.delegate = self |
| 1489 | gesture.cancelsTouchesInView = false |
| 1490 | return gesture |
| 1491 | }() |
| 1492 | |
| 1493 | private lazy var tapGesture: UITapGestureRecognizer = { |
| 1494 | let gesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))) |
| 1495 | gesture.delegate = self |
| 1496 | gesture.cancelsTouchesInView = false |
| 1497 | return gesture |
| 1498 | }() |
| 1499 | |
| 1500 | private lazy var longPressGesture: UILongPressGestureRecognizer = { |
| 1501 | let gesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:))) |
| 1502 | gesture.delegate = self |
| 1503 | gesture.cancelsTouchesInView = false |
| 1504 | gesture.minimumPressDuration = 0.28 |
| 1505 | return gesture |
| 1506 | }() |
| 1507 | |
| 1508 | override init(frame: CGRect) { |
| 1509 | super.init(frame: frame) |
| 1510 | isOpaque = true |
| 1511 | contentMode = .redraw |
| 1512 | addGestureRecognizer(horizontalPanGesture) |
| 1513 | addGestureRecognizer(tapGesture) |
| 1514 | addGestureRecognizer(longPressGesture) |
| 1515 | tapGesture.require(toFail: longPressGesture) |
| 1516 | } |
| 1517 | |
| 1518 | func invalidateVisibleViewport() { |
| 1519 | setNeedsDisplayForVisibleBounds() |
| 1520 | } |
| 1521 | |
| 1522 | private func setNeedsDisplayForVisibleBounds() { |
| 1523 | setNeedsDisplay() |
| 1524 | } |
| 1525 | |
| 1526 | required init?(coder: NSCoder) { |
| 1527 | super.init(coder: coder) |
| 1528 | isOpaque = true |
| 1529 | contentMode = .redraw |
| 1530 | addGestureRecognizer(horizontalPanGesture) |
| 1531 | addGestureRecognizer(tapGesture) |
| 1532 | addGestureRecognizer(longPressGesture) |
| 1533 | tapGesture.require(toFail: longPressGesture) |
| 1534 | } |
| 1535 | |
| 1536 | override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { |
| 1537 | guard gestureRecognizer === horizontalPanGesture else { |
| 1538 | return true |
| 1539 | } |
| 1540 | |
| 1541 | let velocity = horizontalPanGesture.velocity(in: self) |
| 1542 | guard abs(velocity.x) > abs(velocity.y) * 1.25 else { |
| 1543 | return false |
| 1544 | } |
| 1545 | |
| 1546 | guard let panTarget = horizontalPanTarget(at: horizontalPanGesture.location(in: self)) else { |
| 1547 | return false |
| 1548 | } |
| 1549 | |
| 1550 | let currentOffset = horizontalOffset(for: panTarget.fileId, kind: panTarget.kind) |
| 1551 | if velocity.x > 0 && currentOffset <= 0.5 { |
| 1552 | return false |
| 1553 | } |
| 1554 | |
| 1555 | return maxHorizontalOffset(for: panTarget) > 0 |
| 1556 | } |
| 1557 | |
| 1558 | @objc private func handleTap(_ gesture: UITapGestureRecognizer) { |
| 1559 | guard gesture.state == .ended else { |
| 1560 | return |
| 1561 | } |
| 1562 | |
| 1563 | let point = gesture.location(in: self) |
| 1564 | if let stickyHeader = stickyFileHeaderTarget(), stickyHeader.rect.contains(point) { |
| 1565 | handleFileHeaderTap(row: stickyHeader.row, rect: stickyHeader.rect, point: point) |
| 1566 | return |
| 1567 | } |
| 1568 | |
| 1569 | guard let rowIndex = rowIndex(at: verticalOffset + point.y), |
| 1570 | rows.indices.contains(rowIndex) else { |
| 1571 | return |
| 1572 | } |
| 1573 | |
| 1574 | let row = rows[rowIndex] |
| 1575 | if row.kind == "comment" { |
| 1576 | onToggleComment?(row.id) |
| 1577 | return |
| 1578 | } |
| 1579 | |
| 1580 | if row.kind == "notice", row.actionable == true { |
| 1581 | onPressNotice?(["rowId": row.id, "fileId": resolvedFileId(for: row)]) |
| 1582 | return |
| 1583 | } |
| 1584 | |
| 1585 | if row.kind == "line" { |
| 1586 | onPressLine?(linePressPayload(for: row, gesture: "tap")) |
| 1587 | return |
| 1588 | } |
| 1589 | |
| 1590 | guard row.kind == "file" else { |
| 1591 | return |
| 1592 | } |
| 1593 | |
| 1594 | let rowY = rowOffsets[rowIndex] - verticalOffset |
| 1595 | let rect = CGRect(x: 0, y: rowY, width: max(bounds.width, viewportWidth), height: height(for: row)) |
| 1596 | handleFileHeaderTap(row: row, rect: rect, point: point) |
| 1597 | } |
| 1598 | |
| 1599 | @objc private func handleLongPress(_ gesture: UILongPressGestureRecognizer) { |
| 1600 | guard gesture.state == .began else { |
| 1601 | return |
| 1602 | } |
| 1603 | |
| 1604 | let point = gesture.location(in: self) |
| 1605 | if let stickyHeader = stickyFileHeaderTarget(), stickyHeader.rect.contains(point) { |
| 1606 | return |
| 1607 | } |
| 1608 | |
| 1609 | guard let rowIndex = rowIndex(at: verticalOffset + point.y), |
| 1610 | rows.indices.contains(rowIndex) else { |
| 1611 | return |
| 1612 | } |
| 1613 | |
| 1614 | let row = rows[rowIndex] |
| 1615 | guard row.kind == "line" else { |
| 1616 | return |
| 1617 | } |
| 1618 | |
| 1619 | onPressLine?(linePressPayload(for: row, gesture: "longPress")) |
| 1620 | } |
| 1621 | |
| 1622 | private func linePressPayload(for row: ReviewDiffNativeRow, gesture: String) -> [String: Any] { |
| 1623 | var payload: [String: Any] = [ |
| 1624 | "rowId": row.id, |
| 1625 | "fileId": resolvedFileId(for: row), |
| 1626 | "gesture": gesture |
| 1627 | ] |
| 1628 | |
| 1629 | if let oldLineNumber = row.oldLineNumber { |
| 1630 | payload["oldLineNumber"] = oldLineNumber |
| 1631 | } |
| 1632 | if let newLineNumber = row.newLineNumber { |
| 1633 | payload["newLineNumber"] = newLineNumber |
| 1634 | } |
| 1635 | if let change = row.change { |
| 1636 | payload["change"] = change |
| 1637 | } |
| 1638 | |
| 1639 | return payload |
| 1640 | } |
| 1641 | |
| 1642 | private func handleFileHeaderTap(row: ReviewDiffNativeRow, rect: CGRect, point: CGPoint) { |
| 1643 | let interactiveRects = fileHeaderInteractiveRects(for: row, cardRect: rect) |
| 1644 | let fileId = resolvedFileId(for: row) |
| 1645 | |
| 1646 | if interactiveRects.checkbox.contains(point) { |
| 1647 | onToggleViewedFile?(fileId) |
| 1648 | return |
| 1649 | } |
| 1650 | |
| 1651 | if rect.contains(point) { |
| 1652 | onToggleFile?(fileId) |
| 1653 | } |
| 1654 | } |
| 1655 | |
| 1656 | func gestureRecognizer( |
| 1657 | _ gestureRecognizer: UIGestureRecognizer, |
| 1658 | shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer |
| 1659 | ) -> Bool { |
| 1660 | false |
| 1661 | } |
| 1662 | |
| 1663 | @objc private func handleHorizontalPan(_ gesture: UIPanGestureRecognizer) { |
| 1664 | switch gesture.state { |
| 1665 | case .began: |
| 1666 | stopHorizontalDeceleration() |
| 1667 | let panTarget = horizontalPanTarget(at: gesture.location(in: self)) |
| 1668 | activePanFileId = panTarget?.fileId |
| 1669 | activePanKind = panTarget?.kind |
| 1670 | panStartHorizontalOffset = horizontalOffset(for: panTarget?.fileId, kind: panTarget?.kind) |
| 1671 | case .changed, .ended, .cancelled: |
| 1672 | guard let activePanFileId, let activePanKind else { |
| 1673 | return |
| 1674 | } |
| 1675 | let translation = gesture.translation(in: self) |
| 1676 | setHorizontalOffset( |
| 1677 | min( |
| 1678 | max(panStartHorizontalOffset - translation.x, 0), |
| 1679 | maxHorizontalOffset(for: (fileId: activePanFileId, kind: activePanKind)) |
| 1680 | ), |
| 1681 | for: activePanFileId, |
| 1682 | kind: activePanKind |
| 1683 | ) |
| 1684 | if gesture.state == .ended, activePanKind == .code { |
| 1685 | let velocity = -gesture.velocity(in: self).x |
| 1686 | self.activePanFileId = nil |
| 1687 | self.activePanKind = nil |
| 1688 | startHorizontalDeceleration(fileId: activePanFileId, velocity: velocity) |
| 1689 | } else if gesture.state == .cancelled { |
| 1690 | self.activePanFileId = nil |
| 1691 | self.activePanKind = nil |
| 1692 | } else if gesture.state == .ended { |
| 1693 | self.activePanFileId = nil |
| 1694 | self.activePanKind = nil |
| 1695 | } |
| 1696 | default: |
| 1697 | break |
| 1698 | } |
| 1699 | } |
| 1700 | |
| 1701 | private func horizontalPanTarget(at point: CGPoint) -> (fileId: String, kind: ReviewDiffHorizontalPanKind)? { |
| 1702 | if let stickyHeader = stickyFileHeaderTarget(), stickyHeader.rect.contains(point) { |
| 1703 | return (resolvedFileId(for: stickyHeader.row), .fileHeaderPath) |
| 1704 | } |
| 1705 | |
| 1706 | guard let row = row(at: point) else { |
| 1707 | guard verticalOffset + point.y >= contentHeight, |
| 1708 | fileHeaderRowIndices.isEmpty, |
| 1709 | contentWidthsByFileId.count == 1, |
| 1710 | let fileId = contentWidthsByFileId.keys.first, |
| 1711 | !collapsedFileIds.contains(fileId) else { |
| 1712 | return nil |
| 1713 | } |
| 1714 | return (fileId, .code) |
| 1715 | } |
| 1716 | |
| 1717 | let fileId = resolvedFileId(for: row) |
| 1718 | if row.kind == "file" { |
| 1719 | return (fileId, .fileHeaderPath) |
| 1720 | } |
| 1721 | |
| 1722 | return (fileId, .code) |
| 1723 | } |
| 1724 | |
| 1725 | private func stickyFileHeaderTarget() -> ReviewDiffStickyFileHeaderTarget? { |
| 1726 | guard let stickyHeader = stickyFileHeaderRowIndex() else { |
| 1727 | return nil |
| 1728 | } |
| 1729 | |
| 1730 | let rowIndex = stickyHeader.rowIndex |
| 1731 | let headerTop = rowOffsets[rowIndex] |
| 1732 | guard headerTop < verticalOffset + topContentInset else { |
| 1733 | return nil |
| 1734 | } |
| 1735 | |
| 1736 | let nextHeaderPosition = stickyHeader.position + 1 |
| 1737 | let nextHeaderRowIndex = fileHeaderRowIndices.indices.contains(nextHeaderPosition) |
| 1738 | ? fileHeaderRowIndices[nextHeaderPosition] |
| 1739 | : nil |
| 1740 | let pushedY: CGFloat |
| 1741 | if let nextHeaderRowIndex { |
| 1742 | pushedY = min(topContentInset, rowOffsets[nextHeaderRowIndex] - verticalOffset - style.fileHeaderHeight) |
| 1743 | } else { |
| 1744 | pushedY = topContentInset |
| 1745 | } |
| 1746 | |
| 1747 | guard pushedY > topContentInset - style.fileHeaderHeight else { |
| 1748 | return nil |
| 1749 | } |
| 1750 | |
| 1751 | let rect = CGRect( |
| 1752 | x: 0, |
| 1753 | y: pushedY, |
| 1754 | width: max(bounds.width, viewportWidth), |
| 1755 | height: style.fileHeaderHeight |
| 1756 | ) |
| 1757 | return ReviewDiffStickyFileHeaderTarget(rowIndex: rowIndex, row: rows[rowIndex], rect: rect) |
| 1758 | } |
| 1759 | |
| 1760 | private func stickyFileHeaderRowIndex() -> ReviewDiffStickyFileHeaderIndex? { |
| 1761 | guard !fileHeaderRowIndices.isEmpty else { |
| 1762 | return nil |
| 1763 | } |
| 1764 | |
| 1765 | var lowerBound = 0 |
| 1766 | var upperBound = fileHeaderRowIndices.count |
| 1767 | while lowerBound < upperBound { |
| 1768 | let midpoint = (lowerBound + upperBound) / 2 |
| 1769 | let rowIndex = fileHeaderRowIndices[midpoint] |
| 1770 | if rowOffsets[rowIndex] <= verticalOffset + topContentInset { |
| 1771 | lowerBound = midpoint + 1 |
| 1772 | } else { |
| 1773 | upperBound = midpoint |
| 1774 | } |
| 1775 | } |
| 1776 | |
| 1777 | let matchIndex = lowerBound - 1 |
| 1778 | guard matchIndex >= 0 else { |
| 1779 | return nil |
| 1780 | } |
| 1781 | return ReviewDiffStickyFileHeaderIndex(position: matchIndex, rowIndex: fileHeaderRowIndices[matchIndex]) |
| 1782 | } |
| 1783 | |
| 1784 | func scrollAnchor(forFileId fileId: String) -> ReviewDiffScrollAnchor? { |
| 1785 | if let stickyHeader = stickyFileHeaderTarget(), |
| 1786 | resolvedFileId(for: stickyHeader.row) == fileId { |
| 1787 | return ReviewDiffScrollAnchor(fileId: fileId, screenY: topContentInset) |
| 1788 | } |
| 1789 | |
| 1790 | guard let headerOffset = fileHeaderOffset(forFileId: fileId) else { |
| 1791 | return nil |
| 1792 | } |
| 1793 | |
| 1794 | return ReviewDiffScrollAnchor(fileId: fileId, screenY: headerOffset - verticalOffset) |
| 1795 | } |
| 1796 | |
| 1797 | func fileHeaderOffset(forFileId fileId: String) -> CGFloat? { |
| 1798 | guard let rowIndex = fileHeaderRowIndex(forFileId: fileId) else { |
| 1799 | return nil |
| 1800 | } |
| 1801 | |
| 1802 | return rowOffsets[rowIndex] |
| 1803 | } |
| 1804 | |
| 1805 | func visibleFileId(atVerticalOffset verticalOffset: CGFloat) -> String? { |
| 1806 | guard let firstHeaderRowIndex = fileHeaderRowIndices.first else { |
| 1807 | return nil |
| 1808 | } |
| 1809 | |
| 1810 | var lowerBound = 0 |
| 1811 | var upperBound = fileHeaderRowIndices.count |
| 1812 | while lowerBound < upperBound { |
| 1813 | let midpoint = (lowerBound + upperBound) / 2 |
| 1814 | let rowIndex = fileHeaderRowIndices[midpoint] |
| 1815 | if rowOffsets[rowIndex] <= verticalOffset + 0.5 { |
| 1816 | lowerBound = midpoint + 1 |
| 1817 | } else { |
| 1818 | upperBound = midpoint |
| 1819 | } |
| 1820 | } |
| 1821 | |
| 1822 | let rowIndex = lowerBound > 0 |
| 1823 | ? fileHeaderRowIndices[lowerBound - 1] |
| 1824 | : firstHeaderRowIndex |
| 1825 | guard rows.indices.contains(rowIndex) else { |
| 1826 | return nil |
| 1827 | } |
| 1828 | return resolvedFileId(for: rows[rowIndex]) |
| 1829 | } |
| 1830 | |
| 1831 | private func fileHeaderRowIndex(forFileId fileId: String) -> Int? { |
| 1832 | fileHeaderRowIndices.first { rowIndex in |
| 1833 | rows.indices.contains(rowIndex) && resolvedFileId(for: rows[rowIndex]) == fileId |
| 1834 | } |
| 1835 | } |
| 1836 | |
| 1837 | private func row(at point: CGPoint) -> ReviewDiffNativeRow? { |
| 1838 | guard let rowIndex = rowIndex(at: verticalOffset + point.y) else { |
| 1839 | return nil |
| 1840 | } |
| 1841 | guard rows.indices.contains(rowIndex) else { |
| 1842 | return nil |
| 1843 | } |
| 1844 | return rows[rowIndex] |
| 1845 | } |
| 1846 | |
| 1847 | private func rowIndex(at absoluteY: CGFloat) -> Int? { |
| 1848 | guard !rows.isEmpty else { |
| 1849 | return nil |
| 1850 | } |
| 1851 | |
| 1852 | var lowerBound = 0 |
| 1853 | var upperBound = rows.count - 1 |
| 1854 | while lowerBound <= upperBound { |
| 1855 | let midpoint = (lowerBound + upperBound) / 2 |
| 1856 | let rowStart = rowOffsets[midpoint] |
| 1857 | let rowEnd = rowStart + height(at: midpoint) |
| 1858 | |
| 1859 | if absoluteY < rowStart { |
| 1860 | upperBound = midpoint - 1 |
| 1861 | } else if absoluteY >= rowEnd { |
| 1862 | lowerBound = midpoint + 1 |
| 1863 | } else { |
| 1864 | return midpoint |
| 1865 | } |
| 1866 | } |
| 1867 | |
| 1868 | return nil |
| 1869 | } |
| 1870 | |
| 1871 | private func firstVisibleRowIndex(atOrAfter absoluteY: CGFloat) -> Int? { |
| 1872 | guard !rows.isEmpty else { |
| 1873 | return nil |
| 1874 | } |
| 1875 | |
| 1876 | var lowerBound = 0 |
| 1877 | var upperBound = rows.count |
| 1878 | while lowerBound < upperBound { |
| 1879 | let midpoint = (lowerBound + upperBound) / 2 |
| 1880 | let rowEnd = rowOffsets[midpoint] + height(at: midpoint) |
| 1881 | |
| 1882 | if rowEnd < absoluteY { |
| 1883 | lowerBound = midpoint + 1 |
| 1884 | } else { |
| 1885 | upperBound = midpoint |
| 1886 | } |
| 1887 | } |
| 1888 | |
| 1889 | return lowerBound < rows.count ? lowerBound : nil |
| 1890 | } |
| 1891 | |
| 1892 | private func lastVisibleRowIndex(atOrBefore absoluteY: CGFloat) -> Int? { |
| 1893 | guard !rows.isEmpty else { |
| 1894 | return nil |
| 1895 | } |
| 1896 | |
| 1897 | var lowerBound = 0 |
| 1898 | var upperBound = rows.count |
| 1899 | while lowerBound < upperBound { |
| 1900 | let midpoint = (lowerBound + upperBound) / 2 |
| 1901 | let rowStart = rowOffsets[midpoint] |
| 1902 | |
| 1903 | if rowStart <= absoluteY { |
| 1904 | lowerBound = midpoint + 1 |
| 1905 | } else { |
| 1906 | upperBound = midpoint |
| 1907 | } |
| 1908 | } |
| 1909 | |
| 1910 | let index = lowerBound - 1 |
| 1911 | return index >= 0 ? index : nil |
| 1912 | } |
| 1913 | |
| 1914 | private func resolvedFileId(for row: ReviewDiffNativeRow) -> String { |
| 1915 | row.resolvedFileId |
| 1916 | } |
| 1917 | |
| 1918 | private func horizontalOffset( |
| 1919 | for fileId: String?, |
| 1920 | kind: ReviewDiffHorizontalPanKind? = .code |
| 1921 | ) -> CGFloat { |
| 1922 | guard let fileId else { |
| 1923 | return 0 |
| 1924 | } |
| 1925 | if kind == .fileHeaderPath { |
| 1926 | return headerPathOffsetsByFileId[fileId] ?? 0 |
| 1927 | } |
| 1928 | return horizontalOffsetsByFileId[fileId] ?? 0 |
| 1929 | } |
| 1930 | |
| 1931 | private func setHorizontalOffset( |
| 1932 | _ offset: CGFloat, |
| 1933 | for fileId: String, |
| 1934 | kind: ReviewDiffHorizontalPanKind = .code |
| 1935 | ) { |
| 1936 | if kind == .fileHeaderPath { |
| 1937 | headerPathOffsetsByFileId[fileId] = offset |
| 1938 | setNeedsDisplayForVisibleBounds() |
| 1939 | return |
| 1940 | } |
| 1941 | horizontalOffsetsByFileId[fileId] = offset |
| 1942 | setNeedsDisplayForVisibleBounds() |
| 1943 | } |
| 1944 | |
| 1945 | private func clampHorizontalOffsets() { |
| 1946 | for (fileId, offset) in horizontalOffsetsByFileId { |
| 1947 | horizontalOffsetsByFileId[fileId] = min(offset, maxHorizontalOffset(for: (fileId: fileId, kind: .code))) |
| 1948 | } |
| 1949 | for (fileId, offset) in headerPathOffsetsByFileId { |
| 1950 | headerPathOffsetsByFileId[fileId] = min( |
| 1951 | offset, |
| 1952 | maxHorizontalOffset(for: (fileId: fileId, kind: .fileHeaderPath)) |
| 1953 | ) |
| 1954 | } |
| 1955 | } |
| 1956 | |
| 1957 | private func maxHorizontalOffset(for target: (fileId: String, kind: ReviewDiffHorizontalPanKind)) -> CGFloat { |
| 1958 | if target.kind == .fileHeaderPath, |
| 1959 | let rowIndex = fileHeaderRowIndex(forFileId: target.fileId) { |
| 1960 | return maxHeaderPathOffset(for: rows[rowIndex]) |
| 1961 | } |
| 1962 | if codeWrapColumns != nil { |
| 1963 | return 0 |
| 1964 | } |
| 1965 | |
| 1966 | return max(0, contentWidth(for: target.fileId) - max(0, viewportWidth - codeStartX)) |
| 1967 | } |
| 1968 | |
| 1969 | private func contentWidth(for fileId: String) -> CGFloat { |
| 1970 | contentWidthsByFileId[fileId] ?? min(style.contentWidth, max(viewportWidth, 0)) |
| 1971 | } |
| 1972 | |
| 1973 | func currentVisibleRowRange() -> (firstRowIndex: Int, lastRowIndex: Int)? { |
| 1974 | guard !rows.isEmpty else { |
| 1975 | return nil |
| 1976 | } |
| 1977 | |
| 1978 | let visibleMinY = verticalOffset |
| 1979 | let visibleMaxY = verticalOffset + max(bounds.height, 1) |
| 1980 | guard let firstRowIndex = firstVisibleRowIndex(atOrAfter: visibleMinY), |
| 1981 | let lastRowIndex = lastVisibleRowIndex(atOrBefore: visibleMaxY), |
| 1982 | firstRowIndex <= lastRowIndex else { |
| 1983 | return nil |
| 1984 | } |
| 1985 | |
| 1986 | return (firstRowIndex: firstRowIndex, lastRowIndex: lastRowIndex) |
| 1987 | } |
| 1988 | |
| 1989 | private func maxHeaderPathOffset(for row: ReviewDiffNativeRow) -> CGFloat { |
| 1990 | let fullRect = CGRect(x: 0, y: 0, width: max(bounds.width, viewportWidth), height: height(for: row)) |
| 1991 | let layout = fileHeaderPathLayout(for: row, cardRect: fullRect) |
| 1992 | let pathWidth = textWidth(layout.displayPath, font: fileHeaderFont) |
| 1993 | return max(0, pathWidth - layout.rect.width) |
| 1994 | } |
| 1995 | |
| 1996 | private func startHorizontalDeceleration(fileId: String, velocity: CGFloat) { |
| 1997 | guard abs(velocity) > 80 else { |
| 1998 | return |
| 1999 | } |
| 2000 | |
| 2001 | let currentOffset = horizontalOffset(for: fileId) |
| 2002 | let maxOffset = maxHorizontalOffset(for: (fileId: fileId, kind: .code)) |
| 2003 | if (currentOffset <= 0 && velocity < 0) || (currentOffset >= maxOffset && velocity > 0) { |
| 2004 | return |
| 2005 | } |
| 2006 | |
| 2007 | stopHorizontalDeceleration() |
| 2008 | deceleratingFileId = fileId |
| 2009 | horizontalVelocity = velocity |
| 2010 | lastDecelerationTimestamp = 0 |
| 2011 | |
| 2012 | let displayLink = CADisplayLink(target: self, selector: #selector(stepHorizontalDeceleration(_:))) |
| 2013 | displayLink.add(to: .main, forMode: .common) |
| 2014 | decelerationDisplayLink = displayLink |
| 2015 | } |
| 2016 | |
| 2017 | @objc private func stepHorizontalDeceleration(_ displayLink: CADisplayLink) { |
| 2018 | guard let fileId = deceleratingFileId else { |
| 2019 | stopHorizontalDeceleration() |
| 2020 | return |
| 2021 | } |
| 2022 | |
| 2023 | if lastDecelerationTimestamp == 0 { |
| 2024 | lastDecelerationTimestamp = displayLink.timestamp |
| 2025 | return |
| 2026 | } |
| 2027 | |
| 2028 | let dt = max(0, displayLink.timestamp - lastDecelerationTimestamp) |
| 2029 | lastDecelerationTimestamp = displayLink.timestamp |
| 2030 | |
| 2031 | let maxOffset = maxHorizontalOffset(for: (fileId: fileId, kind: .code)) |
| 2032 | let nextOffset = horizontalOffset(for: fileId) + horizontalVelocity * CGFloat(dt) |
| 2033 | let clampedOffset = min(max(nextOffset, 0), maxOffset) |
| 2034 | setHorizontalOffset(clampedOffset, for: fileId) |
| 2035 | |
| 2036 | // UIScrollView deceleration rates are expressed per millisecond. |
| 2037 | horizontalVelocity *= CGFloat(pow(Double(UIScrollView.DecelerationRate.normal.rawValue), dt * 1000)) |
| 2038 | |
| 2039 | if abs(horizontalVelocity) < 20 || clampedOffset <= 0 || clampedOffset >= maxOffset { |
| 2040 | stopHorizontalDeceleration() |
| 2041 | } |
| 2042 | } |
| 2043 | |
| 2044 | private func stopHorizontalDeceleration() { |
| 2045 | decelerationDisplayLink?.invalidate() |
| 2046 | decelerationDisplayLink = nil |
| 2047 | deceleratingFileId = nil |
| 2048 | horizontalVelocity = 0 |
| 2049 | lastDecelerationTimestamp = 0 |
| 2050 | } |
| 2051 | |
| 2052 | deinit { |
| 2053 | stopHorizontalDeceleration() |
| 2054 | } |
| 2055 | |
| 2056 | override func draw(_ rect: CGRect) { |
| 2057 | let drawStartedAt = CACurrentMediaTime() |
| 2058 | guard let context = UIGraphicsGetCurrentContext() else { |
| 2059 | return |
| 2060 | } |
| 2061 | |
| 2062 | theme.background.setFill() |
| 2063 | context.fill(rect) |
| 2064 | |
| 2065 | if rows.isEmpty { |
| 2066 | drawEmptyState(rect) |
| 2067 | return |
| 2068 | } |
| 2069 | |
| 2070 | let visibleMinY = verticalOffset + rect.minY |
| 2071 | let visibleMaxY = verticalOffset + rect.maxY |
| 2072 | let overscan = max(style.rowHeight, style.fileHeaderHeight) * 4 |
| 2073 | let rangeMinY = max(0, visibleMinY - overscan) |
| 2074 | let rangeMaxY = visibleMaxY + overscan |
| 2075 | guard let firstRowIndex = firstVisibleRowIndex(atOrAfter: rangeMinY), |
| 2076 | let lastRowIndex = lastVisibleRowIndex(atOrBefore: rangeMaxY), |
| 2077 | firstRowIndex <= lastRowIndex else { |
| 2078 | return |
| 2079 | } |
| 2080 | |
| 2081 | var drawnRowCount = 0 |
| 2082 | for rowIndex in firstRowIndex...lastRowIndex { |
| 2083 | let rowStart = rowOffsets[rowIndex] |
| 2084 | let rowHeight = height(at: rowIndex) |
| 2085 | if rowHeight <= 0 { |
| 2086 | continue |
| 2087 | } |
| 2088 | let rowEnd = rowStart + rowHeight |
| 2089 | if rowEnd < visibleMinY || rowStart > visibleMaxY { |
| 2090 | continue |
| 2091 | } |
| 2092 | drawRow(rows[rowIndex], rowIndex: rowIndex, context: context) |
| 2093 | drawnRowCount += 1 |
| 2094 | } |
| 2095 | drawStickyFileHeader(context: context) |
| 2096 | |
| 2097 | maybeEmitDrawMetrics( |
| 2098 | drawnRowCount: drawnRowCount, |
| 2099 | durationMs: (CACurrentMediaTime() - drawStartedAt) * 1000, |
| 2100 | firstRowIndex: firstRowIndex, |
| 2101 | lastRowIndex: lastRowIndex |
| 2102 | ) |
| 2103 | } |
| 2104 | |
| 2105 | private func maybeEmitDrawMetrics( |
| 2106 | drawnRowCount: Int, |
| 2107 | durationMs: Double, |
| 2108 | firstRowIndex: Int, |
| 2109 | lastRowIndex: Int |
| 2110 | ) { |
| 2111 | guard !isVerticalScrollActive else { |
| 2112 | return |
| 2113 | } |
| 2114 | |
| 2115 | let now = CACurrentMediaTime() |
| 2116 | guard now - lastDrawMetricsTimestamp >= 1 else { |
| 2117 | return |
| 2118 | } |
| 2119 | |
| 2120 | lastDrawMetricsTimestamp = now |
| 2121 | onDrawMetrics?([ |
| 2122 | "drawnRows": drawnRowCount, |
| 2123 | "durationMs": durationMs, |
| 2124 | "firstRowIndex": firstRowIndex, |
| 2125 | "lastRowIndex": lastRowIndex, |
| 2126 | "scannedRows": lastRowIndex - firstRowIndex + 1, |
| 2127 | "totalRows": rows.count, |
| 2128 | ]) |
| 2129 | } |
| 2130 | |
| 2131 | private func drawEmptyState(_ rect: CGRect) { |
| 2132 | let message = "No native diff rows" |
| 2133 | let attributes: [NSAttributedString.Key: Any] = [ |
| 2134 | .font: emptyStateFont, |
| 2135 | .foregroundColor: theme.mutedText, |
| 2136 | ] |
| 2137 | message.draw(at: CGPoint(x: 16, y: rect.minY + 16), withAttributes: attributes) |
| 2138 | } |
| 2139 | |
| 2140 | private func drawRow(_ row: ReviewDiffNativeRow, rowIndex: Int, context: CGContext) { |
| 2141 | let rowY = rowOffsets[rowIndex] - verticalOffset |
| 2142 | let fullRect = CGRect(x: 0, y: rowY, width: max(bounds.width, viewportWidth), height: height(at: rowIndex)) |
| 2143 | |
| 2144 | switch row.kind { |
| 2145 | case "file": |
| 2146 | drawFileRow(row, rect: fullRect, context: context) |
| 2147 | case "hunk": |
| 2148 | drawHunkRow(row, rect: fullRect, context: context) |
| 2149 | case "notice": |
| 2150 | drawNoticeRow(row, rect: fullRect, context: context) |
| 2151 | case "comment": |
| 2152 | drawCommentRow(row, rect: fullRect, context: context) |
| 2153 | default: |
| 2154 | drawCodeRow(row, rect: fullRect, context: context) |
| 2155 | } |
| 2156 | } |
| 2157 | |
| 2158 | private func drawStickyFileHeader(context: CGContext) { |
| 2159 | guard let stickyHeader = stickyFileHeaderTarget() else { |
| 2160 | return |
| 2161 | } |
| 2162 | |
| 2163 | drawFileRow(stickyHeader.row, rect: stickyHeader.rect, context: context) |
| 2164 | } |
| 2165 | |
| 2166 | private func drawFileRow(_ row: ReviewDiffNativeRow, rect: CGRect, context: CGContext) { |
| 2167 | theme.background.setFill() |
| 2168 | context.fill(rect) |
| 2169 | |
| 2170 | let cardRect = rect |
| 2171 | theme.headerBackground.setFill() |
| 2172 | context.fill(cardRect) |
| 2173 | |
| 2174 | let hairline = 1 / traitCollection.displayScale |
| 2175 | theme.border.setFill() |
| 2176 | context.fill(CGRect(x: cardRect.minX, y: cardRect.maxY - hairline, width: cardRect.width, height: hairline)) |
| 2177 | |
| 2178 | let centerY = cardRect.midY |
| 2179 | let interactiveRects = fileHeaderInteractiveRects(for: row, cardRect: cardRect) |
| 2180 | let fileId = resolvedFileId(for: row) |
| 2181 | drawDisclosureChevron( |
| 2182 | rect: interactiveRects.chevron, |
| 2183 | color: theme.mutedText, |
| 2184 | collapsed: collapsedFileIds.contains(fileId) |
| 2185 | ) |
| 2186 | |
| 2187 | drawFileIcon(rect: interactiveRects.icon, changeType: row.changeType) |
| 2188 | |
| 2189 | drawViewedCheckbox(rect: interactiveRects.checkbox, checked: viewedFileIds.contains(fileId)) |
| 2190 | |
| 2191 | let deletions = row.deletions ?? 0 |
| 2192 | let additions = row.additions ?? 0 |
| 2193 | let deleteText = "-\(deletions)" |
| 2194 | let addText = "+\(additions)" |
| 2195 | let deleteWidth = textWidth(deleteText, font: fileHeaderMetaFont) |
| 2196 | let addWidth = textWidth(addText, font: fileHeaderMetaFont) |
| 2197 | let countsGap = min(style.fileHeaderCountGap, 4) |
| 2198 | let countsWidth = deleteWidth + countsGap + addWidth |
| 2199 | let countsX = interactiveRects.checkbox.minX - 10 - countsWidth |
| 2200 | drawSingleLineText( |
| 2201 | deleteText, |
| 2202 | rect: CGRect(x: countsX, y: centerY - 9, width: deleteWidth, height: 18), |
| 2203 | color: theme.deleteText, |
| 2204 | font: fileHeaderMetaFont |
| 2205 | ) |
| 2206 | drawSingleLineText( |
| 2207 | addText, |
| 2208 | rect: CGRect(x: countsX + deleteWidth + countsGap, y: centerY - 9, width: addWidth, height: 18), |
| 2209 | color: theme.addText, |
| 2210 | font: fileHeaderMetaFont |
| 2211 | ) |
| 2212 | |
| 2213 | let pathLayout = fileHeaderPathLayout(for: row, cardRect: cardRect) |
| 2214 | let pathOffset = horizontalOffset(for: resolvedFileId(for: row), kind: .fileHeaderPath) |
| 2215 | drawSingleLineText( |
| 2216 | pathLayout.displayPath, |
| 2217 | rect: pathLayout.rect, |
| 2218 | color: theme.text, |
| 2219 | font: fileHeaderFont, |
| 2220 | horizontalOffset: pathOffset |
| 2221 | ) |
| 2222 | drawFileHeaderPathScrollFade(row, pathRect: pathLayout.rect, horizontalOffset: pathOffset, context: context) |
| 2223 | } |
| 2224 | |
| 2225 | private func drawNoticeRow(_ row: ReviewDiffNativeRow, rect: CGRect, context: CGContext) { |
| 2226 | guard !collapsedFileIds.contains(resolvedFileId(for: row)) else { |
| 2227 | return |
| 2228 | } |
| 2229 | |
| 2230 | let warning = row.tone == "warning" |
| 2231 | (warning ? theme.warningBackground : theme.background).setFill() |
| 2232 | context.fill(rect) |
| 2233 | |
| 2234 | let hairline = 1 / traitCollection.displayScale |
| 2235 | theme.border.withAlphaComponent(0.65).setFill() |
| 2236 | context.fill(CGRect(x: 0, y: rect.maxY - hairline, width: rect.width, height: hairline)) |
| 2237 | |
| 2238 | let iconSize: CGFloat = 16 |
| 2239 | let iconRect = CGRect( |
| 2240 | x: style.fileHeaderHorizontalPadding + 2, |
| 2241 | y: rect.midY - iconSize / 2, |
| 2242 | width: iconSize, |
| 2243 | height: iconSize |
| 2244 | ) |
| 2245 | let noticeColor = warning ? theme.warningText : theme.mutedText |
| 2246 | drawNoticeIcon(rect: iconRect, color: noticeColor) |
| 2247 | |
| 2248 | drawSingleLineText( |
| 2249 | row.text ?? "", |
| 2250 | rect: CGRect( |
| 2251 | x: iconRect.maxX + 10, |
| 2252 | y: rect.midY - fileHeaderSubtextFont.lineHeight / 2, |
| 2253 | width: max(24, viewportWidth - iconRect.maxX - 10 - style.fileHeaderHorizontalPadding), |
| 2254 | height: fileHeaderSubtextFont.lineHeight |
| 2255 | ), |
| 2256 | color: noticeColor, |
| 2257 | font: fileHeaderSubtextFont |
| 2258 | ) |
| 2259 | } |
| 2260 | |
| 2261 | private func drawCommentRow(_ row: ReviewDiffNativeRow, rect: CGRect, context: CGContext) { |
| 2262 | guard !collapsedFileIds.contains(resolvedFileId(for: row)) else { |
| 2263 | return |
| 2264 | } |
| 2265 | |
| 2266 | theme.background.setFill() |
| 2267 | context.fill(rect) |
| 2268 | |
| 2269 | let isCollapsed = collapsedCommentIds.contains(row.id) |
| 2270 | let cardInset = CGFloat(8) |
| 2271 | let cardRect = rect.insetBy(dx: cardInset, dy: 5) |
| 2272 | let cardPath = UIBezierPath(roundedRect: cardRect, cornerRadius: 10) |
| 2273 | theme.headerBackground.setFill() |
| 2274 | cardPath.fill() |
| 2275 | theme.border.withAlphaComponent(0.85).setStroke() |
| 2276 | cardPath.lineWidth = 1 |
| 2277 | cardPath.stroke() |
| 2278 | |
| 2279 | let chevronRect = CGRect(x: cardRect.minX + 10, y: cardRect.minY + 11, width: 16, height: 16) |
| 2280 | drawDisclosureChevron(rect: chevronRect, color: theme.mutedText, collapsed: isCollapsed) |
| 2281 | |
| 2282 | let title = "Comment on \(row.commentRangeLabel ?? "line")" |
| 2283 | drawSingleLineText( |
| 2284 | title, |
| 2285 | rect: CGRect( |
| 2286 | x: chevronRect.maxX + 10, |
| 2287 | y: cardRect.minY + 8, |
| 2288 | width: max(24, cardRect.width - chevronRect.maxX - 28), |
| 2289 | height: fileHeaderSubtextFont.lineHeight + 4 |
| 2290 | ), |
| 2291 | color: theme.mutedText, |
| 2292 | font: fileHeaderSubtextFont |
| 2293 | ) |
| 2294 | |
| 2295 | guard !isCollapsed else { |
| 2296 | return |
| 2297 | } |
| 2298 | |
| 2299 | let body = row.commentText?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" |
| 2300 | drawMultilineText( |
| 2301 | body.isEmpty ? "Comment" : body, |
| 2302 | rect: CGRect( |
| 2303 | x: cardRect.minX + 18, |
| 2304 | y: cardRect.minY + 42, |
| 2305 | width: max(24, cardRect.width - 36), |
| 2306 | height: max(20, cardRect.height - 56) |
| 2307 | ), |
| 2308 | color: theme.text, |
| 2309 | font: fileHeaderSubtextFont, |
| 2310 | maximumLineCount: 3 |
| 2311 | ) |
| 2312 | } |
| 2313 | |
| 2314 | private func fileHeaderPathLayout( |
| 2315 | for row: ReviewDiffNativeRow, |
| 2316 | cardRect: CGRect |
| 2317 | ) -> ReviewDiffFileHeaderPathLayout { |
| 2318 | let centerY = cardRect.midY |
| 2319 | let interactiveRects = fileHeaderInteractiveRects(for: row, cardRect: cardRect) |
| 2320 | |
| 2321 | let deletions = row.deletions ?? 0 |
| 2322 | let additions = row.additions ?? 0 |
| 2323 | let deleteWidth = textWidth("-\(deletions)", font: fileHeaderMetaFont) |
| 2324 | let addWidth = textWidth("+\(additions)", font: fileHeaderMetaFont) |
| 2325 | let countsGap = min(style.fileHeaderCountGap, 4) |
| 2326 | let countsWidth = deleteWidth + countsGap + addWidth |
| 2327 | let countsX = interactiveRects.checkbox.minX - 10 - countsWidth |
| 2328 | let pathX = interactiveRects.icon.maxX + 10 |
| 2329 | let pathWidth = max(CGFloat(24), countsX - pathX - 12) |
| 2330 | let displayPath: String |
| 2331 | if let previousPath = row.previousPath, previousPath != row.filePath, let filePath = row.filePath { |
| 2332 | displayPath = "\(previousPath) -> \(filePath)" |
| 2333 | } else { |
| 2334 | displayPath = row.filePath ?? "" |
| 2335 | } |
| 2336 | |
| 2337 | return ReviewDiffFileHeaderPathLayout( |
| 2338 | displayPath: displayPath, |
| 2339 | rect: CGRect(x: pathX, y: centerY - 10, width: pathWidth, height: 20) |
| 2340 | ) |
| 2341 | } |
| 2342 | |
| 2343 | private func fileHeaderInteractiveRects( |
| 2344 | for row: ReviewDiffNativeRow, |
| 2345 | cardRect: CGRect |
| 2346 | ) -> ReviewDiffFileHeaderInteractiveRects { |
| 2347 | let centerY = cardRect.midY |
| 2348 | let horizontalPadding = style.fileHeaderHorizontalPadding |
| 2349 | let chevronRect = CGRect(x: cardRect.minX + horizontalPadding, y: centerY - 10, width: 20, height: 20) |
| 2350 | let iconRect = CGRect(x: chevronRect.maxX + 8, y: centerY - 10, width: 20, height: 20) |
| 2351 | let checkboxRect = CGRect(x: cardRect.maxX - horizontalPadding - 20, y: centerY - 10, width: 20, height: 20) |
| 2352 | return ReviewDiffFileHeaderInteractiveRects( |
| 2353 | chevron: chevronRect, |
| 2354 | icon: iconRect, |
| 2355 | checkbox: checkboxRect |
| 2356 | ) |
| 2357 | } |
| 2358 | |
| 2359 | private func fileStatusColor(_ changeType: String?) -> UIColor { |
| 2360 | switch changeType { |
| 2361 | case "new": |
| 2362 | return theme.addText |
| 2363 | case "deleted": |
| 2364 | return theme.deleteText |
| 2365 | case "renamed", "rename-pure", "rename-changed": |
| 2366 | return theme.hunkText |
| 2367 | default: |
| 2368 | return theme.hunkText |
| 2369 | } |
| 2370 | } |
| 2371 | |
| 2372 | private func drawFileIcon(rect: CGRect, changeType: String?) { |
| 2373 | let color = fileStatusColor(changeType) |
| 2374 | let outerPath = UIBezierPath(roundedRect: rect, cornerRadius: 6) |
| 2375 | color.setStroke() |
| 2376 | outerPath.lineWidth = 2 |
| 2377 | outerPath.stroke() |
| 2378 | |
| 2379 | if isRenameChange(changeType) { |
| 2380 | drawRenameChevronIcon(rect: rect.insetBy(dx: 4.5, dy: 5), color: color) |
| 2381 | return |
| 2382 | } |
| 2383 | |
| 2384 | let dotRect = CGRect(x: rect.midX - 3, y: rect.midY - 3, width: 6, height: 6) |
| 2385 | color.setFill() |
| 2386 | UIBezierPath(ovalIn: dotRect).fill() |
| 2387 | } |
| 2388 | |
| 2389 | private func isRenameChange(_ changeType: String?) -> Bool { |
| 2390 | changeType == "renamed" || changeType == "rename-pure" || changeType == "rename-changed" |
| 2391 | } |
| 2392 | |
| 2393 | private func drawDisclosureChevron(rect: CGRect, color: UIColor, collapsed: Bool) { |
| 2394 | guard let context = UIGraphicsGetCurrentContext() else { |
| 2395 | return |
| 2396 | } |
| 2397 | |
| 2398 | context.saveGState() |
| 2399 | context.setStrokeColor(color.cgColor) |
| 2400 | context.setLineWidth(2) |
| 2401 | context.setLineCap(.round) |
| 2402 | context.setLineJoin(.round) |
| 2403 | if collapsed { |
| 2404 | context.move(to: CGPoint(x: rect.minX + rect.width * 0.40, y: rect.minY + rect.height * 0.28)) |
| 2405 | context.addLine(to: CGPoint(x: rect.minX + rect.width * 0.60, y: rect.midY)) |
| 2406 | context.addLine(to: CGPoint(x: rect.minX + rect.width * 0.40, y: rect.maxY - rect.height * 0.28)) |
| 2407 | } else { |
| 2408 | context.move(to: CGPoint(x: rect.minX + rect.width * 0.28, y: rect.minY + rect.height * 0.42)) |
| 2409 | context.addLine(to: CGPoint(x: rect.midX, y: rect.minY + rect.height * 0.62)) |
| 2410 | context.addLine(to: CGPoint(x: rect.maxX - rect.width * 0.28, y: rect.minY + rect.height * 0.42)) |
| 2411 | } |
| 2412 | context.strokePath() |
| 2413 | context.restoreGState() |
| 2414 | } |
| 2415 | |
| 2416 | private func drawRenameChevronIcon(rect: CGRect, color: UIColor) { |
| 2417 | guard let context = UIGraphicsGetCurrentContext() else { |
| 2418 | return |
| 2419 | } |
| 2420 | |
| 2421 | context.saveGState() |
| 2422 | context.setStrokeColor(color.cgColor) |
| 2423 | context.setLineWidth(1.8) |
| 2424 | context.setLineCap(.round) |
| 2425 | context.setLineJoin(.round) |
| 2426 | |
| 2427 | let chevronWidth = min(rect.width * 0.28, 3.6) |
| 2428 | let chevronHeight = min(rect.height, 8) |
| 2429 | let gap = min(rect.width * 0.18, 2.4) |
| 2430 | let totalWidth = chevronWidth * 2 + gap |
| 2431 | let startX = rect.midX - totalWidth / 2 |
| 2432 | let topY = rect.midY - chevronHeight / 2 |
| 2433 | let bottomY = rect.midY + chevronHeight / 2 |
| 2434 | |
| 2435 | for x in [startX, startX + chevronWidth + gap] { |
| 2436 | context.move(to: CGPoint(x: x, y: topY)) |
| 2437 | context.addLine(to: CGPoint(x: x + chevronWidth, y: rect.midY)) |
| 2438 | context.addLine(to: CGPoint(x: x, y: bottomY)) |
| 2439 | } |
| 2440 | |
| 2441 | context.strokePath() |
| 2442 | context.restoreGState() |
| 2443 | } |
| 2444 | |
| 2445 | private func drawViewedCheckbox(rect: CGRect, checked: Bool) { |
| 2446 | let path = UIBezierPath(roundedRect: rect, cornerRadius: 6) |
| 2447 | if checked { |
| 2448 | theme.hunkText.setFill() |
| 2449 | path.fill() |
| 2450 | } |
| 2451 | (checked ? theme.hunkText : theme.mutedText).setStroke() |
| 2452 | path.lineWidth = 1.8 |
| 2453 | path.stroke() |
| 2454 | |
| 2455 | guard checked, let context = UIGraphicsGetCurrentContext() else { |
| 2456 | return |
| 2457 | } |
| 2458 | |
| 2459 | context.saveGState() |
| 2460 | context.setStrokeColor(theme.background.cgColor) |
| 2461 | context.setLineWidth(2) |
| 2462 | context.setLineCap(.round) |
| 2463 | context.setLineJoin(.round) |
| 2464 | context.move(to: CGPoint(x: rect.minX + rect.width * 0.28, y: rect.midY)) |
| 2465 | context.addLine(to: CGPoint(x: rect.minX + rect.width * 0.44, y: rect.maxY - rect.height * 0.30)) |
| 2466 | context.addLine(to: CGPoint(x: rect.maxX - rect.width * 0.25, y: rect.minY + rect.height * 0.30)) |
| 2467 | context.strokePath() |
| 2468 | context.restoreGState() |
| 2469 | } |
| 2470 | |
| 2471 | private func drawNoticeIcon(rect: CGRect, color: UIColor) { |
| 2472 | guard let context = UIGraphicsGetCurrentContext() else { |
| 2473 | return |
| 2474 | } |
| 2475 | |
| 2476 | context.saveGState() |
| 2477 | context.setStrokeColor(color.cgColor) |
| 2478 | context.setLineWidth(1.7) |
| 2479 | context.setLineCap(.round) |
| 2480 | context.setLineJoin(.round) |
| 2481 | |
| 2482 | context.strokeEllipse(in: rect.insetBy(dx: 1, dy: 1)) |
| 2483 | context.move(to: CGPoint(x: rect.midX, y: rect.minY + rect.height * 0.30)) |
| 2484 | context.addLine(to: CGPoint(x: rect.midX, y: rect.minY + rect.height * 0.58)) |
| 2485 | context.strokePath() |
| 2486 | color.setFill() |
| 2487 | context.fillEllipse(in: CGRect(x: rect.midX - 1, y: rect.maxY - rect.height * 0.30, width: 2, height: 2)) |
| 2488 | context.restoreGState() |
| 2489 | } |
| 2490 | |
| 2491 | private func drawCenteredText(_ text: String, rect: CGRect, color: UIColor, font: UIFont) { |
| 2492 | let paragraphStyle = NSMutableParagraphStyle() |
| 2493 | paragraphStyle.alignment = .center |
| 2494 | let attributes: [NSAttributedString.Key: Any] = [ |
| 2495 | .font: font, |
| 2496 | .foregroundColor: color, |
| 2497 | .paragraphStyle: paragraphStyle, |
| 2498 | ] |
| 2499 | (text as NSString).draw(in: rect, withAttributes: attributes) |
| 2500 | } |
| 2501 | |
| 2502 | private func drawHunkRow(_ row: ReviewDiffNativeRow, rect: CGRect, context: CGContext) { |
| 2503 | let fileId = resolvedFileId(for: row) |
| 2504 | let horizontalOffset = horizontalOffset(for: fileId) |
| 2505 | let contentWidth = contentWidth(for: fileId) |
| 2506 | theme.hunkBackground.setFill() |
| 2507 | context.fill(rect) |
| 2508 | |
| 2509 | context.saveGState() |
| 2510 | context.clip(to: CGRect(x: stickyWidth, y: rect.minY, width: max(0, viewportWidth - stickyWidth), height: style.rowHeight)) |
| 2511 | drawText( |
| 2512 | row.text ?? "", |
| 2513 | rect: CGRect( |
| 2514 | x: codeStartX - horizontalOffset, |
| 2515 | y: centeredTextY(in: rect, font: hunkFont), |
| 2516 | width: contentWidth, |
| 2517 | height: hunkFont.lineHeight |
| 2518 | ), |
| 2519 | color: theme.hunkText, |
| 2520 | font: hunkFont |
| 2521 | ) |
| 2522 | context.restoreGState() |
| 2523 | } |
| 2524 | |
| 2525 | private func drawCodeRow(_ row: ReviewDiffNativeRow, rect: CGRect, context: CGContext) { |
| 2526 | let fileId = resolvedFileId(for: row) |
| 2527 | let horizontalOffset = horizontalOffset(for: fileId) |
| 2528 | let contentWidth = contentWidth(for: fileId) |
| 2529 | let change = row.change ?? "context" |
| 2530 | let layout = codeLayoutsByRowId[row.id] |
| 2531 | let firstLineHeight = layout?.firstLineHeight |
| 2532 | ?? (row.content != nil && codeLayoutWidth != nil ? codeFont.lineHeight : 0) |
| 2533 | let firstLineRect = CGRect( |
| 2534 | x: rect.minX, y: rect.minY, width: rect.width, |
| 2535 | height: max(style.rowHeight, firstLineHeight) |
| 2536 | ) |
| 2537 | rowBackground(for: change).setFill() |
| 2538 | context.fill(rect) |
| 2539 | |
| 2540 | if change == "add" { |
| 2541 | theme.addBar.setFill() |
| 2542 | context.fill(CGRect(x: 0, y: rect.minY, width: style.changeBarWidth, height: rect.height)) |
| 2543 | } else if change == "delete" { |
| 2544 | drawDeleteStripes( |
| 2545 | rect: CGRect(x: 0, y: rect.minY, width: style.changeBarWidth, height: rect.height), |
| 2546 | context: context |
| 2547 | ) |
| 2548 | } |
| 2549 | |
| 2550 | drawSelectionOverlay(row, rect: rect, context: context) |
| 2551 | |
| 2552 | let lineNumber = row.newLineNumber ?? row.oldLineNumber |
| 2553 | if let lineNumber { |
| 2554 | drawRightAlignedText( |
| 2555 | "\(lineNumber)", |
| 2556 | rect: CGRect( |
| 2557 | x: style.changeBarWidth, |
| 2558 | y: centeredTextY(in: firstLineRect, font: lineNumberFont), |
| 2559 | width: style.gutterWidth - style.codePadding, |
| 2560 | height: lineNumberFont.lineHeight |
| 2561 | ), |
| 2562 | color: lineNumberColor(for: change), |
| 2563 | font: lineNumberFont |
| 2564 | ) |
| 2565 | } |
| 2566 | |
| 2567 | context.saveGState() |
| 2568 | context.clip(to: CGRect(x: stickyWidth, y: rect.minY, width: max(0, viewportWidth - stickyWidth), height: rect.height)) |
| 2569 | let codeTextRect = CGRect( |
| 2570 | x: codeStartX - horizontalOffset, |
| 2571 | y: centeredTextY(in: firstLineRect, font: codeFont), |
| 2572 | width: contentWidth, |
| 2573 | height: codeFont.lineHeight |
| 2574 | ) |
| 2575 | if let layout, layout.usesNativeLayout { |
| 2576 | let text = tokensByRowId[row.id].map { |
| 2577 | tokenAttributedString(rowId: row.id, tokens: $0, fallbackColor: theme.text, font: codeFont) |
| 2578 | } ?? NSAttributedString(string: row.content ?? "", attributes: [.foregroundColor: theme.text]) |
| 2579 | let highlights = (change == "add" || change == "delete") ? (row.wordDiffRanges ?? []) : [] |
| 2580 | layout.decorate( |
| 2581 | text: text, |
| 2582 | highlights: highlights.filter { $0.start >= 0 && $0.end > $0.start }.map { |
| 2583 | NSRange(location: $0.start, length: $0.end - $0.start) |
| 2584 | }, |
| 2585 | color: (change == "add" ? theme.addBar : theme.deleteBar).withAlphaComponent(0.28), |
| 2586 | note: row.noteStart.map { |
| 2587 | ReviewDiffCodeNote( |
| 2588 | range: NSRange(location: $0, length: max(0, text.length - $0)), |
| 2589 | color: theme.warningText, |
| 2590 | background: theme.warningBackground |
| 2591 | ) |
| 2592 | }, |
| 2593 | version: codeDecorationVersion |
| 2594 | ) |
| 2595 | layout.draw( |
| 2596 | at: CGPoint(x: codeStartX - horizontalOffset, y: rect.minY + max(0, (firstLineRect.height - layout.firstLineHeight) / 2)), |
| 2597 | clip: context.boundingBoxOfClipPath |
| 2598 | ) |
| 2599 | context.restoreGState() |
| 2600 | return |
| 2601 | } |
| 2602 | let lineStarts = ReviewDiffCodeLineStarts( |
| 2603 | length: (row.content ?? "").utf16.count, columns: codeWrapColumns |
| 2604 | ) |
| 2605 | drawWordDiffRanges( |
| 2606 | row, |
| 2607 | lineStarts: lineStarts, |
| 2608 | firstLineRect: firstLineRect, |
| 2609 | context: context, |
| 2610 | horizontalOffset: horizontalOffset |
| 2611 | ) |
| 2612 | if let tokens = tokensByRowId[row.id], !tokens.isEmpty { |
| 2613 | let attributedText = tokenAttributedString( |
| 2614 | rowId: row.id, |
| 2615 | tokens: tokens, |
| 2616 | fallbackColor: theme.text, |
| 2617 | font: codeFont |
| 2618 | ) |
| 2619 | drawCodeLines(length: attributedText.length, lineStarts: lineStarts, firstLineRect: codeTextRect) { range, lineRect in |
| 2620 | let segment = range.length == attributedText.length |
| 2621 | ? attributedText |
| 2622 | : attributedText.attributedSubstring(from: range) |
| 2623 | segment.draw(in: lineRect) |
| 2624 | } |
| 2625 | } else { |
| 2626 | let content = (row.content ?? "") as NSString |
| 2627 | drawCodeLines(length: content.length, lineStarts: lineStarts, firstLineRect: codeTextRect) { range, lineRect in |
| 2628 | let segment = range.length == content.length ? content as String : content.substring(with: range) |
| 2629 | drawText(segment, rect: lineRect, color: theme.text, font: codeFont) |
| 2630 | } |
| 2631 | } |
| 2632 | context.restoreGState() |
| 2633 | } |
| 2634 | |
| 2635 | private func drawCodeLines( |
| 2636 | length: Int, |
| 2637 | lineStarts: ReviewDiffCodeLineStarts, |
| 2638 | firstLineRect: CGRect, |
| 2639 | draw: (NSRange, CGRect) -> Void |
| 2640 | ) { |
| 2641 | var lineRect = firstLineRect |
| 2642 | let clip = UIGraphicsGetCurrentContext()?.boundingBoxOfClipPath ?? bounds |
| 2643 | let first = max(0, Int(floor((clip.minY - firstLineRect.minY) / codeWrapLineHeight))) |
| 2644 | let last = min(lineStarts.count, Int(ceil((clip.maxY - firstLineRect.minY) / codeWrapLineHeight))) |
| 2645 | guard first < last else { return } |
| 2646 | lineRect.origin.y += CGFloat(first) * codeWrapLineHeight |
| 2647 | for line in first..<last { |
| 2648 | let lineStart = lineStarts[line] |
| 2649 | let lineEnd = line + 1 < lineStarts.count ? lineStarts[line + 1] : length |
| 2650 | draw(NSRange(location: lineStart, length: lineEnd - lineStart), lineRect) |
| 2651 | lineRect.origin.y += codeWrapLineHeight |
| 2652 | } |
| 2653 | } |
| 2654 | |
| 2655 | private func drawSelectionOverlay( |
| 2656 | _ row: ReviewDiffNativeRow, |
| 2657 | rect: CGRect, |
| 2658 | context: CGContext |
| 2659 | ) { |
| 2660 | guard selectedRowIds.contains(row.id) else { |
| 2661 | return |
| 2662 | } |
| 2663 | |
| 2664 | theme.hunkText.withAlphaComponent(0.95).setFill() |
| 2665 | context.fill(CGRect(x: 0, y: rect.minY, width: style.changeBarWidth, height: rect.height)) |
| 2666 | } |
| 2667 | |
| 2668 | private func drawWordDiffRanges( |
| 2669 | _ row: ReviewDiffNativeRow, |
| 2670 | lineStarts: ReviewDiffCodeLineStarts, |
| 2671 | firstLineRect: CGRect, |
| 2672 | context: CGContext, |
| 2673 | horizontalOffset: CGFloat |
| 2674 | ) { |
| 2675 | guard let ranges = row.wordDiffRanges, !ranges.isEmpty else { |
| 2676 | return |
| 2677 | } |
| 2678 | |
| 2679 | let change = row.change ?? "context" |
| 2680 | guard change == "add" || change == "delete" else { |
| 2681 | return |
| 2682 | } |
| 2683 | |
| 2684 | let fillColor: UIColor |
| 2685 | if change == "add" { |
| 2686 | fillColor = theme.addBar.withAlphaComponent(0.28) |
| 2687 | } else { |
| 2688 | fillColor = theme.deleteBar.withAlphaComponent(0.28) |
| 2689 | } |
| 2690 | let highlightHeight = max(4, min(firstLineRect.height - 4, codeFont.lineHeight)) |
| 2691 | let highlightY = firstLineRect.midY - highlightHeight / 2 |
| 2692 | |
| 2693 | fillColor.setFill() |
| 2694 | for range in ranges { |
| 2695 | guard range.end > range.start else { |
| 2696 | continue |
| 2697 | } |
| 2698 | |
| 2699 | for (line, lineStart) in lineStarts.enumerated() { |
| 2700 | let lineEnd = line + 1 < lineStarts.count ? lineStarts[line + 1] : Int.max |
| 2701 | let start = max(range.start, lineStart) |
| 2702 | let end = min(range.end, lineEnd) |
| 2703 | guard end > start else { |
| 2704 | continue |
| 2705 | } |
| 2706 | let highlightRect = CGRect( |
| 2707 | x: codeStartX - horizontalOffset + CGFloat(start - lineStart) * codeCharacterWidth, |
| 2708 | y: highlightY + CGFloat(line) * codeWrapLineHeight, |
| 2709 | width: max(2, CGFloat(end - start) * codeCharacterWidth), |
| 2710 | height: highlightHeight |
| 2711 | ) |
| 2712 | UIBezierPath(roundedRect: highlightRect, cornerRadius: 3).fill() |
| 2713 | } |
| 2714 | } |
| 2715 | } |
| 2716 | |
| 2717 | private func rowBackground(for change: String) -> UIColor { |
| 2718 | if change == "add" { |
| 2719 | return theme.addBackground |
| 2720 | } |
| 2721 | if change == "delete" { |
| 2722 | return theme.deleteBackground |
| 2723 | } |
| 2724 | return theme.background |
| 2725 | } |
| 2726 | |
| 2727 | private func lineNumberColor(for change: String) -> UIColor { |
| 2728 | if change == "add" { |
| 2729 | return theme.addText |
| 2730 | } |
| 2731 | if change == "delete" { |
| 2732 | return theme.deleteText |
| 2733 | } |
| 2734 | return theme.mutedText |
| 2735 | } |
| 2736 | |
| 2737 | private func drawDeleteStripes(rect: CGRect, context: CGContext) { |
| 2738 | theme.deleteBar.setFill() |
| 2739 | var y = rect.minY |
| 2740 | while y < rect.maxY { |
| 2741 | context.fill(CGRect(x: rect.minX, y: y, width: rect.width, height: 1)) |
| 2742 | y += 2 |
| 2743 | } |
| 2744 | } |
| 2745 | |
| 2746 | private func drawText(_ text: String, rect: CGRect, color: UIColor, font: UIFont) { |
| 2747 | let attributes: [NSAttributedString.Key: Any] = [ |
| 2748 | .font: font, |
| 2749 | .foregroundColor: color, |
| 2750 | .ligature: 0, |
| 2751 | ] |
| 2752 | (text as NSString).draw(in: rect, withAttributes: attributes) |
| 2753 | } |
| 2754 | |
| 2755 | private func drawMultilineText( |
| 2756 | _ text: String, |
| 2757 | rect: CGRect, |
| 2758 | color: UIColor, |
| 2759 | font: UIFont, |
| 2760 | maximumLineCount: Int |
| 2761 | ) { |
| 2762 | let paragraphStyle = NSMutableParagraphStyle() |
| 2763 | paragraphStyle.lineBreakMode = .byTruncatingTail |
| 2764 | paragraphStyle.lineSpacing = 2 |
| 2765 | |
| 2766 | let attributes: [NSAttributedString.Key: Any] = [ |
| 2767 | .font: font, |
| 2768 | .foregroundColor: color, |
| 2769 | .paragraphStyle: paragraphStyle, |
| 2770 | .ligature: 0, |
| 2771 | ] |
| 2772 | let maxHeight = CGFloat(maximumLineCount) * (font.lineHeight + paragraphStyle.lineSpacing) |
| 2773 | (text as NSString).draw( |
| 2774 | in: CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: min(rect.height, maxHeight)), |
| 2775 | withAttributes: attributes |
| 2776 | ) |
| 2777 | } |
| 2778 | |
| 2779 | private func centeredTextY(in rect: CGRect, font: UIFont) -> CGFloat { |
| 2780 | rect.midY - font.lineHeight / 2 |
| 2781 | } |
| 2782 | |
| 2783 | private func drawSingleLineText( |
| 2784 | _ text: String, |
| 2785 | rect: CGRect, |
| 2786 | color: UIColor, |
| 2787 | font: UIFont, |
| 2788 | horizontalOffset: CGFloat = 0 |
| 2789 | ) { |
| 2790 | guard let context = UIGraphicsGetCurrentContext() else { |
| 2791 | return |
| 2792 | } |
| 2793 | |
| 2794 | let attributes: [NSAttributedString.Key: Any] = [ |
| 2795 | .font: font, |
| 2796 | .foregroundColor: color, |
| 2797 | .ligature: 0, |
| 2798 | ] |
| 2799 | context.saveGState() |
| 2800 | context.clip(to: rect) |
| 2801 | let textY = rect.midY - font.lineHeight / 2 |
| 2802 | (text as NSString).draw( |
| 2803 | at: CGPoint(x: rect.minX - horizontalOffset, y: textY), |
| 2804 | withAttributes: attributes |
| 2805 | ) |
| 2806 | context.restoreGState() |
| 2807 | } |
| 2808 | |
| 2809 | private func drawFileHeaderPathScrollFade( |
| 2810 | _ row: ReviewDiffNativeRow, |
| 2811 | pathRect: CGRect, |
| 2812 | horizontalOffset: CGFloat, |
| 2813 | context: CGContext |
| 2814 | ) { |
| 2815 | let maxOffset = maxHeaderPathOffset(for: row) |
| 2816 | guard maxOffset > 0, pathRect.width > 0 else { |
| 2817 | return |
| 2818 | } |
| 2819 | |
| 2820 | let fadeWidth = min(CGFloat(28), pathRect.width / 3) |
| 2821 | if horizontalOffset > 0.5 { |
| 2822 | drawHorizontalFade( |
| 2823 | rect: CGRect(x: pathRect.minX, y: pathRect.minY, width: fadeWidth, height: pathRect.height), |
| 2824 | color: theme.headerBackground, |
| 2825 | fadesToRight: false, |
| 2826 | context: context |
| 2827 | ) |
| 2828 | } |
| 2829 | |
| 2830 | if horizontalOffset < maxOffset - 0.5 { |
| 2831 | drawHorizontalFade( |
| 2832 | rect: CGRect(x: pathRect.maxX - fadeWidth, y: pathRect.minY, width: fadeWidth, height: pathRect.height), |
| 2833 | color: theme.headerBackground, |
| 2834 | fadesToRight: true, |
| 2835 | context: context |
| 2836 | ) |
| 2837 | } |
| 2838 | } |
| 2839 | |
| 2840 | private func drawHorizontalFade( |
| 2841 | rect: CGRect, |
| 2842 | color: UIColor, |
| 2843 | fadesToRight: Bool, |
| 2844 | context: CGContext |
| 2845 | ) { |
| 2846 | guard rect.width > 0, |
| 2847 | let gradient = CGGradient( |
| 2848 | colorsSpace: CGColorSpaceCreateDeviceRGB(), |
| 2849 | colors: [ |
| 2850 | color.withAlphaComponent(fadesToRight ? 0 : 1).cgColor, |
| 2851 | color.withAlphaComponent(fadesToRight ? 1 : 0).cgColor, |
| 2852 | ] as CFArray, |
| 2853 | locations: [0, 1] |
| 2854 | ) else { |
| 2855 | return |
| 2856 | } |
| 2857 | |
| 2858 | context.saveGState() |
| 2859 | context.clip(to: rect) |
| 2860 | context.drawLinearGradient( |
| 2861 | gradient, |
| 2862 | start: CGPoint(x: rect.minX, y: rect.midY), |
| 2863 | end: CGPoint(x: rect.maxX, y: rect.midY), |
| 2864 | options: [] |
| 2865 | ) |
| 2866 | context.restoreGState() |
| 2867 | } |
| 2868 | |
| 2869 | private func textWidth(_ text: String, font: UIFont) -> CGFloat { |
| 2870 | let attributes: [NSAttributedString.Key: Any] = [.font: font, .ligature: 0] |
| 2871 | return ceil((text as NSString).size(withAttributes: attributes).width) |
| 2872 | } |
| 2873 | |
| 2874 | private func monospaceCharacterWidth(font: UIFont) -> CGFloat { |
| 2875 | let sampleLength = 64 |
| 2876 | let sample = String(repeating: "M", count: sampleLength) |
| 2877 | let attributes: [NSAttributedString.Key: Any] = [.font: font, .ligature: 0] |
| 2878 | return (sample as NSString).size(withAttributes: attributes).width / CGFloat(sampleLength) |
| 2879 | } |
| 2880 | |
| 2881 | private func tokenAttributedString( |
| 2882 | rowId: String, |
| 2883 | tokens: [ReviewDiffNativeToken], |
| 2884 | fallbackColor: UIColor, |
| 2885 | font: UIFont |
| 2886 | ) -> NSAttributedString { |
| 2887 | if let cached = tokenAttributedStringsByRowId[rowId] { |
| 2888 | return cached |
| 2889 | } |
| 2890 | |
| 2891 | let attributedString = NSMutableAttributedString(string: "") |
| 2892 | for token in tokens where !token.content.isEmpty { |
| 2893 | attributedString.append( |
| 2894 | NSAttributedString( |
| 2895 | string: token.content, |
| 2896 | attributes: [ |
| 2897 | .font: font, |
| 2898 | .foregroundColor: tokenColor(for: token.color, fallbackColor: fallbackColor), |
| 2899 | .ligature: 0, |
| 2900 | ] |
| 2901 | ) |
| 2902 | ) |
| 2903 | } |
| 2904 | |
| 2905 | tokenAttributedStringsByRowId[rowId] = attributedString |
| 2906 | return attributedString |
| 2907 | } |
| 2908 | |
| 2909 | private func tokenColor(for hex: String?, fallbackColor: UIColor) -> UIColor { |
| 2910 | guard let hex, !hex.isEmpty else { |
| 2911 | return fallbackColor |
| 2912 | } |
| 2913 | |
| 2914 | if let color = tokenColorsByHex[hex] { |
| 2915 | return color |
| 2916 | } |
| 2917 | |
| 2918 | guard let color = UIColor(reviewDiffHex: hex) else { |
| 2919 | return fallbackColor |
| 2920 | } |
| 2921 | |
| 2922 | tokenColorsByHex[hex] = color |
| 2923 | return color |
| 2924 | } |
| 2925 | |
| 2926 | private func drawRightAlignedText(_ text: String, rect: CGRect, color: UIColor, font: UIFont) { |
| 2927 | let paragraphStyle = NSMutableParagraphStyle() |
| 2928 | paragraphStyle.alignment = .right |
| 2929 | let attributes: [NSAttributedString.Key: Any] = [ |
| 2930 | .font: font, |
| 2931 | .foregroundColor: color, |
| 2932 | .paragraphStyle: paragraphStyle, |
| 2933 | ] |
| 2934 | (text as NSString).draw(in: rect, withAttributes: attributes) |
| 2935 | } |
| 2936 | } |
| 2937 | |
| 2938 | private extension UIColor { |
| 2939 | convenience init?(reviewDiffHex hex: String?) { |
| 2940 | guard var value = hex?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else { |
| 2941 | return nil |
| 2942 | } |
| 2943 | |
| 2944 | if value.hasPrefix("#") { |
| 2945 | value.removeFirst() |
| 2946 | } |
| 2947 | |
| 2948 | guard value.count == 6 || value.count == 8 else { |
| 2949 | return nil |
| 2950 | } |
| 2951 | |
| 2952 | var rawValue: UInt64 = 0 |
| 2953 | guard Scanner(string: value).scanHexInt64(&rawValue) else { |
| 2954 | return nil |
| 2955 | } |
| 2956 | |
| 2957 | let red: CGFloat |
| 2958 | let green: CGFloat |
| 2959 | let blue: CGFloat |
| 2960 | let alpha: CGFloat |
| 2961 | |
| 2962 | if value.count == 8 { |
| 2963 | red = CGFloat((rawValue >> 24) & 0xff) / 255 |
| 2964 | green = CGFloat((rawValue >> 16) & 0xff) / 255 |
| 2965 | blue = CGFloat((rawValue >> 8) & 0xff) / 255 |
| 2966 | alpha = CGFloat(rawValue & 0xff) / 255 |
| 2967 | } else { |
| 2968 | red = CGFloat((rawValue >> 16) & 0xff) / 255 |
| 2969 | green = CGFloat((rawValue >> 8) & 0xff) / 255 |
| 2970 | blue = CGFloat(rawValue & 0xff) / 255 |
| 2971 | alpha = 1 |
| 2972 | } |
| 2973 | |
| 2974 | self.init(red: red, green: green, blue: blue, alpha: alpha) |
| 2975 | } |
| 2976 | } |