SPB Git

Repository Public

LayoutTests.swift 13.1 KB 294 lines swift

1import CoreGraphics2import Foundation3import Testing4@testable import WorkspaceKit56@Suite("Layout tree")7struct LayoutTests {8    let bounds = CGRect(x: 0, y: 0, width: 1200, height: 800)910    @Test func splittingCreatesRecursiveTree() {11        let a = PaneID(), b = PaneID(), c = PaneID(), d = PaneID()12        var tree = LayoutNode.pane(a)13        let ok1 = tree.split(a, axis: .horizontal, newPane: b)14        #expect(ok1)15        let ok2 = tree.split(b, axis: .vertical, newPane: c)16        #expect(ok2)17        let ok3 = tree.split(c, axis: .horizontal, newPane: d)18        #expect(ok3)19        #expect(tree.panes == [a, b, c, d])20        #expect(tree.depth == 4)21        #expect(tree.isWellFormed)22        // Unknown target and duplicate pane are rejected without changing the tree.23        let before = tree24        let ok4 = tree.split(PaneID(), axis: .horizontal, newPane: PaneID())25        #expect(!ok4)26        let ok5 = tree.split(a, axis: .horizontal, newPane: b)27        #expect(!ok5)28        #expect(tree == before)29    }3031    @Test func sameAxisSplitsStayFlat() {32        let a = PaneID(), b = PaneID(), c = PaneID()33        var tree = LayoutNode.pane(a)34        tree.split(a, axis: .horizontal, newPane: b)35        tree.split(b, axis: .horizontal, newPane: c)36        guard case .split(_, .horizontal, let fractions, let children) = tree else { Issue.record("expected split"); return }37        #expect(children.count == 3)38        #expect(abs(fractions.reduce(0, +) - 1) < 1e-9)39        #expect(tree.depth == 2)40    }4142    @Test func framesTileTheBoundsExactly() {43        for count in [2, 3, 4, 6, 8] {44            let panes = (0..<count).map { _ in PaneID() }45            let tree = LayoutNode.grid(panes)!46            let frames = tree.frames(in: bounds, gap: 1)47            #expect(frames.count == count)48            var area: CGFloat = 049            for (_, rect) in frames {50                #expect(bounds.contains(rect))51                #expect(rect.width > 100 && rect.height > 100)52                area += rect.width * rect.height53            }54            // No overlap: pairwise intersections are empty.55            let rects = Array(frames.values)56            for i in rects.indices { for j in rects.indices where j > i {57                let overlap = rects[i].intersection(rects[j])58                #expect(overlap.isNull || overlap.width * overlap.height == 0)59            } }60            // Only the 1-pt gaps are not covered.61            #expect(area > bounds.width * bounds.height * 0.98)62            #expect(tree.isWellFormed)63        }64    }6566    @Test func removingCollapsesAndLastPaneYieldsNil() {67        let a = PaneID(), b = PaneID(), c = PaneID()68        var tree = LayoutNode.pane(a)69        tree.split(a, axis: .horizontal, newPane: b)70        tree.split(b, axis: .vertical, newPane: c)71        let withoutC = tree.removing(c)!72        #expect(withoutC.panes == [a, b])73        #expect(withoutC.isWellFormed)74        let onlyA = withoutC.removing(b)!75        #expect(onlyA == .pane(a))76        #expect(onlyA.removing(a) == nil)77        #expect(tree.removing(PaneID()) == tree)78    }7980    @Test func resizeMovesDividerWithinLimits() {81        let a = PaneID(), b = PaneID()82        var tree = LayoutNode.pane(a)83        tree.split(a, axis: .horizontal, newPane: b)84        let handle = tree.dividers(in: bounds)[0]85        #expect(handle.axis == .horizontal)86        let ok6 = tree.resize(split: handle.splitID, dividerIndex: 0, by: 0.2)87        #expect(ok6)88        let frames = tree.frames(in: bounds, gap: 0)89        #expect(abs(frames[a]!.width - 840) < 2)90        // Cannot crush a pane below the minimum share.91        tree.resize(split: handle.splitID, dividerIndex: 0, by: 5)92        guard case .split(_, _, let fractions, _) = tree else { return }93        #expect(fractions[1] >= LayoutNode.minimumFraction - 1e-9)94        #expect(abs(fractions.reduce(0, +) - 1) < 1e-9)95        let ok7 = tree.resize(split: UUID(), dividerIndex: 0, by: 0.1)96        #expect(!ok7)97    }9899    @Test func keyboardResizeFindsTheRightAncestor() {100        let a = PaneID(), b = PaneID(), c = PaneID()101        var tree = LayoutNode.pane(a)102        tree.split(a, axis: .horizontal, newPane: b)103        tree.split(b, axis: .vertical, newPane: c)104        let before = tree.frames(in: bounds, gap: 0)105        let ok8 = tree.resize(pane: c, toward: .left, by: 0.1)106        #expect(ok8)107        let after = tree.frames(in: bounds, gap: 0)108        #expect(after[c]!.width > before[c]!.width)109        let ok9 = tree.resize(pane: c, toward: .up, by: 0.1)110        #expect(ok9)111        #expect(tree.frames(in: bounds, gap: 0)[c]!.height > after[c]!.height)112        let ok10 = tree.resize(pane: a, toward: .left)113        #expect(!ok10)114    }115116    @Test func focusNavigationFollowsGeometry() {117        let p = (0..<4).map { _ in PaneID() }118        let tree = LayoutNode.grid(p, columns: 2)!   // p0 p1 / p2 p3119        #expect(tree.neighbor(of: p[0], toward: .right) == p[1])120        #expect(tree.neighbor(of: p[0], toward: .down) == p[2])121        #expect(tree.neighbor(of: p[3], toward: .left) == p[2])122        #expect(tree.neighbor(of: p[3], toward: .up) == p[1])123        #expect(tree.neighbor(of: p[0], toward: .left) == nil)124        #expect(tree.neighbor(of: p[0], toward: .up) == nil)125    }126127    @Test func swapAndMoveRearrange() {128        let p = (0..<3).map { _ in PaneID() }129        var tree = LayoutNode.grid(p, columns: 3)!130        tree.swap(p[0], p[2])131        #expect(tree.panes == [p[2], p[1], p[0]])132        let ok11 = tree.move(p[2], to: .bottom, of: p[0])133        #expect(ok11)134        #expect(tree.isWellFormed)135        #expect(Set(tree.panes) == Set(p))136        let frames = tree.frames(in: bounds, gap: 0)137        #expect(frames[p[2]]!.minY > frames[p[0]]!.minY)138        #expect(abs(frames[p[2]]!.minX - frames[p[0]]!.minX) < 1)139        let ok12 = tree.move(p[0], to: .left, of: p[0])140        #expect(!ok12)141    }142143    @Test func normalizationRepairsDegenerateTrees() {144        let a = PaneID(), b = PaneID()145        let messy = LayoutNode.split(id: UUID(), axis: .horizontal, fractions: [0, .nan], children: [146            .split(id: UUID(), axis: .horizontal, fractions: [1], children: [.pane(a)]), .pane(b)])147        let clean = messy.normalized()148        #expect(clean.isWellFormed)149        #expect(clean.panes == [a, b])150    }151152    @Test func codableRoundTrip() throws {153        let p = (0..<6).map { _ in PaneID() }154        let tree = LayoutNode.grid(p)!155        let data = try JSONEncoder().encode(tree)156        let decoded = try JSONDecoder().decode(LayoutNode.self, from: data)157        #expect(decoded == tree)158    }159160    @Test func randomOperationsKeepInvariants() {161        var generator = SystemRandomNumberGenerator()162        for _ in 0..<200 {163            var panes = [PaneID()]164            var tree = LayoutNode.pane(panes[0])165            for _ in 0..<40 {166                switch Int.random(in: 0..<5, using: &generator) {167                case 0, 1:168                    let new = PaneID()169                    if tree.split(panes.randomElement(using: &generator)!, axis: Bool.random() ? .horizontal : .vertical,170                                  newPane: new, before: Bool.random()) { panes.append(new) }171                case 2:172                    guard panes.count > 1 else { continue }173                    let victim = panes.remove(at: Int.random(in: 0..<panes.count, using: &generator))174                    tree = tree.removing(victim)!175                case 3:176                    guard panes.count > 1 else { continue }177                    tree.move(panes.randomElement(using: &generator)!, to: DropEdge.allCases.randomElement(using: &generator)!,178                              of: panes.randomElement(using: &generator)!)179                default:180                    tree.resize(pane: panes.randomElement(using: &generator)!, toward: Direction.allCases.randomElement(using: &generator)!,181                                by: Double.random(in: -0.5...0.5, using: &generator))182                }183                #expect(tree.isWellFormed)184                #expect(Set(tree.panes) == Set(panes))185            }186            let frames = tree.frames(in: bounds, gap: 1)187            #expect(frames.values.allSatisfy { $0.width >= 0 && $0.height >= 0 && bounds.insetBy(dx: -1, dy: -1).contains($0) })188        }189    }190}191192@Suite("Tabs, snapshots and presets")193struct WorkspaceModelTests {194    @Test func tabSplitRemoveKeepsConsistency() {195        let first = PaneDescriptor()196        var tab = TabModel(single: first)197        let second = PaneDescriptor(role: "tests")198        let ok13 = tab.split(first.id, axis: .horizontal, adding: second)199        #expect(ok13)200        #expect(tab.focusedPane == second.id)201        #expect(tab.isConsistent)202        tab.zoomedPane = second.id203        let removed = tab.remove(second.id)204        #expect(removed?.role == "tests")205        #expect(tab.focusedPane == first.id)206        #expect(tab.zoomedPane == nil)207        #expect(tab.isConsistent)208        tab.remove(first.id)209        #expect(tab.isEmpty)210    }211212    @Test func repairFixesDamagedTab() {213        let a = PaneDescriptor(), b = PaneDescriptor()214        let ghost = PaneID()215        var tab = TabModel(layout: .split(id: UUID(), axis: .horizontal, fractions: [0.3, 0.3, 0.4],216                                          children: [.pane(a.id), .pane(ghost), .pane(b.id)]),217                           panes: [a, b, PaneDescriptor()], focusedPane: ghost, zoomedPane: ghost)218        #expect(!tab.isConsistent)219        tab.repair()220        #expect(tab.isConsistent)221        #expect(tab.layout.panes == [a.id, b.id])222    }223224    @Test func everyPresetIsConsistent() {225        for preset in WorkspacePreset.allCases {226            for screens in [1, 2] {227                let snapshot = PresetBuilder.build(preset, options: PresetOptions(hosts: ["a", "b", "c"], screenCount: screens))228                #expect(!snapshot.windows.isEmpty)229                for window in snapshot.windows {230                    #expect(window.selectedTab != nil)231                    for tab in window.tabs { #expect(tab.isConsistent, "\(preset) tab inconsistent") }232                }233            }234        }235        #expect(PresetBuilder.build(.fourPanes).paneCount == 4)236        #expect(PresetBuilder.build(.grid6).paneCount == 6)237        #expect(PresetBuilder.build(.grid8).paneCount == 8)238        #expect(PresetBuilder.build(.codeTestsLogs).paneCount == 3)239    }240241    @Test func dualMonitorUsesTwoSlotsOnlyWithTwoScreens() {242        let two = PresetBuilder.build(.dualMonitor, options: PresetOptions(screenCount: 2))243        #expect(two.windows.map(\.screenSlot) == [0, 1])244        let one = PresetBuilder.build(.dualMonitor, options: PresetOptions(screenCount: 1))245        #expect(one.windows.count == 2)246        #expect(one.windows.map(\.screenSlot) == [0, 0])247    }248249    @Test func sshFleetCreatesOnePanePerHostAndOverflowsToTabs() {250        let hosts = (1...10).map { "node\($0)" }251        let fleet = PresetBuilder.build(.sshFleet, options: PresetOptions(hosts: hosts, maxPanesPerWindow: 4))252        let all = fleet.windows[0].tabs.flatMap(\.panes)253        #expect(all.count == 10)254        #expect(fleet.windows[0].tabs.count == 3)255        #expect(all.map(\.kind) == hosts.map { SessionKind.ssh(hostAlias: $0) })256        // Broadcast is never pre-enabled by a preset.257        #expect(all.allSatisfy { !$0.receivesBroadcast })258    }259260    @Test func snapshotRoundTripsAndInstantiatesWithFreshIDs() throws {261        let original = PresetBuilder.build(.agentCommandCenter, options: PresetOptions(agentCommands: ["claude", "", "codex"]))262        let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .iso8601263        let decoder = JSONDecoder(); decoder.dateDecodingStrategy = .iso8601264        let decoded = try decoder.decode(WorkspaceSnapshot.self, from: encoder.encode(original))265        #expect(decoded.windows == original.windows)266        let copy = original.instantiated()267        #expect(copy.paneCount == original.paneCount)268        let oldIDs = Set(original.windows.flatMap(\.tabs).flatMap(\.panes).map(\.id))269        let newIDs = Set(copy.windows.flatMap(\.tabs).flatMap(\.panes).map(\.id))270        #expect(oldIDs.isDisjoint(with: newIDs))271        let allConsistent = copy.windows.flatMap(\.tabs).allSatisfy { $0.isConsistent }272        #expect(allConsistent)273        let commands: [String] = copy.windows[0].tabs[0].panes.compactMap { pane in274            if case .command(let line) = pane.kind { return line }275            return nil276        }277        #expect(commands == ["claude", "codex"])278    }279280    @Test func paneCapacityScalesWithScreenSize() {281        #expect(PaneCapacity.recommendedMaximum(for: CGSize(width: 1312, height: 790)) == 4)282        #expect(PaneCapacity.recommendedMaximum(for: CGSize(width: 1920, height: 1050)) >= 4)283        #expect(PaneCapacity.recommendedMaximum(for: CGSize(width: 3840, height: 2100)) == 8)284        #expect(PaneCapacity.recommendedMaximum(for: CGSize(width: 300, height: 200)) == 1)285    }286287    @Test func descriptorDecodingToleratesMissingFields() throws {288        let id = UUID().uuidString289        let pane = try JSONDecoder().decode(PaneDescriptor.self, from: Data(#"{"id":"\#(id)"}"#.utf8))290        #expect(pane.kind == .localShell(path: nil))291        #expect(!pane.receivesBroadcast)292    }293}294
Files main
Menu

Theme