Sources/OrgstarMobile/KeyBar.swift

d88176172f98786bd9a86c2f6ee051fd19fe426d
orgstar/Sources/OrgstarMobile/KeyBar.swift

271 lines · 13385 bytes

  1#if os(iOS)
  2import OrgApp
  3import OrgCore
  4import SwiftUI
  5
  6/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
  7/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column), or
  8/// runs a command. The buttons are `[key-bar]` in config.toml, or the default; they share the
  9/// width without scrolling, and those that don't fit go under More.
 10struct KeyBar: View {
 11    let editor: MobileEditor
 12    let palette: () -> Void
 13    @Environment(\.horizontalSizeClass) private var sizeClass
 14    @AppStorage(KeyBarLayout.Width.iphone.defaultsKey) private var iphone: String?
 15    @AppStorage(KeyBarLayout.Width.ipad.defaultsKey) private var ipad: String?
 16    @State private var width: CGFloat?
 17
 18    /// A button the bar can hold.
 19    struct Item {
 20        enum Action {
 21            /// What the keys are bound to at the caret.
 22            case keys(String)
 23            case command(String)
 24            case palette
 25            /// Schedule, Deadline and Tags in a menu.
 26            case plan
 27            case hideKeyboard
 28        }
 29
 30        let label: String
 31        /// Nil shows `face` as text.
 32        let symbol: String?
 33        let action: Action
 34        /// The text on the button without a symbol; the label when nil.
 35        var face: String? = nil
 36
 37        var text: String { face ?? label }
 38        var slots: Int { KeyBarLayout.slots(symbol: symbol != nil, face: text) }
 39    }
 40
 41    /// The bar's own buttons, by id.
 42    static let items: [String: Item] = [
 43        "commands": Item(label: String(localized: "Commands"), symbol: "command", action: .palette),
 44        "fold": Item(label: String(localized: "Fold", comment: "Key bar button"), symbol: "arrow.right.to.line", action: .keys("TAB")),
 45        "overview": Item(label: String(localized: "Overview", comment: "Key bar button"), symbol: "arrow.left.to.line", action: .keys("S-TAB")),
 46        "promote": Item(label: String(localized: "Promote", comment: "Key bar button"), symbol: "decrease.indent", action: .keys("M-<left>")),
 47        "demote": Item(label: String(localized: "Demote", comment: "Key bar button"), symbol: "increase.indent", action: .keys("M-<right>")),
 48        "move-up": Item(label: String(localized: "Move Up", comment: "Key bar button"), symbol: "arrow.up.square", action: .keys("M-<up>")),
 49        "move-down": Item(label: String(localized: "Move Down", comment: "Key bar button"), symbol: "arrow.down.square", action: .keys("M-<down>")),
 50        "new-heading": Item(label: String(localized: "New Heading or Item", comment: "Key bar button"), symbol: "plus", action: .keys("M-RET")),
 51        "todo": Item(label: "TODO", symbol: nil, action: .keys("C-c C-t")),
 52        "act": Item(label: String(localized: "Act at Point", comment: "Key bar button"), symbol: "checkmark.square", action: .keys("C-c C-c")),
 53        "plan": Item(label: String(localized: "Plan", comment: "Key bar button: a menu of Schedule, Deadline and Tags"), symbol: "calendar.badge.clock", action: .plan),
 54        "schedule": Item(label: String(localized: "Schedule", comment: "Key bar button"), symbol: "calendar", action: .keys("C-c C-s")),
 55        "deadline": Item(label: String(localized: "Deadline", comment: "Key bar button"), symbol: "calendar.badge.exclamationmark", action: .keys("C-c C-d")),
 56        "tags": Item(label: String(localized: "Tags", comment: "Key bar button"), symbol: "tag", action: .keys("C-c C-q")),
 57        "open-link": Item(label: String(localized: "Open Link", comment: "Key bar button"), symbol: "link", action: .keys("C-c C-o")),
 58        "bold": Item(label: String(localized: "Bold", comment: "Key bar button"), symbol: "bold", action: .command("org.emphasize.bold")),
 59        "italic": Item(label: String(localized: "Italic", comment: "Key bar button"), symbol: "italic", action: .command("org.emphasize.italic")),
 60        "code": Item(label: String(localized: "Code", comment: "Key bar button"), symbol: "chevron.left.forwardslash.chevron.right", action: .command("org.emphasize.code")),
 61        "hide-keyboard": Item(label: String(localized: "Hide Keyboard"), symbol: "keyboard.chevron.compact.down", action: .hideKeyboard),
 62    ]
 63
 64    /// Commands with a symbol of their own; others show their title.
 65    static let commandSymbols: [String: String] = [
 66        KeyBarLayout.nextField: "forward.end", KeyBarLayout.previousField: "backward.end",
 67        "edit.undo": "arrow.uturn.backward", "edit.redo": "arrow.uturn.forward", "edit.isearch-forward": "magnifyingglass",
 68        "org.cycle": "arrow.right.to.line", "org.cycle-global": "arrow.left.to.line",
 69        "org.emphasize.bold": "bold", "org.emphasize.italic": "italic", "org.emphasize.underline": "underline",
 70        "org.emphasize.code": "chevron.left.forwardslash.chevron.right", "org.emphasize.strike-through": "strikethrough",
 71        "org.link.insert": "link.badge.plus", "org.link.open": "link",
 72        "app.clock.in": "clock", "app.clock.out": "clock.badge.checkmark",
 73    ]
 74
 75    /// The editor's commands by id, with English titles.
 76    private static let commandTitles = Dictionary(CommandPalette.viewCommands + Commands.everything.map { ($0.id, $0.title) }) { first, _ in first }
 77
 78    /// The button for an id: one of the bar's own, a command, a named macro (its name) or a
 79    /// snippet (its trigger); nil for an id that is none of these here.
 80    static func item(_ id: String) -> Item? {
 81        if let item = items[id] { return item }
 82        if let trigger = Snippets.trigger(ofCommand: id) {
 83            guard let snippet = SnippetLibrary.shared.snippets.first(where: { $0.trigger == trigger }) else { return nil }
 84            return Item(label: Snippets.label(snippet), symbol: nil, action: .command(id), face: trigger)
 85        }
 86        if id.hasPrefix(NamedMacros.commandPrefix) {
 87            let name = String(id.dropFirst(NamedMacros.commandPrefix.count))
 88            return NamedMacros.shared.names.contains(name) ? Item(label: name, symbol: nil, action: .command(id)) : nil
 89        }
 90        guard !AppStoreCommands.hidden.contains(id), let title = commandTitles[id].map(CommandTitle.localized) else { return nil }
 91        return Item(label: title, symbol: commandSymbols[id], action: .command(id), face: KeyBarLayout.face(title: title))
 92    }
 93
 94    /// Ids in `[key-bar]` that are no button here.
 95    static func problems() -> [String] {
 96        KeyBarLayout.Width.allCases.flatMap { width in
 97            KeyBarLayout.problems(KeyBarLayout.stored(width, in: .standard) ?? [], width) { item($0) != nil }
 98        }
 99    }
100
101    /// The bar's buttons are at least 44 points tall, scaled with the text size up to here.
102    static let largestSize = DynamicTypeSize.accessibility2
103    static let target: CGFloat = 44
104    static let padding: CGFloat = 4
105    /// The widest a one-slot button gets where the bar has room, and the narrowest.
106    nonisolated static let widest: CGFloat = 64
107    static let slot: CGFloat = 32
108    @ScaledMetric(relativeTo: .body) private var size = KeyBar.target
109
110    var body: some View {
111        let layout = sizeClass == .regular ? KeyBarLayout.Width.ipad : .iphone
112        var ids = ((layout == .ipad ? ipad : iphone).map(KeyBarLayout.ids) ?? layout.defaultIDs).filter { Self.item($0) != nil }
113        if editor.fields.active { ids = KeyBarLayout.withSnippetFields(ids) }
114        let available = width.map { Int(($0 - 12) / Self.slot) } ?? .max
115        let (shown, more) = KeyBarLayout.fit(ids, available: available) { Self.item($0)?.slots ?? 1 }
116        return SlotRow {
117            ForEach(shown, id: \.self) { id in
118                if let item = Self.item(id) { button(item).layoutValue(key: Slots.self, value: item.slots) }
119            }
120            if !more.isEmpty { moreButton(more) }
121        }
122        .labelStyle(.iconOnly)
123        .padding(.horizontal, 6)
124        .padding(.vertical, Self.padding)
125        .frame(maxWidth: .infinity)
126        .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width = $0 }
127        .background(.bar)
128    }
129
130    @ViewBuilder
131    private func button(_ item: Item) -> some View {
132        switch item.action {
133        case .plan:
134            Menu {
135                planEntries()
136            } label: {
137                label(item).modifier(KeyShape(size: size))
138            }
139            .accessibilityLabel(item.label)
140        default:
141            Button {
142                run(item)
143            } label: {
144                label(item)
145            }
146            .buttonStyle(KeyStyle(size: size, slots: item.slots))
147            .accessibilityLabel(item.label)
148        }
149    }
150
151    private func planEntries() -> some View {
152        ForEach(["schedule", "deadline", "tags"], id: \.self) { id in
153            if let entry = Self.items[id], case .keys(let keys) = entry.action {
154                Button(entry.label, systemImage: entry.symbol ?? "") { editor.run(keys: keys) }
155            }
156        }
157    }
158
159    /// The buttons that don't fit, in a menu in their order.
160    private func moreButton(_ ids: [String]) -> some View {
161        Menu {
162            ForEach(ids, id: \.self) { id in
163                if let item = Self.item(id) {
164                    switch item.action {
165                    case .plan:
166                        Menu(item.label, systemImage: item.symbol ?? "") { planEntries() }
167                    default:
168                        if let symbol = item.symbol {
169                            Button(item.label, systemImage: symbol) { run(item) }
170                        } else {
171                            Button(item.label) { run(item) }
172                        }
173                    }
174                }
175            }
176        } label: {
177            Label(String(localized: "More"), systemImage: "ellipsis")
178                .dynamicTypeSize(...Self.largestSymbolSize)
179                .modifier(KeyShape(size: size))
180        }
181        .menuOrder(.fixed)
182        .accessibilityLabel(String(localized: "More"))
183    }
184
185    private func run(_ item: Item) {
186        switch item.action {
187        case .keys(let keys): editor.run(keys: keys)
188        case .command(let id): editor.run(id)
189        case .palette: palette()
190        case .hideKeyboard: editor.textView.resignFirstResponder()
191        case .plan: break
192        }
193    }
194
195    /// The buttons grow taller with the text size, but their symbols stop growing here, so
196    /// that they fit the button's share of the width.
197    static let largestSymbolSize = DynamicTypeSize.xxxLarge
198
199    @ViewBuilder
200    private func label(_ item: Item) -> some View {
201        Group {
202            if let symbol = item.symbol {
203                Label(item.label, systemImage: symbol)
204            } else if item.slots == 1 {
205                // A word is wider than a symbol, so it stays at the default size.
206                Text(item.text).font(.callout.weight(.semibold)).lineLimit(1).minimumScaleFactor(0.5)
207                    .dynamicTypeSize(...DynamicTypeSize.large)
208            } else {
209                Text(item.text).font(.caption.weight(.semibold)).lineLimit(2).minimumScaleFactor(0.6)
210                    .multilineTextAlignment(.center).padding(.horizontal, 2)
211                    .dynamicTypeSize(...DynamicTypeSize.large)
212            }
213        }
214        .dynamicTypeSize(...Self.largestSymbolSize)
215    }
216}
217
218/// A button's width in slots.
219private struct Slots: LayoutValueKey {
220    static let defaultValue = 1
221}
222
223/// The bar's buttons in a row, each as wide as its share of the slots.
224private struct SlotRow: Layout {
225    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
226        let slots = subviews.reduce(0) { $0 + $1[Slots.self] }
227        let width = proposal.width ?? CGFloat(slots) * KeyBar.widest
228        let unit = width / CGFloat(max(slots, 1))
229        let height = subviews.map { $0.sizeThatFits(ProposedViewSize(width: unit * CGFloat($0[Slots.self]), height: proposal.height)).height }.max() ?? 0
230        return CGSize(width: width, height: height)
231    }
232
233    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
234        let unit = bounds.width / CGFloat(max(subviews.reduce(0) { $0 + $1[Slots.self] }, 1))
235        var x = bounds.minX
236        for view in subviews {
237            let width = unit * CGFloat(view[Slots.self])
238            view.place(at: CGPoint(x: x, y: bounds.minY), proposal: ProposedViewSize(width: width, height: bounds.height))
239            x += width
240        }
241    }
242}
243
244/// A key bar button's look: a tinted label on a rounded tile, `size` tall, sharing the bar's
245/// width with the others. The whole share is the touch target.
246private struct KeyShape: ViewModifier {
247    let size: CGFloat
248    var slots = 1
249    var pressed = false
250
251    func body(content: Content) -> some View {
252        content
253            .foregroundStyle(.tint)
254            .frame(maxWidth: KeyBar.widest * CGFloat(slots), minHeight: size)
255            .background(.fill.tertiary, in: .rect(cornerRadius: 10))
256            .opacity(pressed ? 0.5 : 1)
257            .padding(.horizontal, 2)
258            .frame(maxWidth: .infinity)
259            .contentShape(.rect)
260    }
261}
262
263private struct KeyStyle: ButtonStyle {
264    let size: CGFloat
265    let slots: Int
266
267    func makeBody(configuration: Configuration) -> some View {
268        configuration.label.modifier(KeyShape(size: size, slots: slots, pressed: configuration.isPressed))
269    }
270}
271#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form