aboutsummaryrefslogtreecommitdiff
path: root/Sources/NorgUI/Views/FlatBlocksView.swift
blob: 747edb631858e1ff581301115edf6c52f16ea9d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import NorgKit
import SwiftUI

struct FlatBlocksView: View {
  let blocks: [NorgBlock]
  let onSetStatus: (Int, TaskStatus) -> Void
  var indent: CGFloat = 0

  @Environment(\.norgTheme) private var theme

  var body: some View {
    let ordinals = orderedOrdinals(blocks)
    VStack(alignment: .leading, spacing: theme.blockSpacing) {
      ForEach(Array(blocks.enumerated()), id: \.offset) { index, block in
        row(block, ordinal: ordinals[index])
      }
    }
  }

  @ViewBuilder
  private func row(_ block: NorgBlock, ordinal: Int?) -> some View {
    BlockView(block: block, ordinal: ordinal, onSetStatus: onSetStatus)
      .padding(.leading, indent + levelIndent(block))
      .id(block.line)
      .frame(maxWidth: .infinity, alignment: .leading)

    if let body = block.body, !body.isEmpty {
      FlatBlocksView(blocks: body, onSetStatus: onSetStatus, indent: indent + theme.indentWidth)
    }
  }

  private func levelIndent(_ block: NorgBlock) -> CGFloat {
    switch block {
    case .unorderedListItem(let level, _, _, _),
      .orderedListItem(let level, _, _, _),
      .quote(let level, _, _, _):
      return CGFloat(max(0, level - 1)) * theme.indentWidth
    default:
      return 0
    }
  }
}