sailfork / t3code-github / apps/ mobile/ modules/ t3-review-diff/ ios/ T3ReviewDiffView.swift

import ExpoModulesCore
import UIKit

private struct ReviewDiffNativeRow: Decodable, Sendable {
  let kind: String
  let id: String
  let fileId: String?
  let filePath: String?
  let previousPath: String?
  let changeType: String?
  let additions: Int?
  let deletions: Int?
  let text: String?
  let content: String?
  let change: String?
  let oldLineNumber: Int?
  let newLineNumber: Int?
  let wordDiffRanges: [ReviewDiffNativeWordDiffRange]?
  let commentText: String?
  let commentRangeLabel: String?
  let commentSectionTitle: String?
}

private struct ReviewDiffNativeWordDiffRange: Decodable, Sendable {
  let start: Int
  let end: Int
}

private struct ReviewDiffNativeToken: Decodable, Sendable {
  let content: String
  let color: String?
  let fontStyle: Int?
}

private struct ReviewDiffNativeTokenPatch: Decodable, Sendable {
  let resetKey: String?
  let chunkIndex: Int?
  let tokensByRowId: [String: [ReviewDiffNativeToken]]?
}

private struct ReviewDiffNativeThemePayload: Decodable {
  let background: String?
  let text: String?
  let mutedText: String?
  let headerBackground: String?
  let border: String?
  let hunkBackground: String?
  let hunkText: String?
  let addBackground: String?
  let deleteBackground: String?
  let addBar: String?
  let deleteBar: String?
  let addText: String?
  let deleteText: String?
}

private struct ReviewDiffNativeTheme {
  let background: UIColor
  let text: UIColor
  let mutedText: UIColor
  let headerBackground: UIColor
  let border: UIColor
  let hunkBackground: UIColor
  let hunkText: UIColor
  let addBackground: UIColor
  let deleteBackground: UIColor
  let addBar: UIColor
  let deleteBar: UIColor
  let addText: UIColor
  let deleteText: UIColor

  static func resolve(_ scheme: String) -> ReviewDiffNativeTheme {
    resolve(scheme, payload: nil)
  }

  static func resolve(
    _ scheme: String,
    payload: ReviewDiffNativeThemePayload?
  ) -> ReviewDiffNativeTheme {
    let fallback = fallback(scheme)
    guard let payload else {
      return fallback
    }

    return ReviewDiffNativeTheme(
      background: UIColor(reviewDiffHex: payload.background) ?? fallback.background,
      text: UIColor(reviewDiffHex: payload.text) ?? fallback.text,
      mutedText: UIColor(reviewDiffHex: payload.mutedText) ?? fallback.mutedText,
      headerBackground: UIColor(reviewDiffHex: payload.headerBackground) ?? fallback.headerBackground,
      border: UIColor(reviewDiffHex: payload.border) ?? fallback.border,
      hunkBackground: UIColor(reviewDiffHex: payload.hunkBackground) ?? fallback.hunkBackground,
      hunkText: UIColor(reviewDiffHex: payload.hunkText) ?? fallback.hunkText,
      addBackground: UIColor(reviewDiffHex: payload.addBackground) ?? fallback.addBackground,
      deleteBackground: UIColor(reviewDiffHex: payload.deleteBackground) ?? fallback.deleteBackground,
      addBar: UIColor(reviewDiffHex: payload.addBar) ?? fallback.addBar,
      deleteBar: UIColor(reviewDiffHex: payload.deleteBar) ?? fallback.deleteBar,
      addText: UIColor(reviewDiffHex: payload.addText) ?? fallback.addText,
      deleteText: UIColor(reviewDiffHex: payload.deleteText) ?? fallback.deleteText
    )
  }

  private static func fallback(_ scheme: String) -> ReviewDiffNativeTheme {
    if scheme == "dark" {
      return ReviewDiffNativeTheme(
        background: UIColor(red: 0.07, green: 0.07, blue: 0.07, alpha: 1),
        text: UIColor(red: 0.90, green: 0.90, blue: 0.90, alpha: 1),
        mutedText: UIColor(red: 0.52, green: 0.52, blue: 0.52, alpha: 1),
        headerBackground: UIColor(red: 0.10, green: 0.10, blue: 0.10, alpha: 1),
        border: UIColor(red: 0.16, green: 0.16, blue: 0.16, alpha: 1),
        hunkBackground: UIColor(red: 0.03, green: 0.14, blue: 0.18, alpha: 1),
        hunkText: UIColor(red: 0.41, green: 0.82, blue: 1.00, alpha: 1),
        addBackground: UIColor(red: 0.02, green: 0.16, blue: 0.10, alpha: 1),
        deleteBackground: UIColor(red: 0.18, green: 0.05, blue: 0.08, alpha: 1),
        addBar: UIColor(red: 0.02, green: 0.82, blue: 0.54, alpha: 1),
        deleteBar: UIColor(red: 1.00, green: 0.36, blue: 0.50, alpha: 1),
        addText: UIColor(red: 0.10, green: 0.84, blue: 0.56, alpha: 1),
        deleteText: UIColor(red: 1.00, green: 0.38, blue: 0.52, alpha: 1)
      )
    }

    return ReviewDiffNativeTheme(
      background: UIColor.white,
      text: UIColor(red: 0.16, green: 0.16, blue: 0.16, alpha: 1),
      mutedText: UIColor(red: 0.47, green: 0.47, blue: 0.47, alpha: 1),
      headerBackground: UIColor.white,
      border: UIColor(red: 0.88, green: 0.88, blue: 0.90, alpha: 1),
      hunkBackground: UIColor(red: 0.83, green: 0.92, blue: 0.98, alpha: 1),
      hunkText: UIColor(red: 0.00, green: 0.45, blue: 0.74, alpha: 1),
      addBackground: UIColor(red: 0.85, green: 0.94, blue: 0.92, alpha: 1),
      deleteBackground: UIColor(red: 0.96, green: 0.85, blue: 0.90, alpha: 1),
      addBar: UIColor(red: 0.02, green: 0.80, blue: 0.52, alpha: 1),
      deleteBar: UIColor(red: 1.00, green: 0.34, blue: 0.48, alpha: 1),
      addText: UIColor(red: 0.00, green: 0.56, blue: 0.34, alpha: 1),
      deleteText: UIColor(red: 0.90, green: 0.10, blue: 0.24, alpha: 1)
    )
  }
}

private struct ReviewDiffNativeStylePayload: Decodable {
  let wordWrap: Bool?
  let rowHeight: Double?
  let contentWidth: Double?
  let changeBarWidth: Double?
  let gutterWidth: Double?
  let codePadding: Double?
  let textVerticalInset: Double?
  let fileHeaderHeight: Double?
  let fileHeaderHorizontalMargin: Double?
  let fileHeaderVerticalMargin: Double?
  let fileHeaderCornerRadius: Double?
  let fileHeaderHorizontalPadding: Double?
  let fileHeaderPathRightPadding: Double?
  let fileHeaderCountColumnWidth: Double?
  let fileHeaderCountGap: Double?
  let codeFontSize: Double?
  let codeFontWeight: String?
  let lineNumberFontSize: Double?
  let lineNumberFontWeight: String?
  let hunkFontSize: Double?
  let hunkFontWeight: String?
  let fileHeaderFontSize: Double?
  let fileHeaderFontWeight: String?
  let fileHeaderMetaFontSize: Double?
  let fileHeaderMetaFontWeight: String?
  let fileHeaderSubtextFontSize: Double?
  let fileHeaderSubtextFontWeight: String?
  let fileHeaderStatusFontSize: Double?
  let fileHeaderStatusFontWeight: String?
  let emptyStateFontSize: Double?
  let emptyStateFontWeight: String?
}

private struct ReviewDiffNativeStyle: Equatable {
  let wordWrap: Bool
  let rowHeight: CGFloat
  let contentWidth: CGFloat
  let changeBarWidth: CGFloat
  let gutterWidth: CGFloat
  let codePadding: CGFloat
  let textVerticalInset: CGFloat
  let fileHeaderHeight: CGFloat
  let fileHeaderHorizontalMargin: CGFloat
  let fileHeaderVerticalMargin: CGFloat
  let fileHeaderCornerRadius: CGFloat
  let fileHeaderHorizontalPadding: CGFloat
  let fileHeaderPathRightPadding: CGFloat
  let fileHeaderCountColumnWidth: CGFloat
  let fileHeaderCountGap: CGFloat
  let codeFontSize: CGFloat
  let codeFontWeight: UIFont.Weight
  let lineNumberFontSize: CGFloat
  let lineNumberFontWeight: UIFont.Weight
  let hunkFontSize: CGFloat
  let hunkFontWeight: UIFont.Weight
  let fileHeaderFontSize: CGFloat
  let fileHeaderFontWeight: UIFont.Weight
  let fileHeaderMetaFontSize: CGFloat
  let fileHeaderMetaFontWeight: UIFont.Weight
  let fileHeaderSubtextFontSize: CGFloat
  let fileHeaderSubtextFontWeight: UIFont.Weight
  let fileHeaderStatusFontSize: CGFloat
  let fileHeaderStatusFontWeight: UIFont.Weight
  let emptyStateFontSize: CGFloat
  let emptyStateFontWeight: UIFont.Weight

