Sources/OrgstarMobile/KeyBar.swift

4b0ad76c9ca64e32a6c95a891e8db59bacbf81af
orgstar/Sources/OrgstarMobile/KeyBar.swift

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