SPB Git

Repository Public

LayoutNode.swift 8.2 KB 180 lines swift

1import Foundation23/// Direction in which a split lays out its children.4/// `.horizontal` places children side by side (left → right);5/// `.vertical` stacks them (top → bottom).6public enum SplitAxis: String, Codable, Sendable, Hashable {7    case horizontal8    case vertical910    public var perpendicular: SplitAxis { self == .horizontal ? .vertical : .horizontal }11}1213/// Direction for keyboard navigation between panes.14public enum NavigationDirection: String, Sendable, CaseIterable {15    case left, right, up, down16}1718/// The pane layout of a tab, as an immutable value tree.19///20/// Leaves reference a `PaneID`; splits own an ordered list of children and a list of21/// fractions (summing to 1) that describe how much of the split's extent each child takes.22/// All mutations return a new tree; nothing here touches a process or a view, which is what23/// guarantees that a layout edit can never recreate a PTY.24public indirect enum LayoutNode: Codable, Sendable, Hashable {25    case leaf(PaneID)26    case split(id: SplitID, axis: SplitAxis, children: [LayoutNode], fractions: [Double])2728    public static let minimumFraction = 0.082930    // MARK: Queries3132    /// All pane IDs in depth-first (visual) order.33    public var paneIDs: [PaneID] {34        switch self {35        case .leaf(let id): return [id]36        case .split(_, _, let children, _): return children.flatMap(\.paneIDs)37        }38    }3940    public var paneCount: Int { paneIDs.count }4142    public func contains(_ pane: PaneID) -> Bool {43        paneIDs.contains(pane)44    }4546    public var firstPane: PaneID? { paneIDs.first }4748    /// Depth of the deepest leaf. A single leaf has depth 0.49    public var depth: Int {50        switch self {51        case .leaf: return 052        case .split(_, _, let children, _): return 1 + (children.map(\.depth).max() ?? 0)53        }54    }5556    /// Validates structural invariants: fractions match children, sum to ~1, splits have ≥2 children.57    public var isWellFormed: Bool {58        switch self {59        case .leaf: return true60        case .split(_, _, let children, let fractions):61            guard children.count >= 2, fractions.count == children.count else { return false }62            guard abs(fractions.reduce(0, +) - 1.0) < 0.001 else { return false }63            guard fractions.allSatisfy({ $0 > 0 }) else { return false }64            return children.allSatisfy(\.isWellFormed)65        }66    }6768    // MARK: Mutations (value semantics)6970    /// Splits `target` along `axis`, inserting `newPane` after it (or before when `after == false`).71    /// If the enclosing split already has the same axis the new pane joins it as a sibling, which keeps72    /// trees shallow and matches what users expect from repeated "split right".73    public func splitting(_ target: PaneID, axis: SplitAxis, newPane: PaneID, after: Bool = true) -> LayoutNode {74        switch self {75        case .leaf(let id):76            guard id == target else { return self }77            let children: [LayoutNode] = after ? [.leaf(id), .leaf(newPane)] : [.leaf(newPane), .leaf(id)]78            return .split(id: SplitID(), axis: axis, children: children, fractions: [0.5, 0.5])79        case .split(let sid, let saxis, let children, let fractions):80            if saxis == axis, let idx = children.firstIndex(where: { if case .leaf(let l) = $0 { return l == target } else { return false } }) {81                // Join the existing split: take half of the target's fraction.82                var newChildren = children83                var newFractions = fractions84                let half = fractions[idx] / 285                newFractions[idx] = half86                let insertAt = after ? idx + 1 : idx87                newChildren.insert(.leaf(newPane), at: insertAt)88                newFractions.insert(half, at: insertAt)89                return .split(id: sid, axis: saxis, children: newChildren, fractions: newFractions)90            }91            let newChildren = children.map { $0.splitting(target, axis: axis, newPane: newPane, after: after) }92            return .split(id: sid, axis: saxis, children: newChildren, fractions: fractions)93        }94    }9596    /// Removes a pane. Returns `nil` when the tree becomes empty. Single-child splits collapse97    /// into their child and the remaining fractions are renormalised.98    public func removing(_ target: PaneID) -> LayoutNode? {99        switch self {100        case .leaf(let id):101            return id == target ? nil : self102        case .split(let sid, let axis, let children, let fractions):103            var newChildren: [LayoutNode] = []104            var newFractions: [Double] = []105            for (child, fraction) in zip(children, fractions) {106                if let kept = child.removing(target) {107                    newChildren.append(kept)108                    newFractions.append(fraction)109                }110            }111            if newChildren.isEmpty { return nil }112            if newChildren.count == 1 { return newChildren[0] }113            let total = newFractions.reduce(0, +)114            return .split(id: sid, axis: axis, children: newChildren, fractions: newFractions.map { $0 / total })115        }116    }117118    /// Replaces the leaf `old` with the leaf `new`.119    public func replacing(_ old: PaneID, with new: PaneID) -> LayoutNode {120        switch self {121        case .leaf(let id): return id == old ? .leaf(new) : self122        case .split(let sid, let axis, let children, let fractions):123            return .split(id: sid, axis: axis, children: children.map { $0.replacing(old, with: new) }, fractions: fractions)124        }125    }126127    /// Swaps the positions of two panes without changing the tree shape.128    public func swapping(_ a: PaneID, _ b: PaneID) -> LayoutNode {129        guard a != b, contains(a), contains(b) else { return self }130        let placeholder = PaneID()131        return replacing(a, with: placeholder).replacing(b, with: a).replacing(placeholder, with: b)132    }133134    /// Moves `pane` so that it becomes a sibling of `target` along `axis`.135    public func moving(_ pane: PaneID, nextTo target: PaneID, axis: SplitAxis, after: Bool) -> LayoutNode {136        guard pane != target, contains(pane), contains(target) else { return self }137        guard let without = removing(pane) else { return self }138        return without.splitting(target, axis: axis, newPane: pane, after: after)139    }140141    /// Adjusts the divider at `dividerIndex` (between child i and i+1) of split `splitID` by `delta`142    /// (a fraction of the split's extent; positive grows the first child).143    public func resizing(split splitID: SplitID, dividerIndex: Int, delta: Double) -> LayoutNode {144        switch self {145        case .leaf: return self146        case .split(let sid, let axis, let children, let fractions):147            if sid == splitID {148                guard dividerIndex >= 0, dividerIndex + 1 < fractions.count else { return self }149                var f = fractions150                let pairTotal = f[dividerIndex] + f[dividerIndex + 1]151                let minF = min(LayoutNode.minimumFraction, pairTotal / 2)152                var first = f[dividerIndex] + delta153                first = max(minF, min(pairTotal - minF, first))154                f[dividerIndex] = first155                f[dividerIndex + 1] = pairTotal - first156                return .split(id: sid, axis: axis, children: children, fractions: f)157            }158            return .split(id: sid, axis: axis, children: children.map { $0.resizing(split: splitID, dividerIndex: dividerIndex, delta: delta) }, fractions: fractions)159        }160    }161162    /// Resets every split in the tree to equal fractions.163    public func equalized() -> LayoutNode {164        switch self {165        case .leaf: return self166        case .split(let sid, let axis, let children, _):167            let n = Double(children.count)168            return .split(id: sid, axis: axis, children: children.map { $0.equalized() }, fractions: Array(repeating: 1 / n, count: children.count))169        }170    }171172    /// The next pane in DFS order after `pane` (wrapping), or nil if `pane` is absent.173    public func nextPane(after pane: PaneID, reverse: Bool = false) -> PaneID? {174        let ids = paneIDs175        guard let idx = ids.firstIndex(of: pane), ids.count > 1 else { return nil }176        let next = reverse ? (idx - 1 + ids.count) % ids.count : (idx + 1) % ids.count177        return ids[next]178    }179}180
Files main
Menu

Theme