  static func resolve(_ payload: ReviewDiffNativeStylePayload?) -> ReviewDiffNativeStyle {
    ReviewDiffNativeStyle(
      wordWrap: payload?.wordWrap ?? false,
      rowHeight: metric(payload?.rowHeight, fallback: 24),
      contentWidth: metric(payload?.contentWidth, fallback: 2800),
      changeBarWidth: nonNegativeMetric(payload?.changeBarWidth, fallback: 4),
      gutterWidth: metric(payload?.gutterWidth, fallback: 50),
      codePadding: metric(payload?.codePadding, fallback: 8),
      textVerticalInset: metric(payload?.textVerticalInset, fallback: 3),
      fileHeaderHeight: metric(payload?.fileHeaderHeight, fallback: 54),
      fileHeaderHorizontalMargin: metric(payload?.fileHeaderHorizontalMargin, fallback: 8),
      fileHeaderVerticalMargin: metric(payload?.fileHeaderVerticalMargin, fallback: 6),
      fileHeaderCornerRadius: metric(payload?.fileHeaderCornerRadius, fallback: 10),
      fileHeaderHorizontalPadding: metric(payload?.fileHeaderHorizontalPadding, fallback: 12),
      fileHeaderPathRightPadding: metric(payload?.fileHeaderPathRightPadding, fallback: 128),
      fileHeaderCountColumnWidth: metric(payload?.fileHeaderCountColumnWidth, fallback: 42),
      fileHeaderCountGap: metric(payload?.fileHeaderCountGap, fallback: 6),
      codeFontSize: metric(payload?.codeFontSize, fallback: 12),
      codeFontWeight: fontWeight(payload?.codeFontWeight, fallback: .bold),
      lineNumberFontSize: metric(payload?.lineNumberFontSize, fallback: 11),
      lineNumberFontWeight: fontWeight(payload?.lineNumberFontWeight, fallback: .bold),
      hunkFontSize: metric(payload?.hunkFontSize, fallback: 12),
      hunkFontWeight: fontWeight(payload?.hunkFontWeight, fallback: .bold),
      fileHeaderFontSize: metric(payload?.fileHeaderFontSize, fallback: 13),
      fileHeaderFontWeight: fontWeight(payload?.fileHeaderFontWeight, fallback: .bold),
      fileHeaderMetaFontSize: metric(payload?.fileHeaderMetaFontSize, fallback: 12),
      fileHeaderMetaFontWeight: fontWeight(payload?.fileHeaderMetaFontWeight, fallback: .bold),
      fileHeaderSubtextFontSize: metric(payload?.fileHeaderSubtextFontSize, fallback: 11),
      fileHeaderSubtextFontWeight: fontWeight(payload?.fileHeaderSubtextFontWeight, fallback: .medium),
      fileHeaderStatusFontSize: metric(payload?.fileHeaderStatusFontSize, fallback: 10),
      fileHeaderStatusFontWeight: fontWeight(payload?.fileHeaderStatusFontWeight, fallback: .semibold),
      emptyStateFontSize: metric(payload?.emptyStateFontSize, fallback: 13),
      emptyStateFontWeight: fontWeight(payload?.emptyStateFontWeight, fallback: .semibold)
    )
  }

  private static func metric(_ value: Double?, fallback: CGFloat) -> CGFloat {
    guard let value, value.isFinite, value > 0 else {
      return fallback
    }
    return CGFloat(value)
  }

  private static func nonNegativeMetric(_ value: Double?, fallback: CGFloat) -> CGFloat {
    guard let value, value.isFinite, value >= 0 else {
      return fallback
    }
    return CGFloat(value)
  }

  private static func fontWeight(_ value: String?, fallback: UIFont.Weight) -> UIFont.Weight {
    switch value?.lowercased() {
    case "ultralight", "ultra-light":
      return .ultraLight
    case "thin":
      return .thin
    case "light":
      return .light
    case "regular":
      return .regular
    case "medium":
      return .medium
    case "semibold", "semi-bold":
      return .semibold
    case "bold":
      return .bold
    case "heavy":
      return .heavy
    case "black":
      return .black
    default:
      return fallback
    }
  }

  func applyingOverrides(rowHeight: CGFloat?, contentWidth: CGFloat?) -> ReviewDiffNativeStyle {
    ReviewDiffNativeStyle(
      wordWrap: wordWrap,
      rowHeight: rowHeight ?? self.rowHeight,
      contentWidth: contentWidth ?? self.contentWidth,
      changeBarWidth: changeBarWidth,
      gutterWidth: gutterWidth,
      codePadding: codePadding,
      textVerticalInset: textVerticalInset,
      fileHeaderHeight: fileHeaderHeight,
      fileHeaderHorizontalMargin: fileHeaderHorizontalMargin,
      fileHeaderVerticalMargin: fileHeaderVerticalMargin,
      fileHeaderCornerRadius: fileHeaderCornerRadius,
      fileHeaderHorizontalPadding: fileHeaderHorizontalPadding,
      fileHeaderPathRightPadding: fileHeaderPathRightPadding,
      fileHeaderCountColumnWidth: fileHeaderCountColumnWidth,
      fileHeaderCountGap: fileHeaderCountGap,
      codeFontSize: codeFontSize,
      codeFontWeight: codeFontWeight,
      lineNumberFontSize: lineNumberFontSize,
      lineNumberFontWeight: lineNumberFontWeight,
      hunkFontSize: hunkFontSize,
      hunkFontWeight: hunkFontWeight,
      fileHeaderFontSize: fileHeaderFontSize,
      fileHeaderFontWeight: fileHeaderFontWeight,
      fileHeaderMetaFontSize: fileHeaderMetaFontSize,
      fileHeaderMetaFontWeight: fileHeaderMetaFontWeight,
      fileHeaderSubtextFontSize: fileHeaderSubtextFontSize,
      fileHeaderSubtextFontWeight: fileHeaderSubtextFontWeight,
      fileHeaderStatusFontSize: fileHeaderStatusFontSize,
      fileHeaderStatusFontWeight: fileHeaderStatusFontWeight,
      emptyStateFontSize: emptyStateFontSize,
      emptyStateFontWeight: emptyStateFontWeight
    )
  }
}

