Sources/OrgstarMobile/MobileEditorStore.swift
53 lines · 2362 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 editor of `path`, when a pane shows it.
25 func existing(_ path: String) -> MobileEditor? { editors[path] }
26
27 /// The text view `pane` shows `editor` in: one no other pane owns, else a new one.
28 func view(for pane: PaneID, of editor: MobileEditor) -> UITextView {
29 if let owned = editor.textViews.first(where: { owners[ObjectIdentifier($0)] == pane }) { return owned }
30 let view = editor.textViews.first { owners[ObjectIdentifier($0)] == nil } ?? editor.addView()
31 owners[ObjectIdentifier(view)] = pane
32 return view
33 }
34
35 /// `pane` no longer shows `path`: its view goes, or is left free when it's the editor's
36 /// first, which stays with the editor.
37 func release(_ pane: PaneID, path: String) {
38 guard let editor = editors[path] else { return }
39 for view in editor.textViews where owners[ObjectIdentifier(view)] == pane {
40 owners[ObjectIdentifier(view)] = nil
41 editor.removeView(view)
42 }
43 }
44
45 /// The editors of files the session no longer has open go.
46 func prune(_ session: DocumentSession) {
47 for (path, editor) in editors where !session.isAttached(editor, for: path) {
48 for view in editor.textViews { owners[ObjectIdentifier(view)] = nil }
49 editors[path] = nil
50 }
51 }
52}
53#endif