SPB Git

Repository Public License

TabLayout.swift 15.7 KB 327 lines swift

1import CoreGraphics2import Foundation3import NavigatorCore45/// One row of a tab tree (vertical layout).6public struct TabTreeRow: Sendable, Equatable, Identifiable {7    public var tab: Tab8    /// 0 for a root tab; children of a tab are one level deeper, capped at `TabLayout.maximumDepth`.9    public var depth: Int10    public var childCount: Int11    public var id: TabID { tab.id }12}1314/// A block of the tab list: the pinned tabs, a group, or tabs outside any group.15public struct TabSection: Sendable, Equatable, Identifiable {16    public enum Kind: Sendable, Equatable {17        case pinned18        case group(TabGroup)19        case ungrouped20    }2122    public var kind: Kind23    /// Tabs to show, in order, with their tree depth. Empty for a collapsed group.24    public var rows: [TabTreeRow]25    /// Tabs hidden because the group is collapsed (the header shows the count).26    public var hiddenCount: Int2728    public var id: String {29        switch kind {30        case .pinned: "pinned"31        case .group(let group): "group-\(group.id.string)"32        case .ungrouped: "ungrouped"33        }34    }35}3637/// Sizes of the horizontal tab strip.38public struct TabStripMetrics: Sendable, Equatable {39    public var pinnedWidth: Double40    public var minimumTabWidth: Double41    public var maximumTabWidth: Double42    public var spacing: Double43    /// Width of the overflow button, reserved only when some tabs do not fit.44    public var overflowButtonWidth: Double4546    public init(pinnedWidth: Double = 40, minimumTabWidth: Double = 88, maximumTabWidth: Double = 220,47                spacing: Double = 4, overflowButtonWidth: Double = 36) {48        self.pinnedWidth = max(pinnedWidth, 1); self.minimumTabWidth = max(minimumTabWidth, 1)49        self.maximumTabWidth = max(maximumTabWidth, self.minimumTabWidth); self.spacing = max(spacing, 0)50        self.overflowButtonWidth = max(overflowButtonWidth, 0)51    }52}5354/// Result of fitting tabs in a strip of a given width.55public struct TabStripLayout: Sendable, Equatable {56    /// Tabs drawn in the strip, in order (pinned first).57    public var visible: [TabID]58    /// Tabs reachable through the overflow menu, in order.59    public var overflow: [TabID]60    /// Width given to every unpinned visible tab.61    public var tabWidth: Double62    public var pinnedWidth: Double6364    public var hasOverflow: Bool { !overflow.isEmpty }65}6667/// What a window shows for a tab layout mode.68public enum TabPresentation: Sendable, Equatable {69    /// Sidebar: sections with tree indentation.70    case vertical(sections: [TabSection])71    /// Strip at the top: flat order, overflow menu.72    case horizontal(strip: TabStripLayout, sections: [TabSection])73    /// Only the current tab is shown; `switcher` is the most-recently-used list behind the tab count button.74    case compact(current: TabID?, switcher: [TabID], count: Int)75    /// Thumbnails in a grid, flat order.76    case grid(order: [TabID], frames: [CGRect])77    /// Tabs as satellites around the space: pinned tabs on ring 0, the others on the rings after.78    case orbit(slots: [TabID: OrbitSlot], order: [TabID])79}8081/// Pure functions that turn the tabs of a window into what each `TabLayoutMode` displays.82public enum TabLayout {83    public static let maximumDepth = 68485    // MARK: Ordering8687    /// Display order: open tabs only, pinned first, then `order`, creation date and id (same rule as storage).88    public static func ordered(_ tabs: [Tab]) -> [Tab] {89        tabs.filter { $0.closedAt == nil }.sorted { lhs, rhs in90            if lhs.isPinned != rhs.isPinned { return lhs.isPinned }91            return (lhs.order, lhs.createdAt, lhs.id) < (rhs.order, rhs.createdAt, rhs.id)92        }93    }9495    /// Most recently used first; the id breaks ties so the list is stable.96    public static func mostRecentlyUsed(_ tabs: [Tab]) -> [Tab] {97        tabs.filter { $0.closedAt == nil }.sorted {98            $0.lastActiveAt != $1.lastActiveAt ? $0.lastActiveAt > $1.lastActiveAt : $0.id < $1.id99        }100    }101102    // MARK: Tree103104    /// Depth-first rows of a tab tree built from `parentID`. A tab whose parent is not in `tabs` (closed, in105    /// another window, in another section) is a root. A parent cycle — which storage cannot rule out after a106    /// sync merge — is cut: its tabs become roots instead of disappearing.107    public static func tree(_ tabs: [Tab]) -> [TabTreeRow] {108        let ordered = ordered(tabs)109        let known = Set(ordered.map(\.id))110        var children: [TabID: [Tab]] = [:]111        var roots: [Tab] = []112        for tab in ordered {113            if let parent = tab.parentID, parent != tab.id, known.contains(parent) {114                children[parent, default: []].append(tab)115            } else {116                roots.append(tab)117            }118        }119        var rows: [TabTreeRow] = []120        var visited = Set<TabID>()121        func visit(_ tab: Tab, depth: Int) {122            guard visited.insert(tab.id).inserted else { return }123            let kids = children[tab.id] ?? []124            rows.append(TabTreeRow(tab: tab, depth: min(depth, maximumDepth), childCount: kids.count))125            for kid in kids { visit(kid, depth: depth + 1) }126        }127        for root in roots { visit(root, depth: 0) }128        // Whatever is left belongs to a cycle with no root.129        for tab in ordered where !visited.contains(tab.id) { visit(tab, depth: 0) }130        return rows131    }132133    /// Rows with the subtrees of `collapsed` tabs removed (the collapsed tab itself stays).134    public static func tree(_ tabs: [Tab], collapsed: Set<TabID>) -> [TabTreeRow] {135        var result: [TabTreeRow] = []136        var hideBelow: Int?137        for row in tree(tabs) {138            if let limit = hideBelow {139                if row.depth > limit { continue }140                hideBelow = nil141            }142            result.append(row)143            if collapsed.contains(row.tab.id), row.childCount > 0 { hideBelow = row.depth }144        }145        return result146    }147148    // MARK: Sections149150    /// Pinned tabs, then each group in `order` (collapsed groups keep their header and hide their tabs, except151    /// the selected tab, which is never hidden), then the tabs outside any group. Empty sections are omitted,152    /// except groups, which the user created and expects to see.153    public static func sections(tabs: [Tab], groups: [TabGroup], selected: TabID? = nil,154                                collapsedTrees: Set<TabID> = []) -> [TabSection] {155        let open = ordered(tabs)156        let groupIDs = Set(groups.map(\.id))157        var result: [TabSection] = []158159        let pinned = open.filter(\.isPinned)160        if !pinned.isEmpty {161            // Pinned tabs are a flat row of favourites: no tree, no group.162            result.append(TabSection(kind: .pinned, rows: pinned.map { TabTreeRow(tab: $0, depth: 0, childCount: 0) },163                                     hiddenCount: 0))164        }165        let unpinned = open.filter { !$0.isPinned }166        for group in groups.sorted(by: { ($0.order, $0.id) < ($1.order, $1.id) }) {167            let members = unpinned.filter { $0.groupID == group.id }168            if group.isCollapsed {169                let kept = members.filter { $0.id == selected }170                result.append(TabSection(kind: .group(group), rows: kept.map { TabTreeRow(tab: $0, depth: 0, childCount: 0) },171                                         hiddenCount: members.count - kept.count))172            } else {173                result.append(TabSection(kind: .group(group), rows: tree(members, collapsed: collapsedTrees), hiddenCount: 0))174            }175        }176        let loose = unpinned.filter { $0.groupID.map { !groupIDs.contains($0) } ?? true }177        if !loose.isEmpty {178            result.append(TabSection(kind: .ungrouped, rows: tree(loose, collapsed: collapsedTrees), hiddenCount: 0))179        }180        return result181    }182183    /// Flat order matching `sections`: what keyboard "next tab" and the horizontal strip walk through.184    public static func flatOrder(tabs: [Tab], groups: [TabGroup], selected: TabID? = nil) -> [TabID] {185        sections(tabs: tabs, groups: groups, selected: selected).flatMap { $0.rows.map(\.tab.id) }186    }187188    // MARK: Horizontal overflow189190    /// Fits `order` (pinned tabs first) in `width`.191    ///192    /// Pinned tabs have a fixed width. Unpinned tabs share the rest equally, between the minimum and maximum193    /// width. When even the minimum does not fit, the strip keeps as many as it can and the others go to the194    /// overflow menu; the selected tab is always kept visible by swapping it in for the last visible one.195    /// If the pinned tabs alone do not fit, the last ones overflow too.196    public static func strip(order: [TabID], pinned: Set<TabID>, selected: TabID?, width: Double,197                             metrics: TabStripMetrics = TabStripMetrics()) -> TabStripLayout {198        let pinnedIDs = order.filter(pinned.contains)199        let others = order.filter { !pinned.contains($0) }200        func used(pinnedCount: Int, tabCount: Int, tabWidth: Double) -> Double {201            let items = pinnedCount + tabCount202            return Double(pinnedCount) * metrics.pinnedWidth + Double(tabCount) * tabWidth203                + Double(max(items - 1, 0)) * metrics.spacing204        }205        guard width > 0, !order.isEmpty else {206            return TabStripLayout(visible: [], overflow: order, tabWidth: metrics.minimumTabWidth, pinnedWidth: metrics.pinnedWidth)207        }208209        // Everything fits, possibly with narrower tabs.210        if used(pinnedCount: pinnedIDs.count, tabCount: others.count, tabWidth: metrics.minimumTabWidth) <= width {211            var tabWidth = metrics.maximumTabWidth212            if !others.isEmpty {213                let fixed = used(pinnedCount: pinnedIDs.count, tabCount: others.count, tabWidth: 0)214                tabWidth = min(metrics.maximumTabWidth, max(metrics.minimumTabWidth, (width - fixed) / Double(others.count)))215            }216            return TabStripLayout(visible: order.filter { pinned.contains($0) } + others, overflow: [],217                                  tabWidth: tabWidth, pinnedWidth: metrics.pinnedWidth)218        }219220        let available = width - metrics.overflowButtonWidth - metrics.spacing221        var pinnedCount = pinnedIDs.count222        while pinnedCount > 0, used(pinnedCount: pinnedCount, tabCount: 0, tabWidth: 0) > available { pinnedCount -= 1 }223        var tabCount = 0224        if pinnedCount == pinnedIDs.count {225            while tabCount < others.count,226                  used(pinnedCount: pinnedCount, tabCount: tabCount + 1, tabWidth: metrics.minimumTabWidth) <= available {227                tabCount += 1228            }229        }230        var visiblePinned = Array(pinnedIDs.prefix(pinnedCount))231        var hiddenPinned = Array(pinnedIDs.dropFirst(pinnedCount))232        var visibleOthers = Array(others.prefix(tabCount))233        var hiddenOthers = Array(others.dropFirst(tabCount))234235        if let selected {236            if let index = hiddenOthers.firstIndex(of: selected), let last = visibleOthers.popLast() {237                hiddenOthers.remove(at: index)238                visibleOthers.append(selected)239                hiddenOthers.insert(last, at: 0)240            } else if let index = hiddenPinned.firstIndex(of: selected), let last = visiblePinned.popLast() {241                hiddenPinned.remove(at: index)242                visiblePinned.append(selected)243                hiddenPinned.insert(last, at: 0)244            }245        }246        var tabWidth = metrics.minimumTabWidth247        if !visibleOthers.isEmpty {248            let fixed = used(pinnedCount: visiblePinned.count, tabCount: visibleOthers.count, tabWidth: 0)249            tabWidth = min(metrics.maximumTabWidth, max(metrics.minimumTabWidth, (available - fixed) / Double(visibleOthers.count)))250        }251        return TabStripLayout(visible: visiblePinned + visibleOthers, overflow: hiddenPinned + hiddenOthers,252                              tabWidth: tabWidth, pinnedWidth: metrics.pinnedWidth)253    }254255    // MARK: Grid256257    /// Thumbnail frames for `count` tabs in a container of `size`: as many columns as fit `minimumCellWidth`,258    /// cells keep `aspectRatio` (width / height). The content can be taller than the container (it scrolls).259    public static func gridFrames(count: Int, in size: CGSize, minimumCellWidth: Double = 220, aspectRatio: Double = 1.5,260                                  spacing: Double = 16) -> [CGRect] {261        guard count > 0, size.width > 0, aspectRatio > 0 else { return [] }262        let columns = max(1, min(count, Int((size.width + spacing) / (minimumCellWidth + spacing))))263        let cellWidth = (size.width - spacing * Double(columns - 1)) / Double(columns)264        let cellHeight = cellWidth / aspectRatio265        return (0..<count).map { index in266            CGRect(x: Double(index % columns) * (cellWidth + spacing), y: Double(index / columns) * (cellHeight + spacing),267                   width: cellWidth, height: cellHeight)268        }269    }270271    // MARK: Orbit272273    /// Tabs as satellites: pinned tabs evenly on ring 0, the others evenly on the following rings, each ring274    /// filled to its capacity before the next one. Tabs beyond the total capacity get no slot (the caller275    /// shows them in the list).276    public static func orbitSlots(order: [TabID], pinned: Set<TabID>, metrics: OrbitalMetrics = .standard) -> [TabID: OrbitSlot] {277        var result: [TabID: OrbitSlot] = [:]278        let pinnedIDs = order.filter(pinned.contains)279        let others = order.filter { !pinned.contains($0) }280        var ring = 0281        func place(_ ids: [TabID]) {282            var remaining = ids[...]283            while !remaining.isEmpty, ring <= metrics.maximumRing {284                let onRing = remaining.prefix(metrics.capacity(ofRing: ring))285                for (index, id) in onRing.enumerated() {286                    result[id] = OrbitSlot(ring: ring, angle: -.pi / 2 + 2 * .pi * Double(index) / Double(onRing.count))287                }288                remaining = remaining.dropFirst(onRing.count)289                ring += 1290            }291        }292        place(pinnedIDs)293        place(others)294        return result295    }296297    // MARK: Presentation298299    /// Everything a window needs to draw its tabs in `mode`.300    public static func presentation(mode: TabLayoutMode, tabs: [Tab], groups: [TabGroup], selected: TabID?,301                                    size: CGSize, collapsedTrees: Set<TabID> = [],302                                    stripMetrics: TabStripMetrics = TabStripMetrics(),303                                    orbitalMetrics: OrbitalMetrics = .standard) -> TabPresentation {304        let pinned = Set(tabs.filter(\.isPinned).map(\.id))305        switch mode {306        case .vertical:307            return .vertical(sections: sections(tabs: tabs, groups: groups, selected: selected, collapsedTrees: collapsedTrees))308        case .horizontal:309            // The strip is flat: tree indentation has no meaning there, so no subtree is ever collapsed.310            let all = sections(tabs: tabs, groups: groups, selected: selected)311            let order = all.flatMap { $0.rows.map(\.tab.id) }312            return .horizontal(strip: strip(order: order, pinned: pinned, selected: selected, width: size.width,313                                            metrics: stripMetrics), sections: all)314        case .compact:315            let open = ordered(tabs)316            let current = selected.flatMap { id in open.contains { $0.id == id } ? id : nil } ?? mostRecentlyUsed(open).first?.id317            return .compact(current: current, switcher: mostRecentlyUsed(open).map(\.id), count: open.count)318        case .grid:319            let order = ordered(tabs).map(\.id)320            return .grid(order: order, frames: gridFrames(count: order.count, in: size))321        case .orbit:322            let order = ordered(tabs).map(\.id)323            return .orbit(slots: orbitSlots(order: order, pinned: pinned, metrics: orbitalMetrics), order: order)324        }325    }326}327
Files main
Menu

Theme