Sources/OrgstarMobile/KeyBar.swift

fc3ddfcd5858fab2b88399e3df1ce76f3213a7c9
orgstar/Sources/OrgstarMobile/KeyBar.swift

363 lines · 17443 bytes

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