Repository Public
1import CoreGraphics2import Foundation34/// Direction in which the children of a split are laid out.5public enum SplitAxis: String, Codable, Sendable {6 /// Children side by side (a vertical divider between them).7 case horizontal8 /// Children stacked top to bottom (a horizontal divider between them).9 case vertical10}1112public enum Direction: String, Sendable, CaseIterable { case left, right, up, down }1314/// Edge of a target pane on which another pane is dropped.15public enum DropEdge: String, Sendable, CaseIterable {16 case left, right, top, bottom1718 var axis: SplitAxis { self == .left || self == .right ? .horizontal : .vertical }19 var insertsBefore: Bool { self == .left || self == .top }20}2122/// A draggable divider between two adjacent children of a split.23public struct DividerHandle: Hashable, Sendable {24 public let splitID: UUID25 /// Index of the child placed before the divider.26 public let index: Int27 public let axis: SplitAxis28 public let rect: CGRect29 /// Length of the parent split along its axis, used to convert a drag distance to a fraction.30 public let parentLength: CGFloat31}3233/// Recursive, n-ary split tree. Leaves are panes; inner nodes divide their rectangle among34/// their children according to `fractions` (which always sum to 1).35///36/// The tree is a pure value: every mutation returns/produces a normalized tree (no split with37/// fewer than two children, no directly nested split with the same axis).38public indirect enum LayoutNode: Codable, Sendable, Equatable {39 case pane(PaneID)40 case split(id: UUID, axis: SplitAxis, fractions: [Double], children: [LayoutNode])4142 /// Smallest share a child can be resized to.43 public static let minimumFraction = 0.064445 // MARK: Queries4647 /// Panes in visual order (left-to-right, top-to-bottom, depth first).48 public var panes: [PaneID] {49 switch self {50 case .pane(let id): return [id]51 case .split(_, _, _, let children): return children.flatMap(\.panes)52 }53 }5455 public var paneCount: Int { panes.count }56 public func contains(_ pane: PaneID) -> Bool { panes.contains(pane) }5758 /// Depth of the tree (a single pane has depth 1).59 public var depth: Int {60 switch self {61 case .pane: return 162 case .split(_, _, _, let children): return 1 + (children.map(\.depth).max() ?? 0)63 }64 }6566 // MARK: Mutations6768 /// Splits `target`, placing `newPane` next to it along `axis`.69 /// Returns `false` (tree unchanged) when `target` is not in the tree or `newPane` already is.70 @discardableResult71 public mutating func split(_ target: PaneID, axis: SplitAxis, newPane: PaneID, before: Bool = false) -> Bool {72 guard contains(target), !contains(newPane) else { return false }73 self = inserting(newPane, nextTo: target, axis: axis, before: before).normalized()74 return true75 }7677 private func inserting(_ newPane: PaneID, nextTo target: PaneID, axis: SplitAxis, before: Bool) -> LayoutNode {78 switch self {79 case .pane(let id):80 guard id == target else { return self }81 let pair: [LayoutNode] = before ? [.pane(newPane), .pane(id)] : [.pane(id), .pane(newPane)]82 return .split(id: UUID(), axis: axis, fractions: [0.5, 0.5], children: pair)83 case .split(let id, let splitAxis, var fractions, var children):84 // Splitting a direct child along the same axis inserts a sibling instead of nesting,85 // so "split right" three times gives three equal-ish columns sharing the target's space.86 if splitAxis == axis, let index = children.firstIndex(of: .pane(target)) {87 let half = fractions[index] / 288 fractions[index] = half89 children.insert(.pane(newPane), at: before ? index : index + 1)90 fractions.insert(half, at: before ? index : index + 1)91 return .split(id: id, axis: splitAxis, fractions: fractions, children: children)92 }93 return .split(id: id, axis: splitAxis, fractions: fractions,94 children: children.map { $0.inserting(newPane, nextTo: target, axis: axis, before: before) })95 }96 }9798 /// Removes a pane. Returns the remaining tree, or `nil` when it was the last pane.99 public func removing(_ pane: PaneID) -> LayoutNode? {100 switch self {101 case .pane(let id):102 return id == pane ? nil : self103 case .split(let id, let axis, let fractions, let children):104 var keptChildren: [LayoutNode] = []105 var keptFractions: [Double] = []106 for (child, fraction) in zip(children, fractions) {107 if let kept = child.removing(pane) {108 keptChildren.append(kept)109 keptFractions.append(fraction)110 }111 }112 if keptChildren.isEmpty { return nil }113 return LayoutNode.split(id: id, axis: axis, fractions: keptFractions, children: keptChildren).normalized()114 }115 }116117 /// Exchanges the positions of two panes.118 public mutating func swap(_ a: PaneID, _ b: PaneID) {119 guard a != b, contains(a), contains(b) else { return }120 self = mapPanes { $0 == a ? b : ($0 == b ? a : $0) }121 }122123 /// Moves `pane` so that it sits on `edge` of `target` (drag & drop re-arrangement).124 @discardableResult125 public mutating func move(_ pane: PaneID, to edge: DropEdge, of target: PaneID) -> Bool {126 guard pane != target, contains(pane), contains(target), var without = removing(pane) else { return false }127 guard without.split(target, axis: edge.axis, newPane: pane, before: edge.insertsBefore) else { return false }128 self = without129 return true130 }131132 /// Replaces a pane id (used when a pane is re-created with a new identity).133 public mutating func replace(_ old: PaneID, with new: PaneID) {134 self = mapPanes { $0 == old ? new : $0 }135 }136137 private func mapPanes(_ transform: (PaneID) -> PaneID) -> LayoutNode {138 switch self {139 case .pane(let id): return .pane(transform(id))140 case .split(let id, let axis, let fractions, let children):141 return .split(id: id, axis: axis, fractions: fractions, children: children.map { $0.mapPanes(transform) })142 }143 }144145 /// Moves the divider after child `index` of split `splitID` by `delta` (a fraction of the split).146 @discardableResult147 public mutating func resize(split splitID: UUID, dividerIndex index: Int, by delta: Double) -> Bool {148 var changed = false149 self = resizing(splitID, index, delta, &changed)150 return changed151 }152153 private func resizing(_ splitID: UUID, _ index: Int, _ delta: Double, _ changed: inout Bool) -> LayoutNode {154 guard case .split(let id, let axis, var fractions, let children) = self else { return self }155 if id == splitID {156 guard index >= 0, index + 1 < fractions.count else { return self }157 let pair = fractions[index] + fractions[index + 1]158 let minimum = min(LayoutNode.minimumFraction, pair / 2)159 let first = min(max(fractions[index] + delta, minimum), pair - minimum)160 guard abs(first - fractions[index]) > 1e-9 else { return self }161 fractions[index] = first162 fractions[index + 1] = pair - first163 changed = true164 return .split(id: id, axis: axis, fractions: fractions, children: children)165 }166 return .split(id: id, axis: axis, fractions: fractions,167 children: children.map { $0.resizing(splitID, index, delta, &changed) })168 }169170 /// Grows or shrinks `pane` along `direction` by `amount` (keyboard resize). The nearest171 /// ancestor split with a matching axis and a neighbour on that side is adjusted.172 @discardableResult173 public mutating func resize(pane: PaneID, toward direction: Direction, by amount: Double = 0.05) -> Bool {174 let axis: SplitAxis = (direction == .left || direction == .right) ? .horizontal : .vertical175 let forward = direction == .right || direction == .down176 guard let (splitID, index) = resizeTarget(for: pane, axis: axis, forward: forward) else { return false }177 return resize(split: splitID, dividerIndex: index, by: forward ? amount : -amount)178 }179180 /// Finds the deepest split of `axis` containing `pane` whose child holding the pane has a181 /// neighbour on the requested side; returns the divider to move.182 private func resizeTarget(for pane: PaneID, axis: SplitAxis, forward: Bool) -> (UUID, Int)? {183 guard case .split(let id, let splitAxis, _, let children) = self,184 let childIndex = children.firstIndex(where: { $0.contains(pane) }) else { return nil }185 if let deeper = children[childIndex].resizeTarget(for: pane, axis: axis, forward: forward) { return deeper }186 guard splitAxis == axis else { return nil }187 if forward, childIndex + 1 < children.count { return (id, childIndex) }188 if !forward, childIndex > 0 { return (id, childIndex - 1) }189 return nil190 }191192 /// Gives every child of every split the same share.193 public mutating func equalize() {194 self = equalized()195 }196197 private func equalized() -> LayoutNode {198 guard case .split(let id, let axis, _, let children) = self else { return self }199 let share = 1.0 / Double(children.count)200 return .split(id: id, axis: axis, fractions: Array(repeating: share, count: children.count),201 children: children.map { $0.equalized() })202 }203204 // MARK: Normalization205206 /// Collapses degenerate splits, flattens same-axis nesting and renormalizes fractions.207 public func normalized() -> LayoutNode {208 guard case .split(let id, let axis, let fractions, let children) = self else { return self }209 var flatChildren: [LayoutNode] = []210 var flatFractions: [Double] = []211 let safeFractions = fractions.count == children.count212 ? fractions : Array(repeating: 1.0 / Double(max(children.count, 1)), count: children.count)213 for (child, fraction) in zip(children, safeFractions) {214 let node = child.normalized()215 if case .split(_, let childAxis, let childFractions, let grandchildren) = node, childAxis == axis {216 for (grandchild, childFraction) in zip(grandchildren, childFractions) {217 flatChildren.append(grandchild)218 flatFractions.append(fraction * childFraction)219 }220 } else {221 flatChildren.append(node)222 flatFractions.append(fraction)223 }224 }225 if flatChildren.count == 1 { return flatChildren[0] }226 let cleaned = flatFractions.map { $0.isFinite && $0 > 0 ? $0 : 0.0001 }227 let total = cleaned.reduce(0, +)228 return .split(id: id, axis: axis, fractions: cleaned.map { $0 / total }, children: flatChildren)229 }230231 /// `true` when the invariants documented on the type hold for the whole tree.232 public var isWellFormed: Bool {233 switch self {234 case .pane: return true235 case .split(_, let axis, let fractions, let children):236 guard children.count >= 2, fractions.count == children.count,237 abs(fractions.reduce(0, +) - 1) < 1e-6, fractions.allSatisfy({ $0 > 0 }) else { return false }238 for child in children {239 if case .split(_, let childAxis, _, _) = child, childAxis == axis { return false }240 if !child.isWellFormed { return false }241 }242 return Set(panes).count == panes.count243 }244 }245246 // MARK: Geometry247248 /// Rectangle of every pane inside `bounds`, leaving `gap` points between siblings.249 /// The origin convention is top-left (y grows downwards).250 public func frames(in bounds: CGRect, gap: CGFloat = 1) -> [PaneID: CGRect] {251 var result: [PaneID: CGRect] = [:]252 layout(in: bounds, gap: gap, panes: &result, dividers: nil)253 return result254 }255256 /// Hit areas of every divider inside `bounds`.257 public func dividers(in bounds: CGRect, gap: CGFloat = 1, hitThickness: CGFloat = 7) -> [DividerHandle] {258 var panes: [PaneID: CGRect] = [:]259 var handles: [DividerHandle] = []260 layout(in: bounds, gap: gap, panes: &panes, dividers: (hitThickness, { handles.append($0) }))261 return handles262 }263264 private func layout(in bounds: CGRect, gap: CGFloat, panes: inout [PaneID: CGRect],265 dividers: (CGFloat, (DividerHandle) -> Void)?) {266 switch self {267 case .pane(let id):268 panes[id] = bounds269 case .split(let id, let axis, let fractions, let children):270 let length = axis == .horizontal ? bounds.width : bounds.height271 let usable = max(0, length - gap * CGFloat(children.count - 1))272 var offset: CGFloat = 0273 for (index, child) in children.enumerated() {274 let isLast = index == children.count - 1275 // The last child absorbs rounding so the split always fills its bounds exactly.276 let extent = isLast ? max(0, usable - offset) : (usable * CGFloat(fractions[index])).rounded()277 let start = offset + gap * CGFloat(index)278 let rect = axis == .horizontal279 ? CGRect(x: bounds.minX + start, y: bounds.minY, width: extent, height: bounds.height)280 : CGRect(x: bounds.minX, y: bounds.minY + start, width: bounds.width, height: extent)281 child.layout(in: rect, gap: gap, panes: &panes, dividers: dividers)282 offset += extent283 if !isLast, let (thickness, emit) = dividers {284 let center = start + extent + gap / 2285 let handle = axis == .horizontal286 ? CGRect(x: bounds.minX + center - thickness / 2, y: bounds.minY, width: thickness, height: bounds.height)287 : CGRect(x: bounds.minX, y: bounds.minY + center - thickness / 2, width: bounds.width, height: thickness)288 emit(DividerHandle(splitID: id, index: index, axis: axis, rect: handle, parentLength: usable))289 }290 }291 }292 }293294 /// The pane the keyboard focus should move to from `pane` in `direction`, judged on the295 /// actual geometry (largest overlap on the facing edge, then nearest).296 public func neighbor(of pane: PaneID, toward direction: Direction,297 in bounds: CGRect = CGRect(x: 0, y: 0, width: 1000, height: 1000)) -> PaneID? {298 let all = frames(in: bounds, gap: 0)299 guard let origin = all[pane] else { return nil }300 var best: (id: PaneID, overlap: CGFloat, distance: CGFloat)?301 for id in panes where id != pane {302 guard let rect = all[id] else { continue }303 let distance: CGFloat304 let overlap: CGFloat305 switch direction {306 case .left:307 distance = origin.minX - rect.maxX308 overlap = min(origin.maxY, rect.maxY) - max(origin.minY, rect.minY)309 case .right:310 distance = rect.minX - origin.maxX311 overlap = min(origin.maxY, rect.maxY) - max(origin.minY, rect.minY)312 case .up:313 distance = origin.minY - rect.maxY314 overlap = min(origin.maxX, rect.maxX) - max(origin.minX, rect.minX)315 case .down:316 distance = rect.minY - origin.maxY317 overlap = min(origin.maxX, rect.maxX) - max(origin.minX, rect.minX)318 }319 guard distance > -0.5, overlap > 0.5 else { continue }320 if let current = best {321 if distance < current.distance - 0.5 || (abs(distance - current.distance) <= 0.5 && overlap > current.overlap) {322 best = (id, overlap, distance)323 }324 } else {325 best = (id, overlap, distance)326 }327 }328 return best?.id329 }330331 // MARK: Builders332333 /// A near-square grid of the given panes: `columns` columns, rows filled top to bottom.334 public static func grid(_ panes: [PaneID], columns: Int? = nil) -> LayoutNode? {335 guard !panes.isEmpty else { return nil }336 if panes.count == 1 { return .pane(panes[0]) }337 let columnCount = max(1, min(panes.count, columns ?? Int(Double(panes.count).squareRoot().rounded(.up))))338 let rowCount = Int((Double(panes.count) / Double(columnCount)).rounded(.up))339 var rows: [LayoutNode] = []340 for row in 0..<rowCount {341 let slice = Array(panes[(row * columnCount)..<min(panes.count, (row + 1) * columnCount)])342 rows.append(even(slice.map { .pane($0) }, axis: .horizontal))343 }344 return even(rows, axis: .vertical).normalized()345 }346347 /// A split with equal shares (a single child is returned unchanged).348 public static func even(_ children: [LayoutNode], axis: SplitAxis) -> LayoutNode {349 precondition(!children.isEmpty)350 if children.count == 1 { return children[0] }351 return .split(id: UUID(), axis: axis,352 fractions: Array(repeating: 1.0 / Double(children.count), count: children.count), children: children)353 }354355 /// A split with explicit shares (normalized).356 public static func weighted(_ children: [(LayoutNode, Double)], axis: SplitAxis) -> LayoutNode {357 precondition(!children.isEmpty)358 if children.count == 1 { return children[0].0 }359 return LayoutNode.split(id: UUID(), axis: axis, fractions: children.map(\.1), children: children.map(\.0)).normalized()360 }361}362