public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
  private let payloadDecodeQueue = DispatchQueue(
    label: "com.t3tools.review-diff.payload-decode",
    qos: .userInitiated
  )
  private let scrollView = UIScrollView()
  private let contentView = ReviewDiffContentView()
  private var rows: [ReviewDiffNativeRow] = []
  private var appearanceScheme: String = "light"
  private var themePayload: ReviewDiffNativeThemePayload?
  private var stylePayload: ReviewDiffNativeStylePayload?
  private var rowHeightOverride: CGFloat?
  private var contentWidthOverride: CGFloat?
  private var lastMetricsDebugKey = ""
  private var lastVisibleRangeDebugKey = ""
  private var tokensResetKey = ""
  private var contentResetKey = ""
  private var initialRowIndex: Int?
  private var initialFileId: String?
  private var hasAppliedInitialRowIndex = false
  private var lastVisibleFileId: String?
  private var pendingScrollFileId: String?
  private var pendingScrollAnimated = false
  private var isProgrammaticScrollActive = false
  private var rowsDecodeGeneration = 0
  private var rowsDecodeCancellation: ReviewDiffRowPreparation?
  private var tokensDecodeGeneration = 0
  private var tokensDecodeCancellation: ReviewDiffRowPreparation?

  let onDebug = EventDispatcher()
  let onVisibleFileChange = EventDispatcher()
  let onToggleFile = EventDispatcher()
  let onToggleViewedFile = EventDispatcher()
  let onPressLine = EventDispatcher()
  let onToggleComment = EventDispatcher()
  let onPullToRefresh = EventDispatcher()

  private let pullRefreshControl = UIRefreshControl()

  public required init(appContext: AppContext? = nil) {
    super.init(appContext: appContext)

    clipsToBounds = true
    backgroundColor = contentView.theme.background
    scrollView.contentInsetAdjustmentBehavior = .never
    scrollView.delegate = self
    scrollView.clipsToBounds = true
    scrollView.alwaysBounceVertical = true
    scrollView.alwaysBounceHorizontal = false
    scrollView.showsVerticalScrollIndicator = true
    scrollView.showsHorizontalScrollIndicator = false
    scrollView.backgroundColor = contentView.theme.background
    pullRefreshControl.addTarget(self, action: #selector(handlePullToRefresh), for: .valueChanged)
    addSubview(scrollView)

    contentView.backgroundColor = contentView.theme.background
    contentView.onToggleFile = { [weak self] fileId in
      self?.onToggleFile(["fileId": fileId])
    }
    contentView.onToggleViewedFile = { [weak self] fileId in
      self?.onToggleViewedFile(["fileId": fileId])
    }
    contentView.onPressLine = { [weak self] payload in
      self?.onPressLine(payload)
    }
    contentView.onToggleComment = { [weak self] commentId in
      self?.onToggleComment(["commentId": commentId])
    }
    contentView.onDrawMetrics = { [weak self] metrics in
      self?.emitDebug("draw-metrics", metrics)
    }
    scrollView.addSubview(contentView)
  }

  deinit {
    rowsDecodeCancellation?.cancel()
    tokensDecodeCancellation?.cancel()
  }

  public override func layoutSubviews() {
    super.layoutSubviews()
    let anchor = contentView.viewportWidth != bounds.width ? contentView.viewportRowAnchor() : nil
    scrollView.frame = bounds
    updateContentMetrics(rowAnchor: anchor)
  }

  public func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView.isTracking || scrollView.isDragging || scrollView.isDecelerating {
      contentView.isVerticalScrollActive = true
    }
    updateViewportFrame()
  }

  public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    // A direct gesture takes ownership from any interrupted programmatic jump.
    // Resume visible-file events immediately so the inspector follows the finger.
    isProgrammaticScrollActive = false
    contentView.isVerticalScrollActive = true
  }

  public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    guard !decelerate else {
      return
    }

    finishVerticalScroll()
  }

  public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    finishVerticalScroll()
  }

  public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
    finishVerticalScroll()
  }

  func setRowsJson(_ rowsJson: String) {
    contentView.cancelRowPreparation()
    rowsDecodeCancellation?.cancel()
    let cancellation = ReviewDiffRowPreparation()
    rowsDecodeCancellation = cancellation
    rowsDecodeGeneration += 1
    let generation = rowsDecodeGeneration

    payloadDecodeQueue.async { [weak self] in
      // Check weak liveness without retaining the view or reading its UIKit state.
      guard !cancellation.isCancelled, self != nil else { return }
      guard let data = rowsJson.data(using: .utf8) else {
        return
      }

      do {
        let decodedRows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
        DispatchQueue.main.async { [weak self] in
          guard let self, generation == self.rowsDecodeGeneration else {
            return
          }
          self.contentView.prepareRows(decodedRows, on: self.payloadDecodeQueue, isCurrent: { [weak self] in
            generation == self?.rowsDecodeGeneration
          }, completion: { [weak self] in
            guard let self, generation == self.rowsDecodeGeneration else { return }
            self.rows = decodedRows
            self.contentView.rows = decodedRows
            self.hasAppliedInitialRowIndex = false
            self.lastVisibleFileId = nil
            self.emitDebug("rows-decoded", [
              "rows": decodedRows.count,
              "firstKind": decodedRows.first?.kind ?? "none",
            ])
            self.updateContentMetrics()
            self.applyPendingScrollIfNeeded()
          })
        }
      } catch {
        let message = error.localizedDescription
        DispatchQueue.main.async { [weak self] in
          guard let self, generation == self.rowsDecodeGeneration else {
            return
          }
          self.rows = []
          self.contentView.rows = []
          self.hasAppliedInitialRowIndex = false
          self.lastVisibleFileId = nil
          self.pendingScrollFileId = nil
          self.updateContentMetrics()
          self.emitDebug("rows-decode-failed", ["error": message])
        }
      }
    }
  }

  func setTokensJson(_ tokensJson: String) {
    tokensDecodeCancellation?.cancel()
    let cancellation = ReviewDiffRowPreparation()
    tokensDecodeCancellation = cancellation
    tokensDecodeGeneration += 1
    let generation = tokensDecodeGeneration

    payloadDecodeQueue.async { [weak self] in
      // Entered decoding may finish; only skip full payloads already obsolete in the queue.
      guard !cancellation.isCancelled, self != nil else { return }
      guard let data = tokensJson.data(using: .utf8) else {
        return
      }

      do {
        let decodedTokens = try JSONDecoder().decode(
          [String: [ReviewDiffNativeToken]].self,
          from: data
        )
        DispatchQueue.main.async { [weak self] in
          guard let self, generation == self.tokensDecodeGeneration else {
            return
          }
          self.contentView.tokensByRowId = decodedTokens
        }
      } catch {
        let message = error.localizedDescription
        DispatchQueue.main.async { [weak self] in
          guard let self, generation == self.tokensDecodeGeneration else {
            return
          }
          self.contentView.tokensByRowId = [:]
          self.emitDebug("tokens-decode-failed", ["error": message])
        }
      }
    }
  }

  func setTokensPatchJson(_ tokensPatchJson: String, completion: @escaping (Bool) -> Void) {
    let contentResetKey = self.contentResetKey

    payloadDecodeQueue.async { [weak self] in
      guard let data = tokensPatchJson.data(using: .utf8) else {
        DispatchQueue.main.async { completion(false) }
        return
      }

      do {
        let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)
        DispatchQueue.main.async { [weak self] in
          guard let self else {
            completion(false)
            return
          }
          guard contentResetKey == self.contentResetKey else {
            completion(false)
            return
          }
          // A highlighter request from the previous file can finish after the view has
          // already reset. Never let that stale patch roll the native token state back.
          if let resetKey = patch.resetKey, resetKey != self.tokensResetKey {
            completion(false)
            return
          }

          let tokensByRowId = patch.tokensByRowId ?? [:]
          if tokensByRowId.isEmpty {
            completion(true)
            return
          }

          self.contentView.mergeTokensByRowId(tokensByRowId)
          completion(true)
          if let chunkIndex = patch.chunkIndex {
            self.emitDebug("tokens-patch-decoded", [
              "resetKey": patch.resetKey ?? "",
              "chunkIndex": chunkIndex,
              "rows": tokensByRowId.count,
              "tokens": tokensByRowId.values.reduce(0) { $0 + $1.count },
              "totalRows": self.contentView.tokensByRowId.count,
            ])
          }
        }
      } catch {
        let message = error.localizedDescription
        DispatchQueue.main.async { [weak self] in
          self?.emitDebug("tokens-patch-decode-failed", ["error": message])
          completion(false)
        }
      }
    }
  }

  func setTokensResetKey(_ tokensResetKey: String) {
    guard tokensResetKey != self.tokensResetKey else {
      return
    }

    self.tokensResetKey = tokensResetKey
    contentView.tokensByRowId = [:]
    emitDebug("tokens-reset", [
      "resetKey": tokensResetKey,
    ])
  }

  // Code surfaces fill the screen so UIKit can sample content below the glass bar.
  // Keep the same visible row when header or safe-area reservations change.
  func setContentInsetTop(_ inset: CGFloat) {
    scrollView.automaticallyAdjustsScrollIndicatorInsets = false
    let inset = max(0, inset)
    let delta = inset - scrollView.contentInset.top
    guard delta != 0 else { return }
    scrollView.contentInset.top = inset
    contentView.topContentInset = inset
    scrollView.verticalScrollIndicatorInsets.top = inset
    scrollView.contentOffset.y -= delta
    updateViewportFrame()
  }

  func setContentInsetBottom(_ inset: CGFloat) {
    scrollView.contentInset.bottom = max(0, inset)
    scrollView.verticalScrollIndicatorInsets.bottom = max(0, inset)
  }

  func setContentResetKey(_ contentResetKey: String) {
    guard contentResetKey != self.contentResetKey else {
      return
    }

    self.contentResetKey = contentResetKey
    lastVisibleRangeDebugKey = ""
    contentView.cancelRowPreparation()
    rowsDecodeCancellation?.cancel()
    rowsDecodeCancellation = nil
    rowsDecodeGeneration += 1
    tokensDecodeGeneration += 1
    tokensDecodeCancellation?.cancel()
    contentView.tokensByRowId = [:]
    rows = []
    contentView.rows = []
    hasAppliedInitialRowIndex = false
    pendingScrollFileId = initialFileId
    isProgrammaticScrollActive = false
    scrollView.setContentOffset(CGPoint(x: 0, y: -scrollView.contentInset.top), animated: false)
    updateContentMetrics()
    updateViewportFrame()
    lastVisibleFileId = nil
    applyInitialRowIndexIfNeeded()
  }

  func setCollapsedFileIdsJson(_ collapsedFileIdsJson: String) {
    let nextCollapsedFileIds = decodeFileIdSet(collapsedFileIdsJson)
    let changedFileIds = contentView.collapsedFileIds.symmetricDifference(nextCollapsedFileIds)
    let scrollAnchor: ReviewDiffScrollAnchor?
    if changedFileIds.count == 1, let changedFileId = changedFileIds.first {
      scrollAnchor = contentView.scrollAnchor(forFileId: changedFileId)
    } else {
      scrollAnchor = nil
    }

    contentView.collapsedFileIds = nextCollapsedFileIds
    updateContentMetrics()

    if let scrollAnchor,
       let headerOffset = contentView.fileHeaderOffset(forFileId: scrollAnchor.fileId) {
      let targetOffset = headerOffset - scrollAnchor.screenY
      let minOffset = -scrollView.contentInset.top
      let maxOffset = max(
        scrollView.contentSize.height - scrollView.bounds.height + scrollView.contentInset.bottom,
        minOffset
      )
      let clampedOffset = min(max(targetOffset, minOffset), maxOffset)
      scrollView.setContentOffset(CGPoint(x: 0, y: clampedOffset), animated: false)
      updateViewportFrame()
    }
  }

  func setViewedFileIdsJson(_ viewedFileIdsJson: String) {
    contentView.viewedFileIds = decodeFileIdSet(viewedFileIdsJson)
  }

  func setSelectedRowIdsJson(_ selectedRowIdsJson: String) {
    contentView.selectedRowIds = decodeFileIdSet(selectedRowIdsJson)
  }

  func setCollapsedCommentIdsJson(_ collapsedCommentIdsJson: String) {
    contentView.collapsedCommentIds = decodeFileIdSet(collapsedCommentIdsJson)
    updateContentMetrics()
  }

  private func decodeFileIdSet(_ json: String) -> Set<String> {
    guard let data = json.data(using: .utf8) else {
      return []
    }

    do {
      return Set(try JSONDecoder().decode([String].self, from: data))
    } catch {
      emitDebug("file-id-set-decode-failed", [
        "error": error.localizedDescription,
      ])
      return []
    }
  }

  func setAppearanceScheme(_ appearanceScheme: String) {
    self.appearanceScheme = appearanceScheme
    applyTheme()
  }

  func setThemeJson(_ themeJson: String) {
    guard let data = themeJson.data(using: .utf8) else {
      themePayload = nil
      applyTheme()
      return
    }

    do {
      themePayload = try JSONDecoder().decode(ReviewDiffNativeThemePayload.self, from: data)
    } catch {
      themePayload = nil
      emitDebug("theme-decode-failed", [
        "error": error.localizedDescription,
      ])
    }

    applyTheme()
  }

  private func updateContentMetrics(rowAnchor: ReviewDiffViewportRowAnchor? = nil) {
    let anchor = rowAnchor ?? (contentView.viewportWidth != bounds.width
      ? contentView.viewportRowAnchor() : nil)
    let style = contentView.style
    contentView.viewportWidth = bounds.width
    let height = max(bounds.height, contentView.contentHeight)
    let width = bounds.width
    scrollView.contentSize = CGSize(width: bounds.width, height: height)
    if let anchor, let offset = contentView.offset(for: anchor) {
      let minOffset = -scrollView.contentInset.top
      let maxOffset = max(height - scrollView.bounds.height + scrollView.contentInset.bottom, minOffset)
      let target = min(max(offset - scrollView.contentInset.top, minOffset), maxOffset)
      if abs(target - scrollView.contentOffset.y) > 0.01 {
        scrollView.setContentOffset(CGPoint(x: 0, y: target), animated: false)
        if isProgrammaticScrollActive { finishVerticalScroll() }
      }
    }
    contentView.frame = CGRect(
      x: 0,
      y: scrollView.contentOffset.y,
      width: max(width, 1),
      height: max(bounds.height, 1)
    )
    contentView.verticalOffset = scrollView.contentOffset.y
    contentView.invalidateVisibleViewport()
    contentView.setNeedsDisplay()
    applyInitialRowIndexIfNeeded()
    applyPendingScrollIfNeeded()
    emitVisibleFileIfNeeded()
    emitVisibleRange(reason: "layout")

    let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(contentView.contentHeight))"
    if debugKey != lastMetricsDebugKey {
      lastMetricsDebugKey = debugKey
      emitDebug("metrics", [
        "rows": rows.count,
        "boundsWidth": Double(bounds.width),
        "boundsHeight": Double(bounds.height),
        "contentHeight": Double(contentView.contentHeight),
        "contentWidth": Double(style.contentWidth),
        "fileHeaderHeight": Double(style.fileHeaderHeight),
        "rowHeight": Double(style.rowHeight),
      ])
    }
  }

  private func emitDebug(_ message: String, _ details: [String: Any]) {
    var payload = details
    payload["message"] = message
    onDebug(payload)
  }

  private func finishVerticalScroll() {
    isProgrammaticScrollActive = false
    contentView.isVerticalScrollActive = false
    updateViewportFrame()
    emitVisibleRange(reason: "scroll-end")
  }

  private func emitVisibleFileIfNeeded() {
    // Keep the explicit destination selected while UIKit animates through the files
    // between the old and new offsets. Emitting every intermediate header forces a
    // React render per crossing and makes the navigator visibly flash.
    guard !isProgrammaticScrollActive else {
      return
    }

    // The top of the combined diff is the explicit "All files" destination.
    // Treat it as a first-class selection instead of immediately resolving the
    // first file header and undoing the navigator's optimistic selection.
    let visibleTop = scrollView.contentOffset.y + scrollView.contentInset.top
    if visibleTop <= 0.5 {
      guard lastVisibleFileId != nil else {
        return
      }
      lastVisibleFileId = nil
      onVisibleFileChange(["fileId": NSNull()])
      return
    }

    guard let fileId = contentView.visibleFileId(atVerticalOffset: visibleTop),
          fileId != lastVisibleFileId else {
      return
    }

    lastVisibleFileId = fileId
    onVisibleFileChange(["fileId": fileId])
  }

  private func emitVisibleRange(reason: String) {
    guard bounds.width > 0, bounds.height > 0,
          let range = contentView.currentVisibleRowRange() else {
      return
    }

    let debugKey = "\(range.firstRowIndex):\(range.lastRowIndex):\(Int(scrollView.bounds.height))"
    guard debugKey != lastVisibleRangeDebugKey else {
      return
    }

    lastVisibleRangeDebugKey = debugKey
    emitDebug("visible-range", [
      "reason": reason,
      "firstRowIndex": range.firstRowIndex,
      "lastRowIndex": range.lastRowIndex,
      "totalRows": rows.count,
    ])
  }

  private func applyTheme() {
    contentView.theme = ReviewDiffNativeTheme.resolve(appearanceScheme, payload: themePayload)
    backgroundColor = contentView.theme.background
    scrollView.backgroundColor = contentView.theme.background
    contentView.backgroundColor = contentView.theme.background
    contentView.invalidateVisibleViewport()
  }

  func setStyleJson(_ styleJson: String) {
    guard let data = styleJson.data(using: .utf8) else {
      stylePayload = nil
      applyStyle()
      return
    }

    do {
      stylePayload = try JSONDecoder().decode(ReviewDiffNativeStylePayload.self, from: data)
    } catch {
      stylePayload = nil
      emitDebug("style-decode-failed", [
        "error": error.localizedDescription,
      ])
    }

    applyStyle()
  }

  func setRowHeight(_ rowHeight: CGFloat) {
    rowHeightOverride = rowHeight.isFinite && rowHeight > 0 ? rowHeight : nil
    applyStyle()
  }

  func setContentWidth(_ contentWidth: CGFloat) {
    contentWidthOverride = contentWidth.isFinite && contentWidth > 0 ? contentWidth : nil
    applyStyle()
  }

  func setInitialRowIndex(_ initialRowIndex: Double) {
    let nextIndex: Int? = initialRowIndex.isFinite && initialRowIndex >= 0
      ? Int(initialRowIndex.rounded(.down))
      : nil
    guard nextIndex != self.initialRowIndex else {
      return
    }

    self.initialRowIndex = nextIndex
    hasAppliedInitialRowIndex = false
    applyInitialRowIndexIfNeeded()
  }

  func scrollToFile(_ fileId: String, animated: Bool) {
    pendingScrollFileId = fileId
    pendingScrollAnimated = animated
    applyPendingScrollIfNeeded()
  }

  func setInitialFileId(_ fileId: String) {
    let nextFileId = fileId.isEmpty ? nil : fileId
    guard nextFileId != initialFileId else { return }
    initialFileId = nextFileId
    pendingScrollFileId = nextFileId
    pendingScrollAnimated = false
    // Apply after the prop batch and content metrics, before the first range event.
    setNeedsLayout()
  }

  func scrollToTop(animated: Bool) {
    pendingScrollFileId = nil
    pendingScrollAnimated = false
    setVerticalContentOffset(0, animated: animated)
  }

  func setScrollEnabled(_ enabled: Bool) {
    scrollView.isScrollEnabled = enabled
  }

  func setBounces(_ bounces: Bool) {
    scrollView.bounces = bounces
    scrollView.alwaysBounceVertical = bounces
  }

  func setRefreshEnabled(_ enabled: Bool) {
    if !enabled { pullRefreshControl.endRefreshing() }
    scrollView.refreshControl = enabled ? pullRefreshControl : nil
  }

  @objc private func handlePullToRefresh() {
    onPullToRefresh([:])
  }

  func setRefreshing(_ refreshing: Bool) {
    if refreshing {
      if !pullRefreshControl.isRefreshing {
        pullRefreshControl.beginRefreshing()
      }
    } else if pullRefreshControl.isRefreshing {
      pullRefreshControl.endRefreshing()
    }
  }

  private func applyStyle() {
    let anchor = contentView.viewportRowAnchor()
    contentView.style = ReviewDiffNativeStyle
      .resolve(stylePayload)
      .applyingOverrides(rowHeight: rowHeightOverride, contentWidth: contentWidthOverride)
    updateContentMetrics(rowAnchor: anchor)
  }

  private func updateViewportFrame() {
    contentView.frame = CGRect(
      x: 0,
      y: scrollView.contentOffset.y,
      width: max(bounds.width, 1),
      height: max(bounds.height, 1)
    )
    contentView.verticalOffset = scrollView.contentOffset.y
    contentView.invalidateVisibleViewport()
    emitVisibleFileIfNeeded()
  }

  private func applyPendingScrollIfNeeded() {
    guard let fileId = pendingScrollFileId,
          bounds.height > 0 else {
      return
    }

    guard let headerOffset = contentView.fileHeaderOffset(forFileId: fileId) else {
      if !rows.isEmpty {
        pendingScrollFileId = nil
      }
      return
    }

    let animated = pendingScrollAnimated
    pendingScrollFileId = nil
    pendingScrollAnimated = false
    setVerticalContentOffset(headerOffset, animated: animated)
  }

  private func setVerticalContentOffset(_ targetOffset: CGFloat, animated: Bool) {
    let topInset = scrollView.contentInset.top
    let maxOffset = max(
      scrollView.contentSize.height - scrollView.bounds.height + scrollView.contentInset.bottom,
      -topInset
    )
    let clampedOffset = min(max(targetOffset - topInset, -topInset), maxOffset)
    let shouldAnimate = animated && abs(scrollView.contentOffset.y - clampedOffset) > 0.5
    isProgrammaticScrollActive = shouldAnimate
    contentView.isVerticalScrollActive = shouldAnimate
    scrollView.setContentOffset(CGPoint(x: 0, y: clampedOffset), animated: shouldAnimate)
    if !shouldAnimate {
      finishVerticalScroll()
    }
  }

  private func applyInitialRowIndexIfNeeded() {
    guard !hasAppliedInitialRowIndex,
          let initialRowIndex,
          bounds.height > 0,
          let rowFrame = contentView.frameForRow(at: initialRowIndex) else {
      return
    }

    let visibleHeight = bounds.height - scrollView.contentInset.top - scrollView.contentInset.bottom
    let targetScreenY = max(0, (visibleHeight - rowFrame.height) * 0.3)
    hasAppliedInitialRowIndex = true
    setVerticalContentOffset(rowFrame.minY - targetScreenY, animated: false)
  }
}

