SPB Git

Repository Public License

OrbitService.swift 29.2 KB 626 lines swift

1import CoreGraphics2import Foundation3import NavigatorCore4import Persistence56public enum OrbitError: Error, Sendable, Equatable {7    /// The name is empty once trimmed.8    case invalidName9    case profileNotFound10    case spaceNotFound11    case windowNotFound12    case tabNotFound13    case groupNotFound14    /// The last profile cannot be deleted.15    case lastProfile16    /// A profile keeps at least one space that is not archived.17    case lastSpace18    /// Every ring of the orbital view is full (`OrbitalLayout.totalCapacity`).19    case orbitFull20    /// The tab and the group (or the tabs of a group) are not in the same space.21    case differentSpaces22    /// The target is a private (ghost) profile, space, window or tab: those live in memory in their23    /// `GhostSession` and are never handled by this service.24    case ghostNotPersisted25    case nothingToReopen26}2728public struct OrbitBootstrap: Sendable, Equatable {29    public var profile: Profile30    public var space: OrbitSpace31    public var createdProfile: Bool32    public var createdSpace: Bool33}3435public struct ProfileDeletion: Sendable {36    /// Rows deleted and archive files to remove.37    public var report: DeletionReport38    /// The WebKit data store of the profile, which the web layer must remove (`WKWebsiteDataStore.remove(forIdentifier:)`).39    public var dataStoreIdentifier: UUID40}4142public struct TabCloseResult: Sendable, Equatable {43    /// The window after the close: selection and split updated.44    public var window: BrowserWindow45    /// `true` when the window has no open tab left: the UI closes it or opens a new tab, per platform habit.46    public var windowIsEmpty: Bool47}4849public struct TabMoveResult: Sendable, Equatable {50    public var tab: Tab51    /// The tab crossed a profile boundary: its WebKit session state was dropped, the page reloads from its URL52    /// in the other profile's data store.53    public var crossedProfile: Bool54    /// A window was created in the target space because it had none open.55    public var createdWindow: BrowserWindow?56}5758/// Workspaces, profiles and tab organisation on top of the stores. One instance per database.59///60/// The service owns the rules (what a pinned tab is, where a new space goes, what happens to a split when a tab61/// leaves) and writes through `NavigatorDatabase`; it holds no state of its own, so a UI model refreshes from62/// the values each call returns.63public actor OrbitService {64    private let database: NavigatorDatabase65    private let now: @Sendable () -> Date66    private let metrics: OrbitalMetrics6768    public init(database: NavigatorDatabase, metrics: OrbitalMetrics = .standard,69                now: @escaping @Sendable () -> Date = { .now }) {70        self.database = database71        self.metrics = metrics72        self.now = now73    }7475    private func rejectGhost(_ raw: UUID) throws {76        if database.ghosts.contains(raw) { throw OrbitError.ghostNotPersisted }77    }7879    private func name(_ text: String) throws -> String {80        guard let cleaned = TabOperations.cleanedName(text) else { throw OrbitError.invalidName }81        return cleaned82    }8384    // MARK: - First launch8586    /// Makes sure a default profile and a first space exist. Idempotent: call at every launch.87    /// The names come from the caller so they can be localised.88    public func bootstrap(profileName: String = "Personal", spaceName: String = "Home") async throws -> OrbitBootstrap {89        let profiles = try await database.profiles.all()90        if let profile = profiles.first {91            let spaces = OrbitalLayout.listOrder(try await database.spaces.spaces(profile: profile.id))92            if let space = spaces.first {93                return OrbitBootstrap(profile: profile, space: space, createdProfile: false, createdSpace: false)94            }95            let space = try await createSpace(profile: profile.id, name: spaceName)96            return OrbitBootstrap(profile: profile, space: space, createdProfile: false, createdSpace: true)97        }98        let profile = Profile(name: try name(profileName), createdAt: now())99        try await database.profiles.save(profile)100        let space = try await createSpace(profile: profile.id, name: spaceName)101        return OrbitBootstrap(profile: profile, space: space, createdProfile: true, createdSpace: true)102    }103104    // MARK: - Profiles105106    public func profiles() async throws -> [Profile] { try await database.profiles.all() }107108    /// Creates a profile (its own WebKit data store identifier) with a first space.109    @discardableResult110    public func createProfile(name: String, tint: SpaceTint = .lunarBlue, firstSpaceName: String = "Home") async throws111        -> (profile: Profile, space: OrbitSpace) {112        let profile = Profile(name: try self.name(name), tint: tint, createdAt: now())113        try await database.profiles.save(profile)114        let space = try await createSpace(profile: profile.id, name: firstSpaceName, tint: tint)115        return (profile, space)116    }117118    private func profile(_ id: ProfileID) async throws -> Profile {119        try rejectGhost(id.raw)120        guard let profile = try await database.profiles.profile(id) else { throw OrbitError.profileNotFound }121        return profile122    }123124    @discardableResult125    public func renameProfile(_ id: ProfileID, to name: String) async throws -> Profile {126        var profile = try await profile(id)127        profile.name = try self.name(name)128        try await database.profiles.save(profile)129        return profile130    }131132    @discardableResult133    public func recolourProfile(_ id: ProfileID, tint: SpaceTint) async throws -> Profile {134        var profile = try await profile(id)135        profile.tint = tint136        try await database.profiles.save(profile)137        return profile138    }139140    /// Deletes a profile with its spaces, windows, tabs, history, bookmarks, downloads list and permissions.141    /// The last profile cannot be deleted. The caller removes the WebKit data store and the archive files.142    public func deleteProfile(_ id: ProfileID) async throws -> ProfileDeletion {143        let profile = try await profile(id)144        guard try await database.profiles.all().count > 1 else { throw OrbitError.lastProfile }145        let report = try await database.lifecycle.deleteProfile(id)146        return ProfileDeletion(report: report, dataStoreIdentifier: profile.dataStoreIdentifier)147    }148149    // MARK: - Spaces150151    public func spaces(profile: ProfileID? = nil, includeArchived: Bool = false) async throws -> [OrbitSpace] {152        try await database.spaces.spaces(profile: profile, includeArchived: includeArchived)153    }154155    private func space(_ id: SpaceID) async throws -> OrbitSpace {156        try rejectGhost(id.raw)157        guard let space = try await database.spaces.space(id) else { throw OrbitError.spaceNotFound }158        return space159    }160161    /// Creates a space at the end of the profile's list and at a free position of the orbital view (innermost162    /// ring with room, middle of its widest gap).163    @discardableResult164    public func createSpace(profile: ProfileID, name: String, symbol: String = "circle.hexagongrid",165                            tint: SpaceTint = .lunarBlue) async throws -> OrbitSpace {166        _ = try await self.profile(profile)167        let existing = try await database.spaces.spaces(profile: profile)168        // The orbital view shows one profile at a time: only its own spaces compete for positions.169        guard let slot = OrbitalLayout.placement(forNewSpaceAmong: existing, metrics: metrics) else { throw OrbitError.orbitFull }170        let date = now()171        let space = OrbitSpace(profileID: profile, name: try self.name(name), symbol: symbol, tint: tint,172                               order: (existing.map(\.order).max() ?? -1) + 1, ring: slot.ring, angle: slot.angle,173                               createdAt: date, updatedAt: date)174        try await database.spaces.save(space)175        return space176    }177178    private func update(_ id: SpaceID, _ change: (inout OrbitSpace) throws -> Void) async throws -> OrbitSpace {179        var space = try await space(id)180        try change(&space)181        space.updatedAt = now()182        try await database.spaces.save(space)183        return space184    }185186    @discardableResult187    public func renameSpace(_ id: SpaceID, to name: String) async throws -> OrbitSpace {188        let cleaned = try self.name(name)189        return try await update(id) { $0.name = cleaned }190    }191192    @discardableResult193    public func recolourSpace(_ id: SpaceID, tint: SpaceTint) async throws -> OrbitSpace {194        try await update(id) { $0.tint = tint }195    }196197    @discardableResult198    public func setSymbol(_ symbol: String, forSpace id: SpaceID) async throws -> OrbitSpace {199        let trimmed = symbol.trimmingCharacters(in: .whitespacesAndNewlines)200        guard !trimmed.isEmpty else { throw OrbitError.invalidName }201        return try await update(id) { $0.symbol = trimmed }202    }203204    /// Sets the order of the list (sidebar, accessible list, grid). Spaces not listed keep their position value.205    public func reorderSpaces(_ ids: [SpaceID]) async throws {206        for id in ids { try rejectGhost(id.raw) }207        try await database.spaces.reorder(ids)208    }209210    /// Moves a satellite to a ring and an angle (the result of `OrbitalLayout.drop`).211    @discardableResult212    public func moveSpace(_ id: SpaceID, to slot: OrbitSlot) async throws -> OrbitSpace {213        try await update(id) { $0.ring = min(slot.ring, metrics.maximumRing); $0.angle = slot.angle }214    }215216    /// Drops the satellite at a screen point: computes the landing slot and stores it.217    @discardableResult218    public func dropSpace(_ id: SpaceID, at point: CGPoint, viewport: OrbitalViewport) async throws219        -> (space: OrbitSpace, result: OrbitDragResult) {220        let current = try await space(id)221        let siblings = try await database.spaces.spaces(profile: current.profileID)222        let result = OrbitalLayout.drop(id, at: point, spaces: siblings, metrics: metrics, viewport: viewport)223        return (try await moveSpace(id, to: result.slot), result)224    }225226    /// Rearranges all the non-archived spaces of a profile evenly, in list order ("tidy up").227    @discardableResult228    public func tidySpaces(profile: ProfileID) async throws -> [OrbitSpace] {229        let ordered = OrbitalLayout.listOrder(try await database.spaces.spaces(profile: profile))230        let slots = OrbitalLayout.evenSlots(count: ordered.count, metrics: metrics)231        var result: [OrbitSpace] = []232        for (space, slot) in zip(ordered, slots) {233            result.append(try await moveSpace(space.id, to: slot))234        }235        return result236    }237238    /// Archives a space: it leaves the orbital view and the lists; its windows and tabs stay stored and come239    /// back with `unarchiveSpace`. A profile keeps at least one active space.240    public func archiveSpace(_ id: SpaceID) async throws {241        let space = try await space(id)242        guard !space.isArchived else { return }243        let active = try await database.spaces.spaces(profile: space.profileID, includeArchived: false)244        guard active.contains(where: { $0.id != id }) else { throw OrbitError.lastSpace }245        try await database.spaces.setArchived(id, true, at: now())246    }247248    /// Brings an archived space back, at a free position if its old one was taken meanwhile.249    @discardableResult250    public func unarchiveSpace(_ id: SpaceID) async throws -> OrbitSpace {251        var space = try await space(id)252        guard space.isArchived else { return space }253        let others = try await database.spaces.spaces(profile: space.profileID, includeArchived: false)254        space.isArchived = false255        if !OrbitalLayout.overlaps(in: others + [space], metrics: metrics).isEmpty {256            guard let slot = OrbitalLayout.placement(forNewSpaceAmong: others, metrics: metrics) else { throw OrbitError.orbitFull }257            space.ring = slot.ring258            space.angle = slot.angle259        }260        space.updatedAt = now()261        try await database.spaces.save(space)262        return space263    }264265    /// Deletes a space with its windows, tabs and groups. Notes, canvases and agent runs linked to it are kept,266    /// unlinked. A profile keeps at least one active space.267    public func deleteSpace(_ id: SpaceID) async throws {268        let space = try await space(id)269        let active = try await database.spaces.spaces(profile: space.profileID, includeArchived: false)270        guard space.isArchived || active.contains(where: { $0.id != id }) else { throw OrbitError.lastSpace }271        try await database.spaces.delete(id)272    }273274    // MARK: - Windows275276    private func window(_ id: WindowID) async throws -> BrowserWindow {277        try rejectGhost(id.raw)278        guard let window = try await database.windows.window(id) else { throw OrbitError.windowNotFound }279        return window280    }281282    /// Opens a window in a space, after the existing ones.283    @discardableResult284    public func openWindow(space: SpaceID, tabLayout: TabLayoutMode = .vertical, frame: WindowFrame? = nil) async throws -> BrowserWindow {285        _ = try await self.space(space)286        let order = (try await database.windows.openWindows().map(\.order).max() ?? -1) + 1287        let window = BrowserWindow(spaceID: space, frame: frame, tabLayout: tabLayout, order: order)288        try await database.windows.save(window)289        return window290    }291292    /// Closes a window, keeping it and its tabs for "reopen closed window".293    public func closeWindow(_ id: WindowID) async throws {294        _ = try await window(id)295        try await database.windows.close(id, at: now())296    }297298    /// Reopens a closed window (the most recently closed one by default) with its tabs, all dormant.299    public func reopenClosedWindow(_ id: WindowID? = nil) async throws -> ClosedWindow {300        let target: WindowID301        if let id { target = id } else {302            guard let latest = try await database.windows.recentlyClosed(limit: 1).first else { throw OrbitError.nothingToReopen }303            target = latest.window.id304        }305        do { return try await database.windows.reopen(target) } catch PersistenceError.notFound {306            throw OrbitError.windowNotFound307        }308    }309310    /// Moves a whole window to another space: its tabs follow and leave their groups (a group belongs to one311    /// space). Tabs that cross a profile boundary lose their WebKit session state.312    @discardableResult313    public func moveWindow(_ id: WindowID, toSpace target: SpaceID) async throws -> BrowserWindow {314        var window = try await window(id)315        let destination = try await space(target)316        guard window.spaceID != target else { return window }317        let origin = try await space(window.spaceID)318        let crossesProfile = origin.profileID != destination.profileID319        window.spaceID = target320        var tabs = try await database.tabs.tabs(window: id)321        for index in tabs.indices {322            tabs[index].spaceID = target323            tabs[index].groupID = nil324            if crossesProfile { tabs[index].sessionState = nil; tabs[index].lifecycle = .dormant }325        }326        // One transaction: the window and its tabs change space together.327        try await database.session.apply([.saveWindow(window)] + tabs.map { .saveTab($0) })328        return window329    }330331    // MARK: - Tabs332333    private func tab(_ id: TabID) async throws -> Tab {334        guard let tab = try await database.tabs.tab(id), tab.closedAt == nil else { throw OrbitError.tabNotFound }335        return tab336    }337338    /// Opens a tab in a window. `parent` records which tab opened it (tree layout); with `.after(parent)` it339    /// is placed after the parent's existing children.340    @discardableResult341    public func openTab(in windowID: WindowID, url: URL?, title: String = "", parent: TabID? = nil,342                        position: TabOperations.NewTabPosition = .end, select: Bool = true,343                        lifecycle: TabLifecycle = .live) async throws -> Tab {344        var window = try await window(windowID)345        let existing = try await database.tabs.tabs(window: windowID)346        let date = now()347        var tab = Tab(windowID: windowID, spaceID: window.spaceID, parentID: parent, url: url, title: title,348                      lifecycle: lifecycle, createdAt: date, lastActiveAt: date)349        // A child opens in its parent's group, like the page that opened it.350        if let parent, let parentTab = existing.first(where: { $0.id == parent }), !parentTab.isPinned {351            tab.groupID = parentTab.groupID352        } else if let parent, existing.first(where: { $0.id == parent })?.isPinned == true {353            tab.parentID = nil354        }355        let unpinned = existing.filter { !$0.isPinned }356        let index = TabOperations.insertionIndex(for: position, in: unpinned)357        var order = unpinned.map(\.id)358        order.insert(tab.id, at: index)359        tab.order = index360        var changes: [SessionChange] = [.saveTab(tab), .reorderTabs(window: windowID, ids: order)]361        if select {362            window.selectedTabID = tab.id363            changes.append(.selectTab(window: windowID, tab: tab.id))364        }365        try await database.session.apply(changes)366        return tab367    }368369    /// Duplicates a tab right after the original. The copy is dormant: the UI loads it when shown.370    @discardableResult371    public func duplicateTab(_ id: TabID) async throws -> Tab {372        let original = try await tab(id)373        try rejectGhost(original.windowID.raw)374        var copy = TabOperations.duplicate(original, now: now())375        let unpinned = try await database.tabs.tabs(window: original.windowID).filter { !$0.isPinned }376        var order = unpinned.map(\.id)377        // After the original, or first among the unpinned tabs when the original is pinned.378        let index = order.firstIndex(of: id).map { $0 + 1 } ?? 0379        order.insert(copy.id, at: index)380        copy.order = index381        try await database.session.apply([.saveTab(copy), .reorderTabs(window: original.windowID, ids: order)])382        return copy383    }384385    /// Pins or unpins a tab. A pinned tab leaves its group and its place in the tree: pinned tabs are a flat386    /// row of favourites at the start of the window. It is appended after the existing pinned tabs; an387    /// unpinned tab goes to the start of the unpinned ones.388    @discardableResult389    public func setPinned(_ id: TabID, _ pinned: Bool) async throws -> Tab {390        var tab = try await tab(id)391        guard tab.isPinned != pinned else { return tab }392        let siblings = try await database.tabs.tabs(window: tab.windowID).filter { $0.id != id }393        tab.isPinned = pinned394        if pinned { tab.groupID = nil; tab.parentID = nil }395        var changes: [SessionChange] = []396        if pinned {397            tab.order = (siblings.filter(\.isPinned).map(\.order).max() ?? -1) + 1398            changes.append(.saveTab(tab))399        } else {400            tab.order = 0401            changes.append(.saveTab(tab))402            changes.append(.reorderTabs(window: tab.windowID, ids: [id] + siblings.filter { !$0.isPinned }.map(\.id)))403        }404        try await database.session.apply(changes)405        return tab406    }407408    /// Sets the display order of the tabs of a window (pinned and unpinned tabs are ordered separately by409    /// storage: pinned always come first).410    public func reorderTabs(window: WindowID, _ ids: [TabID]) async throws {411        try rejectGhost(window.raw)412        try await database.tabs.reorder(window: window, ids)413    }414415    /// Moves a tab to a position in a window (its own or another one, possibly in another space).416    ///417    /// Leaving its space, the tab leaves its group. Leaving its profile, it also loses its WebKit session418    /// state: back/forward history and form state of one profile never enter another. The tab is removed from419    /// the split of the window it leaves.420    @discardableResult421    public func moveTab(_ id: TabID, toWindow target: WindowID, index: Int? = nil) async throws -> TabMoveResult {422        var tab = try await tab(id)423        let destination = try await window(target)424        let source = try await window(tab.windowID)425        var crossedProfile = false426        if source.spaceID != destination.spaceID {427            let from = try await space(source.spaceID), to = try await space(destination.spaceID)428            crossedProfile = from.profileID != to.profileID429        }430        let targetTabs = try await database.tabs.tabs(window: target).filter { $0.isPinned == tab.isPinned }431        let order = TabOperations.inserting(id, into: targetTabs.map(\.id), at: index)432433        var changes: [SessionChange] = []434        if source.id != target {435            changes.append(contentsOf: try await detach(tab, from: source))436            tab.windowID = target437            tab.spaceID = destination.spaceID438            if source.spaceID != destination.spaceID { tab.groupID = nil }439            // The parent stays behind in the other window.440            tab.parentID = nil441            if crossedProfile { tab.sessionState = nil; tab.lifecycle = .dormant }442        }443        changes.append(.saveTab(tab))444        changes.append(.reorderTabs(window: target, ids: order))445        try await database.session.apply(changes)446        tab.order = order.firstIndex(of: id) ?? tab.order447        return TabMoveResult(tab: tab, crossedProfile: crossedProfile, createdWindow: nil)448    }449450    /// Moves a tab to another space: into that space's first open window, or a new window when it has none.451    @discardableResult452    public func moveTab(_ id: TabID, toSpace target: SpaceID) async throws -> TabMoveResult {453        _ = try await space(target)454        if let existing = try await database.windows.openWindows(space: target).first {455            return try await moveTab(id, toWindow: existing.id)456        }457        let created = try await openWindow(space: target)458        var result = try await moveTab(id, toWindow: created.id)459        try await database.session.apply([.selectTab(window: created.id, tab: id)])460        result.createdWindow = try await window(created.id)461        return result462    }463464    /// Changes to apply to the window a tab leaves (closed or moved away): selection, split, and the children465    /// of the tab, which are attached to its parent so the tree stays connected.466    private func detach(_ tab: Tab, from window: BrowserWindow) async throws -> [SessionChange] {467        var changes: [SessionChange] = []468        var window = window469        let siblings = try await database.tabs.tabs(window: window.id)470        let order = siblings.map(\.id)471        var windowChanged = false472        if let split = window.split, split.panes.contains(tab.id) {473            window.split = SplitEngine.removing(tab.id, from: split)474            if let remaining = window.split { window.selectedTabID = SplitEngine.focusedTab(of: remaining) }475            windowChanged = true476        }477        let selection = TabOperations.selectionAfterClosing(tab.id, selected: window.selectedTabID, order: order)478        if selection != window.selectedTabID {479            window.selectedTabID = selection480            windowChanged = true481        }482        if windowChanged { changes.append(.saveWindow(window)) }483        for var child in siblings where child.parentID == tab.id {484            child.parentID = tab.parentID485            changes.append(.saveTab(child))486        }487        return changes488    }489490    /// Closes a tab, keeping it for "reopen closed tab". Returns the window with its new selection.491    @discardableResult492    public func closeTab(_ id: TabID) async throws -> TabCloseResult {493        let tab = try await tab(id)494        let window = try await window(tab.windowID)495        var changes = try await detach(tab, from: window)496        changes.append(.closeTab(id: id, at: now()))497        try await database.session.apply(changes)498        let after = try await self.window(tab.windowID)499        let remaining = try await database.tabs.tabs(window: tab.windowID)500        return TabCloseResult(window: after, windowIsEmpty: remaining.isEmpty)501    }502503    /// Recently closed tabs (most recent first) and windows.504    public func recentlyClosed(space: SpaceID? = nil, limit: Int = 25) async throws -> (tabs: [Tab], windows: [ClosedWindow]) {505        (try await database.tabs.recentlyClosed(space: space, limit: limit),506         try await database.windows.recentlyClosed(limit: min(limit, 10)))507    }508509    /// Reopens a closed tab — the most recently closed one of the space by default — in its original window510    /// when that window is still open, else in `window`, else in the first open window of its space, else in511    /// a new window. The tab comes back dormant with its history.512    @discardableResult513    public func reopenClosedTab(_ id: TabID? = nil, space: SpaceID? = nil, into window: WindowID? = nil) async throws -> Tab {514        let closed: Tab515        if let id {516            guard let stored = try await database.tabs.tab(id), stored.closedAt != nil else { throw OrbitError.nothingToReopen }517            closed = stored518        } else {519            guard let latest = try await database.tabs.recentlyClosed(space: space, limit: 1).first else {520                throw OrbitError.nothingToReopen521            }522            closed = latest523        }524        var target = window525        if target == nil {526            let original = try await database.windows.window(closed.windowID)527            if original == nil || original?.closedAt != nil {528                if let open = try await database.windows.openWindows(space: closed.spaceID).first {529                    target = open.id530                } else {531                    target = try await openWindow(space: closed.spaceID).id532                }533            }534        }535        return try await database.tabs.reopen(closed.id, into: target)536    }537538    // MARK: - Tab groups539540    private func group(_ id: TabGroupID) async throws -> TabGroup {541        guard let group = try await database.tabGroups.group(id) else { throw OrbitError.groupNotFound }542        return group543    }544545    /// Creates a group in a space and puts `tabs` in it. Pinned tabs and tabs of another space are refused.546    @discardableResult547    public func createGroup(space: SpaceID, name: String, tint: SpaceTint = .spectralViolet,548                            tabs: [TabID] = []) async throws -> TabGroup {549        _ = try await self.space(space)550        let order = (try await database.tabGroups.groups(space: space).map(\.order).max() ?? -1) + 1551        let group = TabGroup(spaceID: space, name: try self.name(name), tint: tint, order: order)552        var changes: [SessionChange] = [.saveGroup(group)]553        changes.append(contentsOf: try await membership(of: tabs, in: group))554        try await database.session.apply(changes)555        return group556    }557558    private func membership(of tabs: [TabID], in group: TabGroup) async throws -> [SessionChange] {559        var changes: [SessionChange] = []560        for id in tabs {561            var tab = try await tab(id)562            guard tab.spaceID == group.spaceID, !tab.isPinned else { throw OrbitError.differentSpaces }563            tab.groupID = group.id564            changes.append(.saveTab(tab))565        }566        return changes567    }568569    private func update(_ id: TabGroupID, _ change: (inout TabGroup) -> Void) async throws -> TabGroup {570        var group = try await group(id)571        change(&group)572        try await database.tabGroups.save(group)573        return group574    }575576    @discardableResult577    public func renameGroup(_ id: TabGroupID, to name: String) async throws -> TabGroup {578        let cleaned = try self.name(name)579        return try await update(id) { $0.name = cleaned }580    }581582    @discardableResult583    public func recolourGroup(_ id: TabGroupID, tint: SpaceTint) async throws -> TabGroup {584        try await update(id) { $0.tint = tint }585    }586587    @discardableResult588    public func setGroupCollapsed(_ id: TabGroupID, _ collapsed: Bool) async throws -> TabGroup {589        try await update(id) { $0.isCollapsed = collapsed }590    }591592    public func reorderGroups(_ ids: [TabGroupID]) async throws { try await database.tabGroups.reorder(ids) }593594    /// Adds tabs to a group (they must be unpinned tabs of the group's space).595    public func addTabs(_ tabs: [TabID], toGroup id: TabGroupID) async throws {596        let group = try await group(id)597        try await database.session.apply(try await membership(of: tabs, in: group))598    }599600    /// Takes tabs out of their group; they stay open.601    public func ungroupTabs(_ tabs: [TabID]) async throws {602        for id in tabs { try await database.tabs.setGroup(id, nil) }603    }604605    /// Deletes a group. Its tabs stay open and ungrouped, or are closed (kept as recently closed) with606    /// `closingTabs`.607    public func deleteGroup(_ id: TabGroupID, closingTabs: Bool = false) async throws {608        _ = try await group(id)609        if closingTabs {610            for tab in try await database.tabs.tabs(group: id) { try await closeTab(tab.id) }611        }612        try await database.tabGroups.delete(id)613    }614615    // MARK: - Search616617    /// Fuzzy search across the spaces of a profile (all profiles when `nil`) and their open tabs.618    public func search(_ query: String, profile: ProfileID? = nil, includeArchived: Bool = false,619                       limit: Int = 50) async throws -> [OrbitSearchResult] {620        let spaces = try await database.spaces.spaces(profile: profile, includeArchived: includeArchived)621        var tabs: [Tab] = []622        for space in spaces { tabs.append(contentsOf: try await database.tabs.tabs(space: space.id)) }623        return OrbitSearch.search(query, spaces: spaces, tabs: tabs, limit: limit)624    }625}626
Files main
Menu

Theme