Sources/OrgstarMobile/KeyBar.swift
366 lines · 17623 bytes
25 symbols in this file
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 if id.hasPrefix(UserCommands.commandPrefix) {
94 return UserCommands.shared.command(id).map { Item(label: $0.title, symbol: nil, action: .command(id)) }
95 }
96 guard !AppStoreCommands.hidden.contains(id), let title = commandTitles[id].map(CommandTitle.localized) else { return nil }
97 return Item(label: title, symbol: commandSymbols[id], action: .command(id), face: KeyBarLayout.face(title: title))
98 }
99
100 /// Ids in `[key-bar]` that are no button here.
101 static func problems() -> [String] {
102 KeyBarLayout.Width.allCases.flatMap { width in
103 KeyBarLayout.problems(KeyBarLayout.stored(width, in: .standard) ?? [], width) { item($0) != nil }
104 }
105 }
106
107 /// The bar's buttons are at least 44 points tall, scaled with the text size up to here.
108 static let largestSize = DynamicTypeSize.accessibility2
109 static let target: CGFloat = 44
110 static let padding: CGFloat = 4
111 /// The widest a one-slot button gets where the bar has room.
112 nonisolated static let widest: CGFloat = 64
113 @ScaledMetric(relativeTo: .body) private var size = KeyBar.target
114
115 var body: some View {
116 Group {
117 if SuggestionRow.shows(editor.suggestions.completion, dismissed: editor.suggestions.dismissed), let completion = editor.suggestions.completion {
118 suggestionRow(completion)
119 } else {
120 keys
121 }
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 private var keys: some View {
132 let layout = sizeClass == .regular ? KeyBarLayout.Width.ipad : .iphone
133 var ids = ((layout == .ipad ? ipad : iphone).map(KeyBarLayout.ids) ?? layout.defaultIDs).filter { Self.item($0) != nil }
134 if editor.fields.active { ids = KeyBarLayout.withSnippetFields(ids) }
135 let available = width.map { KeyBarLayout.availableSlots(width: $0 - 12, scale: symbolScale) } ?? .max
136 let (shown, more) = KeyBarLayout.fit(ids, available: available) { Self.item($0)?.slots ?? 1 }
137 return SlotRow {
138 ForEach(shown, id: \.self) { id in
139 if let item = Self.item(id) { button(item).layoutValue(key: Slots.self, value: item.slots) }
140 }
141 if !more.isEmpty { moreButton(more) }
142 }
143 }
144
145 /// The candidates at the caret in the bar's place, scrolling on their own, and at the end
146 /// the button that puts them away and brings the keys back.
147 private func suggestionRow(_ completion: Completion) -> some View {
148 HStack(spacing: 4) {
149 ScrollView(.horizontal, showsIndicators: false) {
150 HStack(spacing: 4) {
151 ForEach(SuggestionRow.items(completion), id: \.candidate) { item in
152 Button {
153 editor.chooseSuggestion(item.candidate)
154 } label: {
155 suggestionLabel(item)
156 }
157 .buttonStyle(SuggestionStyle(size: size))
158 .accessibilityLabel([item.candidate, item.detail, item.snippet ? String(localized: "snippet", comment: "Marks a snippet in the completion list") : nil]
159 .compactMap { $0 }.joined(separator: ", "))
160 }
161 }
162 .padding(.horizontal, 2)
163 }
164 // Back at the start for each new completion.
165 .id(completion.range.lowerBound)
166 Button {
167 editor.suggestions.dismissed = true
168 } label: {
169 Label(String(localized: "Hide Suggestions"), systemImage: "xmark")
170 }
171 .buttonStyle(KeyStyle(size: size, slots: 1))
172 .frame(width: KeyBar.widest)
173 .accessibilityLabel(String(localized: "Hide Suggestions"))
174 }
175 .dynamicTypeSize(...Self.largestSymbolSize)
176 .accessibilityIdentifier("suggestions")
177 }
178
179 private func suggestionLabel(_ item: SuggestionRow.Item) -> some View {
180 CappedWidth(width: 240) {
181 HStack(spacing: 4) {
182 if item.snippet { Image(systemName: "text.badge.plus").foregroundStyle(.tint) }
183 Text(item.candidate).foregroundStyle(.primary)
184 if let detail = item.detail { Text(detail).foregroundStyle(.secondary) }
185 }
186 .font(.body)
187 .lineLimit(1)
188 }
189 }
190
191 @ViewBuilder
192 private func button(_ item: Item) -> some View {
193 switch item.action {
194 case .plan:
195 Menu {
196 planEntries()
197 } label: {
198 label(item).modifier(KeyShape(size: size))
199 }
200 .accessibilityLabel(item.label)
201 default:
202 Button {
203 run(item)
204 } label: {
205 label(item)
206 }
207 .buttonStyle(KeyStyle(size: size, slots: item.slots))
208 .accessibilityLabel(item.label)
209 }
210 }
211
212 private func planEntries() -> some View {
213 ForEach(["schedule", "deadline", "tags"], id: \.self) { id in
214 if let entry = Self.items[id], case .keys(let keys) = entry.action {
215 Button(entry.label, systemImage: entry.symbol ?? "") { editor.run(keys: keys) }
216 }
217 }
218 }
219
220 /// The buttons that don't fit, in a menu in their order.
221 private func moreButton(_ ids: [String]) -> some View {
222 Menu {
223 ForEach(ids, id: \.self) { id in
224 if let item = Self.item(id) {
225 switch item.action {
226 case .plan:
227 Menu(item.label, systemImage: item.symbol ?? "") { planEntries() }
228 default:
229 if let symbol = item.symbol {
230 Button(item.label, systemImage: symbol) { run(item) }
231 } else {
232 Button(item.label) { run(item) }
233 }
234 }
235 }
236 }
237 } label: {
238 Label(String(localized: "More"), systemImage: "ellipsis")
239 .dynamicTypeSize(...Self.largestSymbolSize)
240 .modifier(KeyShape(size: size))
241 }
242 .menuOrder(.fixed)
243 .accessibilityLabel(String(localized: "More"))
244 }
245
246 private func run(_ item: Item) {
247 switch item.action {
248 case .keys(let keys): editor.run(keys: keys)
249 case .command(let id): editor.run(id)
250 case .palette: palette()
251 case .hideKeyboard: editor.textView.resignFirstResponder()
252 case .plan: break
253 }
254 }
255
256 /// The buttons grow taller with the text size, but their symbols stop growing here.
257 static let largestSymbolSize = DynamicTypeSize.xxxLarge
258
259 /// How much larger than at the default size the symbols are drawn, which the slots follow.
260 private var symbolScale: CGFloat {
261 let traits = UITraitCollection(preferredContentSizeCategory: UIContentSizeCategory(min(typeSize, Self.largestSymbolSize)))
262 return UIFontMetrics(forTextStyle: .body).scaledValue(for: 1, compatibleWith: traits)
263 }
264
265 @ViewBuilder
266 private func label(_ item: Item) -> some View {
267 Group {
268 if let symbol = item.symbol {
269 Label(item.label, systemImage: symbol)
270 } else if item.slots == 1 {
271 // A word is wider than a symbol, so it stays at the default size.
272 Text(item.text).font(.callout.weight(.semibold)).lineLimit(1).minimumScaleFactor(0.5)
273 .dynamicTypeSize(...DynamicTypeSize.large)
274 } else {
275 Text(item.text).font(.caption.weight(.semibold)).lineLimit(2).minimumScaleFactor(0.6)
276 .multilineTextAlignment(.center).padding(.horizontal, 2)
277 .dynamicTypeSize(...DynamicTypeSize.large)
278 }
279 }
280 .dynamicTypeSize(...Self.largestSymbolSize)
281 }
282}
283
284/// A button's width in slots.
285private struct Slots: LayoutValueKey {
286 static let defaultValue = 1
287}
288
289/// The bar's buttons in a row, each as wide as its share of the slots.
290private struct SlotRow: Layout {
291 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
292 let slots = subviews.reduce(0) { $0 + $1[Slots.self] }
293 let width = proposal.width ?? CGFloat(slots) * KeyBar.widest
294 let unit = width / CGFloat(max(slots, 1))
295 let height = subviews.map { $0.sizeThatFits(ProposedViewSize(width: unit * CGFloat($0[Slots.self]), height: proposal.height)).height }.max() ?? 0
296 return CGSize(width: width, height: height)
297 }
298
299 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
300 let unit = bounds.width / CGFloat(max(subviews.reduce(0) { $0 + $1[Slots.self] }, 1))
301 var x = bounds.minX
302 for view in subviews {
303 let width = unit * CGFloat(view[Slots.self])
304 view.place(at: CGPoint(x: x, y: bounds.minY), proposal: ProposedViewSize(width: width, height: bounds.height))
305 x += width
306 }
307 }
308}
309
310/// A key bar button's look: a tinted label on a rounded tile, `size` tall, sharing the bar's
311/// width with the others. The whole share is the touch target.
312private struct KeyShape: ViewModifier {
313 let size: CGFloat
314 var slots = 1
315 var pressed = false
316
317 func body(content: Content) -> some View {
318 content
319 .foregroundStyle(.tint)
320 .frame(maxWidth: KeyBar.widest * CGFloat(slots), minHeight: size)
321 .background(.fill.tertiary, in: .rect(cornerRadius: 10))
322 .opacity(pressed ? 0.5 : 1)
323 .padding(.horizontal, 2)
324 .frame(maxWidth: .infinity)
325 .contentShape(.rect)
326 }
327}
328
329/// As wide as its content wants up to `width`, where a long suggestion is cut short.
330private struct CappedWidth: Layout {
331 let width: CGFloat
332
333 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
334 guard let view = subviews.first else { return .zero }
335 let ideal = view.sizeThatFits(.unspecified)
336 return view.sizeThatFits(ProposedViewSize(width: min(ideal.width, width), height: proposal.height))
337 }
338
339 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
340 subviews.first?.place(at: bounds.origin, proposal: ProposedViewSize(bounds.size))
341 }
342}
343
344/// A suggestion: its text on a tile as tall as the keys, as wide as the text needs.
345private struct SuggestionStyle: ButtonStyle {
346 let size: CGFloat
347
348 func makeBody(configuration: Configuration) -> some View {
349 configuration.label
350 .padding(.horizontal, 12)
351 .frame(minHeight: size)
352 .background(.fill.tertiary, in: .rect(cornerRadius: 10))
353 .opacity(configuration.isPressed ? 0.5 : 1)
354 .contentShape(.rect)
355 }
356}
357
358private struct KeyStyle: ButtonStyle {
359 let size: CGFloat
360 let slots: Int
361
362 func makeBody(configuration: Configuration) -> some View {
363 configuration.label.modifier(KeyShape(size: size, slots: slots, pressed: configuration.isPressed))
364 }
365}
366#endif