private enum ReviewDiffHorizontalPanKind {
  case code
  case fileHeaderPath
}

private struct ReviewDiffFileHeaderPathLayout {
  let displayPath: String
  let rect: CGRect
}

private struct ReviewDiffFileHeaderInteractiveRects {
  let chevron: CGRect
  let icon: CGRect
  let checkbox: CGRect
}

private struct ReviewDiffStickyFileHeaderIndex {
  let position: Int
  let rowIndex: Int
}

private struct ReviewDiffStickyFileHeaderTarget {
  let rowIndex: Int
  let row: ReviewDiffNativeRow
  let rect: CGRect
}

private struct ReviewDiffViewportRowAnchor {
  let rowIndex: Int
  let intraRowOffset: CGFloat
}

private struct ReviewDiffScrollAnchor {
  let fileId: String
  let screenY: CGFloat
}

private final class ReviewDiffRowPreparation {
  private let lock = NSLock()
  private var cancelled = false

  func cancel() {
    lock.lock()
    cancelled = true
    lock.unlock()
  }

  var isCancelled: Bool {
    lock.lock()
    defer { lock.unlock() }
    return cancelled
  }
}

private struct ReviewDiffGeometryConfiguration: Equatable {
  let style: ReviewDiffNativeStyle
  let viewportWidth: CGFloat
  let collapsedFileIds: Set<String>
  let collapsedCommentIds: Set<String>

