Sources/OrgstarMobile/MobileEditorStore.swift

design-themes-widgets
orgstar/Sources/OrgstarMobile/MobileEditorStore.swift history · blame · raw

50 lines · 2240 bytes

 1#if os(iOS)
 2import OrgApp
 3import UIKit
 4
 5/// The editors of the open buffers and the text views the panes show them in, across every
 6/// scene: one `MobileEditor` per file, one text view per pane that shows it.
 7@MainActor
 8final class MobileEditorStore {
 9    private var editors: [String: MobileEditor] = [:]
10    /// The pane each text view belongs to.
11    private var owners: [ObjectIdentifier: PaneID] = [:]
12
13    /// The editor of `path`, made with `make` when there's none or the session's buffer for the
14    /// file is no longer it (the file was closed and opened again).
15    func editor(for path: String, session: DocumentSession, make: () -> MobileEditor?) -> MobileEditor? {
16        if let editor = editors[path], session.isAttached(editor, for: path) { return editor }
17        if let old = editors[path] { for view in old.textViews { owners[ObjectIdentifier(view)] = nil } }
18        guard let made = make() else { return nil }
19        editors[path] = made
20        session.attach(made, for: path)
21        return made
22    }
23
24    /// The text view `pane` shows `editor` in: one no other pane owns, else a new one.
25    func view(for pane: PaneID, of editor: MobileEditor) -> UITextView {
26        if let owned = editor.textViews.first(where: { owners[ObjectIdentifier($0)] == pane }) { return owned }
27        let view = editor.textViews.first { owners[ObjectIdentifier($0)] == nil } ?? editor.addView()
28        owners[ObjectIdentifier(view)] = pane
29        return view
30    }
31
32    /// `pane` no longer shows `path`: its view goes, or is left free when it's the editor's
33    /// first, which stays with the editor.
34    func release(_ pane: PaneID, path: String) {
35        guard let editor = editors[path] else { return }
36        for view in editor.textViews where owners[ObjectIdentifier(view)] == pane {
37            owners[ObjectIdentifier(view)] = nil
38            editor.removeView(view)
39        }
40    }
41
42    /// The editors of files the session no longer has open go.
43    func prune(_ session: DocumentSession) {
44        for (path, editor) in editors where !session.isAttached(editor, for: path) {
45            for view in editor.textViews { owners[ObjectIdentifier(view)] = nil }
46            editors[path] = nil
47        }
48    }
49}
50#endif