Sources/Orgstar/WindowModel.swift

73 lines · 2562 bytes

 1import Foundation
 2import OrgApp
 3
 4/// One editor window's panes: how they divide the window and which has focus. The panes
 5/// themselves belong to the session, which keeps them in step with the buffers.
 6@MainActor
 7@Observable
 8final class WindowModel: Identifiable {
 9    let id = UUID()
10    let session: DocumentSession
11    private(set) var layout: PaneLayout
12    private(set) var panes: [PaneID: EditorPane]
13    var focused: PaneID
14
15    /// A window around `pane`, which the session already has.
16    init(session: DocumentSession, pane: EditorPane) {
17        self.session = session
18        layout = .pane(pane.id)
19        panes = [pane.id: pane]
20        focused = pane.id
21    }
22
23    func pane(_ id: PaneID) -> EditorPane? { panes[id] }
24    var focusedPane: EditorPane { panes[focused] ?? panes[layout.panes[0]] ?? panes.values.first ?? session.focused }
25    var paneCount: Int { layout.panes.count }
26
27    /// A new pane after the focused one, showing the same buffer, as `split-window` does. The
28    /// focus stays where it was.
29    @discardableResult
30    func split(_ axis: PaneLayout.Axis) -> EditorPane {
31        let current = focusedPane
32        let pane = session.makePane()
33        panes[pane.id] = pane
34        layout = layout.splitting(current.id, axis: axis, new: pane.id)
35        if let path = current.path { session.open(path, in: pane) }
36        return pane
37    }
38
39    /// Removes `id` from the window; its buffers stay open. The only pane stays.
40    func close(_ id: PaneID) {
41        guard let pane = panes[id], let rest = layout.removing(id) else { return }
42        layout = rest
43        panes[id] = nil
44        session.closePane(pane)
45        if focused == id { focus(rest.panes[0]) }
46    }
47
48    /// Removes every pane but the focused one.
49    func closeOthers() {
50        for id in layout.panes where id != focused { close(id) }
51    }
52
53    /// Focuses the pane after the focused one in reading order, wrapping.
54    func focusNext() {
55        focus(layout.next(after: focused))
56    }
57
58    func focus(_ id: PaneID) {
59        guard let pane = panes[id] else { return }
60        focused = id
61        session.focused = pane
62    }
63
64    func setFraction(_ fraction: Double, ofSplitBetween before: PaneID, and after: PaneID) {
65        layout = layout.settingFraction(fraction, ofSplitBetween: before, and: after)
66    }
67
68    /// Takes every pane out of the session, as the window closes. The panes stay listed here
69    /// so views still on screen can read them.
70    func closeAll() {
71        for pane in panes.values { session.closePane(pane) }
72    }
73}