  func height(for row: ReviewDiffNativeRow) -> CGFloat {
    if row.kind == "file" { return style.fileHeaderHeight }
    if collapsedFileIds.contains(row.resolvedFileId) { return 0 }
    if row.kind == "notice" { return max(style.rowHeight * 2, 44) }
    if row.kind == "comment" { return collapsedCommentIds.contains(row.id) ? 44 : 124 }
    return style.rowHeight
  }
}

private struct ReviewDiffRowGeometryInput {
  let configuration: ReviewDiffGeometryConfiguration
  let font: UIFont
  let hunkFont: UIFont
  let characterWidth: CGFloat
  let layoutWidth: CGFloat?
  let cached: [String: ReviewDiffCodeLayout]
}

private struct ReviewDiffRowGeometry {
  let offsets: [CGFloat]
  let fileHeaderIndices: [Int]
  let contentWidths: [String: CGFloat]
  let nativeLayouts: [String: ReviewDiffCodeLayout]
  let height: CGFloat
  let characterWidth: CGFloat
  let wrapColumns: Int?
}

private extension ReviewDiffNativeRow {
  var resolvedFileId: String {
    if let fileId { return fileId }
    if let range = id.range(of: ":header") ?? id.range(of: ":hunk:") ?? id.range(of: ":line:") {
      return String(id[..<range.lowerBound])
    }
    return filePath ?? id
  }
}

