Sources/OrgApp/PaneLayout.swift
71 lines · 2985 bytes
1import Foundation
2
3/// Identifies a pane for as long as it exists.
4public struct PaneID: Hashable, Sendable {
5 private let raw = UUID()
6 public init() {}
7}
8
9/// How a window divides its editor area: one pane, or two layouts side by side (`horizontal`)
10/// or one above the other (`vertical`), with the first's share of the space.
11public indirect enum PaneLayout: Equatable, Sendable {
12 public enum Axis: Equatable, Sendable { case horizontal, vertical }
13
14 case pane(PaneID)
15 case split(axis: Axis, first: PaneLayout, second: PaneLayout, fraction: Double)
16
17 /// Panes in reading order: left before right, top before bottom.
18 public var panes: [PaneID] {
19 switch self {
20 case .pane(let id): [id]
21 case .split(_, let first, let second, _): first.panes + second.panes
22 }
23 }
24
25 /// `id` halved along `axis`, with `new` after it.
26 public func splitting(_ id: PaneID, axis: Axis, new: PaneID) -> PaneLayout {
27 switch self {
28 case .pane(id): .split(axis: axis, first: .pane(id), second: .pane(new), fraction: 0.5)
29 case .pane: self
30 case .split(let a, let first, let second, let fraction):
31 .split(axis: a, first: first.splitting(id, axis: axis, new: new), second: second.splitting(id, axis: axis, new: new), fraction: fraction)
32 }
33 }
34
35 /// The layout without `id`; its sibling takes the space. Nil when `id` was the only pane.
36 public func removing(_ id: PaneID) -> PaneLayout? {
37 switch self {
38 case .pane(id): nil
39 case .pane: self
40 case .split(let axis, let first, let second, let fraction):
41 switch (first.removing(id), second.removing(id)) {
42 case (nil, let rest?), (let rest?, nil): rest
43 case (let a?, let b?): .split(axis: axis, first: a, second: b, fraction: fraction)
44 case (nil, nil): nil
45 }
46 }
47 }
48
49 /// The split whose first pane in reading order is `id`, with `fraction` for its first side.
50 public func settingFraction(_ fraction: Double, ofSplitStartingWith id: PaneID) -> PaneLayout {
51 switch self {
52 case .pane: self
53 case .split(let axis, let first, let second, let old):
54 if first.panes.first == id {
55 .split(axis: axis, first: first, second: second, fraction: min(max(fraction, 0.1), 0.9))
56 } else {
57 .split(axis: axis, first: first.settingFraction(fraction, ofSplitStartingWith: id), second: second.settingFraction(fraction, ofSplitStartingWith: id), fraction: old)
58 }
59 }
60 }
61
62 /// Only `id`, filling the window.
63 public func only(_ id: PaneID) -> PaneLayout { .pane(id) }
64
65 /// The pane after `id` in reading order, wrapping; the first when `id` isn't here.
66 public func next(after id: PaneID) -> PaneID {
67 let all = panes
68 guard let index = all.firstIndex(of: id) else { return all[0] }
69 return all[(index + 1) % all.count]
70 }
71}