private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
  var rows: [ReviewDiffNativeRow] = [] {
    didSet {
      stopHorizontalDeceleration()
      horizontalOffsetsByFileId.removeAll()
      headerPathOffsetsByFileId.removeAll()
      activePanFileId = nil
      activePanKind = nil
      codeDecorationVersion += 1
      tokenAttributedStringsByRowId.removeAll()
      if let geometry = preparedRowGeometry {
        preparedRowGeometry = nil
        applyRowGeometry(geometry)
      } else {
        cancelRowPreparation()
        rebuildRowLayout()
      }
      setNeedsDisplayForVisibleBounds()
    }
  }
  var tokensByRowId: [String: [ReviewDiffNativeToken]] = [:] {
    didSet {
      codeDecorationVersion += 1
      tokenAttributedStringsByRowId.removeAll()
      clampHorizontalOffsets()
      setNeedsDisplayForVisibleBounds()
    }
  }

  func mergeTokensByRowId(_ tokensPatch: [String: [ReviewDiffNativeToken]]) {
    // One mutation lets didSet invalidate decoration and display once per batch.
    tokensByRowId.merge(tokensPatch) { _, tokens in tokens }
  }

  var collapsedFileIds: Set<String> = [] {
    didSet {
      rebuildRowLayout()
      clampHorizontalOffsets()
      setNeedsDisplayForVisibleBounds()
    }
  }
  var viewedFileIds: Set<String> = [] {
    didSet {
      setNeedsDisplayForVisibleBounds()
    }
  }
  var selectedRowIds: Set<String> = [] {
    didSet {
      setNeedsDisplayForVisibleBounds()
    }
  }
  var collapsedCommentIds: Set<String> = [] {
    didSet {
      rebuildRowLayout()
      setNeedsDisplayForVisibleBounds()
    }
  }
  var style = ReviewDiffNativeStyle.resolve(nil) {
    didSet {
      codeDecorationVersion += 1
      tokenAttributedStringsByRowId.removeAll()
      rebuildRowLayout()
      clampHorizontalOffsets()
      setNeedsDisplayForVisibleBounds()
    }
  }
  var viewportWidth: CGFloat = 0 {
    didSet {
      if style.wordWrap, viewportWidth != oldValue {
        rebuildRowLayout()
      }
      clampHorizontalOffsets()
      setNeedsDisplayForVisibleBounds()
    }
  }
  var verticalOffset: CGFloat = 0
  var topContentInset: CGFloat = 0
  var theme = ReviewDiffNativeTheme.resolve("light") {
    didSet {
      tokenColorsByHex.removeAll()
      codeDecorationVersion += 1
      tokenAttributedStringsByRowId.removeAll()
      setNeedsDisplayForVisibleBounds()
    }
  }
  private(set) var contentHeight: CGFloat = 0

  private var rowOffsets: [CGFloat] = []
  private var fileHeaderRowIndices: [Int] = []
  private var contentWidthsByFileId: [String: CGFloat] = [:]
  private var tokenColorsByHex: [String: UIColor] = [:]
  private var tokenAttributedStringsByRowId: [String: NSAttributedString] = [:]
  private var codeCharacterWidth: CGFloat = 8
  private var codeWrapColumns: Int?
  private var codeLayoutsByRowId: [String: ReviewDiffCodeLayout] = [:]
  private var codeLayoutWidth: CGFloat?
  private var codeLayoutFont: UIFont?
  private var codeDecorationVersion = 0
  private var rowPreparation: ReviewDiffRowPreparation?
  private var preparedRowGeometry: ReviewDiffRowGeometry?

  private var geometryConfiguration: ReviewDiffGeometryConfiguration {
    ReviewDiffGeometryConfiguration(
      style: style, viewportWidth: viewportWidth,
      collapsedFileIds: collapsedFileIds, collapsedCommentIds: collapsedCommentIds
    )
  }
  private var panStartHorizontalOffset: CGFloat = 0
  private var activePanFileId: String?
  private var activePanKind: ReviewDiffHorizontalPanKind?
  private var horizontalOffsetsByFileId: [String: CGFloat] = [:]
  private var headerPathOffsetsByFileId: [String: CGFloat] = [:]
  private var decelerationDisplayLink: CADisplayLink?
  private var deceleratingFileId: String?
  private var horizontalVelocity: CGFloat = 0
  private var lastDecelerationTimestamp: CFTimeInterval = 0
  private var lastDrawMetricsTimestamp: CFTimeInterval = 0
  var isVerticalScrollActive = false
  var onToggleFile: ((String) -> Void)?
  var onToggleViewedFile: ((String) -> Void)?
  var onPressLine: (([String: Any]) -> Void)?
  var onToggleComment: ((String) -> Void)?
  var onDrawMetrics: (([String: Any]) -> Void)?

  private var stickyWidth: CGFloat {
    style.changeBarWidth + style.gutterWidth
  }

  private var codeStartX: CGFloat {
    stickyWidth + style.codePadding
  }

  /// Height before word wrap. Laid-out rows use height(at:), which includes wrapped lines.
  private func height(for row: ReviewDiffNativeRow) -> CGFloat {
    geometryConfiguration.height(for: row)
  }

  /// Laid-out height, including wrapped lines. Requires a layout built from the current rows.
  private func height(at index: Int) -> CGFloat {
    let nextOffset = index + 1 < rowOffsets.count ? rowOffsets[index + 1] : contentHeight
    return nextOffset - rowOffsets[index]
  }

  private var codeWrapLineHeight: CGFloat {
    ceil(codeFont.lineHeight)
  }

  private func codeLayoutWidthLimit(font: UIFont) -> CGFloat? {
    guard style.wordWrap else { return ReviewDiffCodeLayout.unboundedWidth }
    let width = viewportWidth - codeStartX - style.codePadding
    let characterWidth = monospaceCharacterWidth(font: font)
    return characterWidth > 0 && width >= characterWidth ? width : nil
  }

  func frameForRow(at index: Int) -> CGRect? {
    guard rows.indices.contains(index), rowOffsets.indices.contains(index) else {
      return nil
    }

    return CGRect(
      x: 0,
      y: rowOffsets[index],
      width: max(viewportWidth, 1),
      height: height(at: index)
    )
  }

  // Pixel offsets cannot identify the same code row after wrapping or font changes.
  func viewportRowAnchor() -> ReviewDiffViewportRowAnchor? {
    let top = max(0, verticalOffset + topContentInset)
    guard let index = rowIndex(at: top) else { return nil }
    return ReviewDiffViewportRowAnchor(rowIndex: index, intraRowOffset: top - rowOffsets[index])
  }

  func offset(for anchor: ReviewDiffViewportRowAnchor) -> CGFloat? {
    guard let frame = frameForRow(at: anchor.rowIndex), frame.height > 0 else { return nil }
    let intraRowOffset = anchor.intraRowOffset < frame.height
      ? anchor.intraRowOffset : max(0, frame.height - 1)
    return frame.minY + intraRowOffset
  }

  func cancelRowPreparation() {
    rowPreparation?.cancel()
    rowPreparation = nil
    preparedRowGeometry = nil
  }

  /// Prepare immutable geometry on the decode worker; publication only swaps its buffers.
  func prepareRows(
    _ rows: [ReviewDiffNativeRow],
    on queue: DispatchQueue,
    isCurrent: @escaping () -> Bool,
    completion: @escaping () -> Void
  ) {
    cancelRowPreparation()
    let preparation = ReviewDiffRowPreparation()
    rowPreparation = preparation
    let configuration = geometryConfiguration
    let font = codeFont
    let characterWidth = monospaceCharacterWidth(font: font)
    let width = codeLayoutWidthLimit(font: font)
    let hunkFont = self.hunkFont
    let cached = codeLayoutWidth == width && codeLayoutFont == font ? codeLayoutsByRowId : [:]
    let input = ReviewDiffRowGeometryInput(
      configuration: configuration, font: font, hunkFont: hunkFont,
      characterWidth: characterWidth, layoutWidth: width, cached: cached
    )
    queue.async { [weak self] in
      guard let geometry = Self.buildRowGeometry(
        rows, input: input, isCancelled: { preparation.isCancelled }
      ) else { return }
      DispatchQueue.main.async { [weak self] in
        guard let self, !preparation.isCancelled, isCurrent() else { return }
        if self.geometryConfiguration != configuration {
          self.prepareRows(rows, on: queue, isCurrent: isCurrent, completion: completion)
          return
        }
        self.rowPreparation = nil
        self.codeLayoutWidth = width
        self.codeLayoutFont = font
        self.preparedRowGeometry = geometry
        completion()
      }
    }
  }

  private func rebuildRowLayout() {
    let font = codeFont
    let characterWidth = monospaceCharacterWidth(font: font)
    let layoutWidth = codeLayoutWidthLimit(font: font)
    let cached = codeLayoutWidth == layoutWidth && codeLayoutFont == font ? codeLayoutsByRowId : [:]
    let input = ReviewDiffRowGeometryInput(
      configuration: geometryConfiguration, font: font, hunkFont: hunkFont,
      characterWidth: characterWidth, layoutWidth: layoutWidth, cached: cached
    )
    guard let geometry = Self.buildRowGeometry(rows, input: input) else { return }
    codeLayoutWidth = layoutWidth
    codeLayoutFont = font
    applyRowGeometry(geometry)
  }

  private static func buildRowGeometry(
    _ rows: [ReviewDiffNativeRow],
    input: ReviewDiffRowGeometryInput,
    isCancelled: () -> Bool = { false }
  ) -> ReviewDiffRowGeometry? {
    var nextOffsets: [CGFloat] = []
    var nextFileHeaderRowIndices: [Int] = []
    nextOffsets.reserveCapacity(rows.count)
    var maxWidthsByFileId: [String: CGFloat] = [:]
    var nextCodeLayouts: [String: ReviewDiffCodeLayout] = [:]
    var offset: CGFloat = 0
    let style = input.configuration.style
    let characterWidth = input.characterWidth
    let wrapColumns = style.wordWrap ? input.layoutWidth.map { Int($0 / characterWidth) } : nil

    for (index, row) in rows.enumerated() {
      // Bound obsolete work without locking once per row; never read UIView state here.
      if index.isMultiple(of: 256), isCancelled() { return nil }
      nextOffsets.append(offset)
      if row.kind == "file" {
        nextFileHeaderRowIndices.append(index)
      }
      var rowHeight = input.configuration.height(for: row)
      let fileId = row.resolvedFileId
      switch row.kind {
      case "line":
        let width = lineWidth(
          for: row, input: input, wrapColumns: wrapColumns,
          height: &rowHeight, layouts: &nextCodeLayouts
        )
        maxWidthsByFileId[fileId] = max(maxWidthsByFileId[fileId] ?? 0, width)
      case "hunk":
        // Hunk context can hold tabs and draws in its own font.
        let width = ceil(((row.text ?? "") as NSString).size(withAttributes: [.font: input.hunkFont, .ligature: 0]).width)
        maxWidthsByFileId[fileId] = max(maxWidthsByFileId[fileId] ?? 0, width)
      default:
        break
      }
      offset += rowHeight
    }
    guard !isCancelled() else { return nil }
    return ReviewDiffRowGeometry(
      offsets: nextOffsets, fileHeaderIndices: nextFileHeaderRowIndices,
      contentWidths: maxWidthsByFileId.mapValues { ceil($0) + style.codePadding * 2 },
      nativeLayouts: nextCodeLayouts, height: offset,
      characterWidth: characterWidth, wrapColumns: wrapColumns
    )
  }

  private static func lineWidth(
    for row: ReviewDiffNativeRow,
    input: ReviewDiffRowGeometryInput,
    wrapColumns: Int?,
    height: inout CGFloat,
    layouts: inout [String: ReviewDiffCodeLayout]
  ) -> CGFloat {
    let characterWidth = input.characterWidth
    let font = input.font
    var width = CGFloat(row.content?.utf16.count ?? 0) * characterWidth
    if let layoutWidth = input.layoutWidth, let content = row.content {
      if ReviewDiffCodeLayout.isPrintableASCII(content) {
        let length = content.utf8.count
        let starts = ReviewDiffCodeLineStarts(length: length, columns: wrapColumns)
        width = CGFloat(min(length, starts.columns)) * characterWidth
        if height > 0 {
          height = max(height, font.lineHeight) + CGFloat(starts.count - 1) * ceil(font.lineHeight)
        }
      } else {
        let layout: ReviewDiffCodeLayout
        if let previous = input.cached[row.id], previous.text == content {
          layout = previous
        } else {
          layout = ReviewDiffCodeLayout(
            text: content, font: font, width: layoutWidth, characterWidth: characterWidth
          )
        }
        layouts[row.id] = layout
        width = layout.usedWidth
        if height > 0 {
          height = max(height, layout.firstLineHeight) + layout.extraHeight
        }
      }
    }
    return width
  }

  private func applyRowGeometry(_ geometry: ReviewDiffRowGeometry) {
    codeCharacterWidth = geometry.characterWidth
    codeWrapColumns = geometry.wrapColumns
    codeLayoutsByRowId = geometry.nativeLayouts
    contentWidthsByFileId = geometry.contentWidths
    rowOffsets = geometry.offsets
    fileHeaderRowIndices = geometry.fileHeaderIndices
    contentHeight = geometry.height
  }

  private var codeFont: UIFont {
    UIFont.monospacedSystemFont(ofSize: style.codeFontSize, weight: style.codeFontWeight)
  }

  private var lineNumberFont: UIFont {
    UIFont.monospacedSystemFont(ofSize: style.lineNumberFontSize, weight: style.lineNumberFontWeight)
  }

  private var hunkFont: UIFont {
    UIFont.monospacedSystemFont(ofSize: style.hunkFontSize, weight: style.hunkFontWeight)
  }

  private var fileHeaderFont: UIFont {
    UIFont.systemFont(ofSize: style.fileHeaderFontSize, weight: style.fileHeaderFontWeight)
  }

  private var fileHeaderMetaFont: UIFont {
    UIFont.systemFont(ofSize: style.fileHeaderMetaFontSize, weight: style.fileHeaderMetaFontWeight)
  }

  private var fileHeaderSubtextFont: UIFont {
    UIFont.systemFont(ofSize: style.fileHeaderSubtextFontSize, weight: style.fileHeaderSubtextFontWeight)
  }

  private var fileHeaderStatusFont: UIFont {
    UIFont.systemFont(ofSize: style.fileHeaderStatusFontSize, weight: style.fileHeaderStatusFontWeight)
  }

  private var emptyStateFont: UIFont {
    UIFont.systemFont(ofSize: style.emptyStateFontSize, weight: style.emptyStateFontWeight)
  }

  private lazy var horizontalPanGesture: UIPanGestureRecognizer = {
    let gesture = UIPanGestureRecognizer(target: self, action: #selector(handleHorizontalPan(_:)))
    gesture.delegate = self
    gesture.cancelsTouchesInView = false
    return gesture
  }()

  private lazy var tapGesture: UITapGestureRecognizer = {
    let gesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
    gesture.delegate = self
    gesture.cancelsTouchesInView = false
    return gesture
  }()

  private lazy var longPressGesture: UILongPressGestureRecognizer = {
    let gesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
    gesture.delegate = self
    gesture.cancelsTouchesInView = false
    gesture.minimumPressDuration = 0.28
    return gesture
  }()

  override init(frame: CGRect) {
    super.init(frame: frame)
    isOpaque = true
    contentMode = .redraw
    addGestureRecognizer(horizontalPanGesture)
    addGestureRecognizer(tapGesture)
    addGestureRecognizer(longPressGesture)
    tapGesture.require(toFail: longPressGesture)
  }

  func invalidateVisibleViewport() {
    setNeedsDisplayForVisibleBounds()
  }

  private func setNeedsDisplayForVisibleBounds() {
    setNeedsDisplay()
  }

  required init?(coder: NSCoder) {
    super.init(coder: coder)
    isOpaque = true
    contentMode = .redraw
    addGestureRecognizer(horizontalPanGesture)
    addGestureRecognizer(tapGesture)
    addGestureRecognizer(longPressGesture)
    tapGesture.require(toFail: longPressGesture)
  }

  override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    guard gestureRecognizer === horizontalPanGesture else {
      return true
    }

    let velocity = horizontalPanGesture.velocity(in: self)
    guard abs(velocity.x) > abs(velocity.y) * 1.25 else {
      return false
    }

    guard let panTarget = horizontalPanTarget(at: horizontalPanGesture.location(in: self)) else {
      return false
    }

    let currentOffset = horizontalOffset(for: panTarget.fileId, kind: panTarget.kind)
    if velocity.x > 0 && currentOffset <= 0.5 {
      return false
    }

    return maxHorizontalOffset(for: panTarget) > 0
  }

  @objc private func handleTap(_ gesture: UITapGestureRecognizer) {
    guard gesture.state == .ended else {
      return
    }

    let point = gesture.location(in: self)
    if let stickyHeader = stickyFileHeaderTarget(), stickyHeader.rect.contains(point) {
      handleFileHeaderTap(row: stickyHeader.row, rect: stickyHeader.rect, point: point)
      return
    }

    guard let rowIndex = rowIndex(at: verticalOffset + point.y),
          rows.indices.contains(rowIndex) else {
      return
    }

    let row = rows[rowIndex]
    if row.kind == "comment" {
      onToggleComment?(row.id)
      return
    }

    if row.kind == "line" {
      onPressLine?(linePressPayload(for: row, gesture: "tap"))
      return
    }

    guard row.kind == "file" else {
      return
    }

    let rowY = rowOffsets[rowIndex] - verticalOffset
    let rect = CGRect(x: 0, y: rowY, width: max(bounds.width, viewportWidth), height: height(for: row))
    handleFileHeaderTap(row: row, rect: rect, point: point)
  }

  @objc private func handleLongPress(_ gesture: UILongPressGestureRecognizer) {
    guard gesture.state == .began else {
      return
    }

    let point = gesture.location(in: self)
    if let stickyHeader = stickyFileHeaderTarget(), stickyHeader.rect.contains(point) {
      return
    }

    guard let rowIndex = rowIndex(at: verticalOffset + point.y),
          rows.indices.contains(rowIndex) else {
      return
    }

    let row = rows[rowIndex]
    guard row.kind == "line" else {
      return
    }

    onPressLine?(linePressPayload(for: row, gesture: "longPress"))
  }

  private func linePressPayload(for row: ReviewDiffNativeRow, gesture: String) -> [String: Any] {
    var payload: [String: Any] = [
      "rowId": row.id,
      "fileId": resolvedFileId(for: row),
      "gesture": gesture
    ]

    if let oldLineNumber = row.oldLineNumber {
      payload["oldLineNumber"] = oldLineNumber
    }
    if let newLineNumber = row.newLineNumber {
      payload["newLineNumber"] = newLineNumber
    }
    if let change = row.change {
      payload["change"] = change
    }

    return payload
  }

  private func handleFileHeaderTap(row: ReviewDiffNativeRow, rect: CGRect, point: CGPoint) {
    let interactiveRects = fileHeaderInteractiveRects(for: row, cardRect: rect)
    let fileId = resolvedFileId(for: row)

    if interactiveRects.checkbox.contains(point) {
      onToggleViewedFile?(fileId)
      return
    }

    if rect.contains(point) {
      onToggleFile?(fileId)
    }
  }

  func gestureRecognizer(
    _ gestureRecognizer: UIGestureRecognizer,
    shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
  ) -> Bool {
    false
  }

  @objc private func handleHorizontalPan(_ gesture: UIPanGestureRecognizer) {
    switch gesture.state {
    case .began:
      stopHorizontalDeceleration()
      let panTarget = horizontalPanTarget(at: gesture.location(in: self))
      activePanFileId = panTarget?.fileId
      activePanKind = panTarget?.kind
      panStartHorizontalOffset = horizontalOffset(for: panTarget?.fileId, kind: panTarget?.kind)
    case .changed, .ended, .cancelled:
      guard let activePanFileId, let activePanKind else {
        return
      }
      let translation = gesture.translation(in: self)
      setHorizontalOffset(
        min(
          max(panStartHorizontalOffset - translation.x, 0),
          maxHorizontalOffset(for: (fileId: activePanFileId, kind: activePanKind))
        ),
        for: activePanFileId,
        kind: activePanKind
      )
      if gesture.state == .ended, activePanKind == .code {
        let velocity = -gesture.velocity(in: self).x
        self.activePanFileId = nil
        self.activePanKind = nil
        startHorizontalDeceleration(fileId: activePanFileId, velocity: velocity)
      } else if gesture.state == .cancelled {
        self.activePanFileId = nil
        self.activePanKind = nil
      } else if gesture.state == .ended {
        self.activePanFileId = nil
        self.activePanKind = nil
      }
    default:
      break
    }
  }

  private func horizontalPanTarget(at point: CGPoint) -> (fileId: String, kind: ReviewDiffHorizontalPanKind)? {
    if let stickyHeader = stickyFileHeaderTarget(), stickyHeader.rect.contains(point) {
      return (resolvedFileId(for: stickyHeader.row), .fileHeaderPath)
    }

    guard let row = row(at: point) else {
      guard verticalOffset + point.y >= contentHeight,
            fileHeaderRowIndices.isEmpty,
            contentWidthsByFileId.count == 1,
            let fileId = contentWidthsByFileId.keys.first,
            !collapsedFileIds.contains(fileId) else {
        return nil
      }
      return (fileId, .code)
    }

    let fileId = resolvedFileId(for: row)
    if row.kind == "file" {
      return (fileId, .fileHeaderPath)
    }

    return (fileId, .code)
  }

  private func stickyFileHeaderTarget() -> ReviewDiffStickyFileHeaderTarget? {
    guard let stickyHeader = stickyFileHeaderRowIndex() else {
      return nil
    }

    let rowIndex = stickyHeader.rowIndex
    let headerTop = rowOffsets[rowIndex]
    guard headerTop < verticalOffset + topContentInset else {
      return nil
    }

    let nextHeaderPosition = stickyHeader.position + 1
    let nextHeaderRowIndex = fileHeaderRowIndices.indices.contains(nextHeaderPosition)
      ? fileHeaderRowIndices[nextHeaderPosition]
      : nil
    let pushedY: CGFloat
    if let nextHeaderRowIndex {
      pushedY = min(topContentInset, rowOffsets[nextHeaderRowIndex] - verticalOffset - style.fileHeaderHeight)
    } else {
      pushedY = topContentInset
    }

    guard pushedY > topContentInset - style.fileHeaderHeight else {
      return nil
    }

    let rect = CGRect(
      x: 0,
      y: pushedY,
      width: max(bounds.width, viewportWidth),
      height: style.fileHeaderHeight
    )
    return ReviewDiffStickyFileHeaderTarget(rowIndex: rowIndex, row: rows[rowIndex], rect: rect)
  }

  private func stickyFileHeaderRowIndex() -> ReviewDiffStickyFileHeaderIndex? {
    guard !fileHeaderRowIndices.isEmpty else {
      return nil
    }

    var lowerBound = 0
    var upperBound = fileHeaderRowIndices.count
    while lowerBound < upperBound {
      let midpoint = (lowerBound + upperBound) / 2
      let rowIndex = fileHeaderRowIndices[midpoint]
      if rowOffsets[rowIndex] <= verticalOffset + topContentInset {
        lowerBound = midpoint + 1
      } else {
        upperBound = midpoint
      }
    }

    let matchIndex = lowerBound - 1
    guard matchIndex >= 0 else {
      return nil
    }
    return ReviewDiffStickyFileHeaderIndex(position: matchIndex, rowIndex: fileHeaderRowIndices[matchIndex])
  }

  func scrollAnchor(forFileId fileId: String) -> ReviewDiffScrollAnchor? {
    if let stickyHeader = stickyFileHeaderTarget(),
       resolvedFileId(for: stickyHeader.row) == fileId {
      return ReviewDiffScrollAnchor(fileId: fileId, screenY: topContentInset)
    }

    guard let headerOffset = fileHeaderOffset(forFileId: fileId) else {
      return nil
    }

    return ReviewDiffScrollAnchor(fileId: fileId, screenY: headerOffset - verticalOffset)
  }

  func fileHeaderOffset(forFileId fileId: String) -> CGFloat? {
    guard let rowIndex = fileHeaderRowIndex(forFileId: fileId) else {
      return nil
    }

    return rowOffsets[rowIndex]
  }

  func visibleFileId(atVerticalOffset verticalOffset: CGFloat) -> String? {
    guard let firstHeaderRowIndex = fileHeaderRowIndices.first else {
      return nil
    }

    var lowerBound = 0
    var upperBound = fileHeaderRowIndices.count
    while lowerBound < upperBound {
      let midpoint = (lowerBound + upperBound) / 2
      let rowIndex = fileHeaderRowIndices[midpoint]
      if rowOffsets[rowIndex] <= verticalOffset + 0.5 {
        lowerBound = midpoint + 1
      } else {
        upperBound = midpoint
      }
    }

    let rowIndex = lowerBound > 0
      ? fileHeaderRowIndices[lowerBound - 1]
      : firstHeaderRowIndex
    guard rows.indices.contains(rowIndex) else {
      return nil
    }
    return resolvedFileId(for: rows[rowIndex])
  }

  private func fileHeaderRowIndex(forFileId fileId: String) -> Int? {
    fileHeaderRowIndices.first { rowIndex in
      rows.indices.contains(rowIndex) && resolvedFileId(for: rows[rowIndex]) == fileId
    }
  }

  private func row(at point: CGPoint) -> ReviewDiffNativeRow? {
    guard let rowIndex = rowIndex(at: verticalOffset + point.y) else {
      return nil
    }
    guard rows.indices.contains(rowIndex) else {
      return nil
    }
    return rows[rowIndex]
  }

  private func rowIndex(at absoluteY: CGFloat) -> Int? {
    guard !rows.isEmpty else {
      return nil
    }

    var lowerBound = 0
    var upperBound = rows.count - 1
    while lowerBound <= upperBound {
      let midpoint = (lowerBound + upperBound) / 2
      let rowStart = rowOffsets[midpoint]
      let rowEnd = rowStart + height(at: midpoint)

      if absoluteY < rowStart {
        upperBound = midpoint - 1
      } else if absoluteY >= rowEnd {
        lowerBound = midpoint + 1
      } else {
        return midpoint
      }
    }

    return nil
  }

  private func firstVisibleRowIndex(atOrAfter absoluteY: CGFloat) -> Int? {
    guard !rows.isEmpty else {
      return nil
    }

    var lowerBound = 0
    var upperBound = rows.count
    while lowerBound < upperBound {
      let midpoint = (lowerBound + upperBound) / 2
      let rowEnd = rowOffsets[midpoint] + height(at: midpoint)

      if rowEnd < absoluteY {
        lowerBound = midpoint + 1
      } else {
        upperBound = midpoint
      }
    }

    return lowerBound < rows.count ? lowerBound : nil
  }

  private func lastVisibleRowIndex(atOrBefore absoluteY: CGFloat) -> Int? {
    guard !rows.isEmpty else {
      return nil
    }

    var lowerBound = 0
    var upperBound = rows.count
    while lowerBound < upperBound {
      let midpoint = (lowerBound + upperBound) / 2
      let rowStart = rowOffsets[midpoint]

      if rowStart <= absoluteY {
        lowerBound = midpoint + 1
      } else {
        upperBound = midpoint
      }
    }

    let index = lowerBound - 1
    return index >= 0 ? index : nil
  }

  private func resolvedFileId(for row: ReviewDiffNativeRow) -> String {
    row.resolvedFileId
  }

  private func horizontalOffset(
    for fileId: String?,
    kind: ReviewDiffHorizontalPanKind? = .code
  ) -> CGFloat {
    guard let fileId else {
      return 0
    }
    if kind == .fileHeaderPath {
      return headerPathOffsetsByFileId[fileId] ?? 0
    }
    return horizontalOffsetsByFileId[fileId] ?? 0
  }

  private func setHorizontalOffset(
    _ offset: CGFloat,
    for fileId: String,
    kind: ReviewDiffHorizontalPanKind = .code
  ) {
    if kind == .fileHeaderPath {
      headerPathOffsetsByFileId[fileId] = offset
      setNeedsDisplayForVisibleBounds()
      return
    }
    horizontalOffsetsByFileId[fileId] = offset
    setNeedsDisplayForVisibleBounds()
  }

  private func clampHorizontalOffsets() {
    for (fileId, offset) in horizontalOffsetsByFileId {
      horizontalOffsetsByFileId[fileId] = min(offset, maxHorizontalOffset(for: (fileId: fileId, kind: .code)))
    }
    for (fileId, offset) in headerPathOffsetsByFileId {
      headerPathOffsetsByFileId[fileId] = min(
        offset,
        maxHorizontalOffset(for: (fileId: fileId, kind: .fileHeaderPath))
      )
    }
  }

  private func maxHorizontalOffset(for target: (fileId: String, kind: ReviewDiffHorizontalPanKind)) -> CGFloat {
    if target.kind == .fileHeaderPath,
       let rowIndex = fileHeaderRowIndex(forFileId: target.fileId) {
      return maxHeaderPathOffset(for: rows[rowIndex])
    }