// The bar above the keyboard and the formatting panel that takes the // keyboard's place. Which keys there are, their order, words and symbols are // the core's (`WritingWords`); the bar's own five are found by action: // `undo`, `redo`, `tag`, `hide`, `format`. #if canImport(UIKit) import UIKit /// What a key wears: its drawn mark when the icon set has one, else its /// glyph ("H1", "B") in the look's face and the glyph's style, else the /// phone's own symbol the key's icon names, else its label. @MainActor func wear(_ key: WritingKey, on button: UIButton, look: WritingLook, size: CGFloat = 17) { var config = button.configuration ?? .plain() if let icon = key.icon, let image = WritingMarks.image(icon, size: size + 5) { // Notes' own drawing of the key (`WritingMarks`), before any glyph or system symbol. config.image = image config.attributedTitle = nil } else if let glyph = key.glyph, !glyph.isEmpty { var face: WritingFace = [] switch key.style { case "bold": face = .bold case "italic": face = .italic case "mono": face = .mono default: face = glyph.count <= 2 ? .bold : [] } var title = AttributeContainer() title.font = look.font(face).withSize(size) if key.style == "underline" { title.underlineStyle = .single } if key.style == "strike" { title.strikethroughStyle = .single } config.attributedTitle = AttributedString(glyph, attributes: title) config.image = nil } else if let icon = key.icon, let image = UIImage(systemName: WritingIcons.symbol(icon), withConfiguration: UIImage.SymbolConfiguration(pointSize: size, weight: .regular)) { config.image = image config.attributedTitle = nil } else { var title = AttributeContainer() title.font = look.font([]).withSize(size * 0.8) config.attributedTitle = AttributedString(key.label, attributes: title) } config.contentInsets = NSDirectionalEdgeInsets(top: 4, leading: 4, bottom: 4, trailing: 4) button.configuration = config button.accessibilityLabel = key.label button.largeContentTitle = key.label button.showsLargeContentViewer = true } /// The phone's own symbol for each icon the core names. enum WritingIcons { static func symbol(_ icon: String) -> String { switch icon { case "undo": "arrow.uturn.backward" case "redo": "arrow.uturn.forward" case "tag": "number" case "import", "picture": "photo" case "hide", "hide_keyboard": "keyboard.chevron.compact.down" case "format": "textformat" case "divider": "minus" case "highlight": "highlighter" case "bullets": "list.bullet" case "numbers": "list.number" case "check": "checklist" case "quote": "text.quote" case "code": "chevron.left.forwardslash.chevron.right" case "link": "link" case "indent": "increase.indent" case "outdent": "decrease.indent" case "up": "arrow.up" case "down": "arrow.down" case "delete": "delete.left" case "space": "space" case "return": "return" case "keyboard": "keyboard" case "archive": "archivebox" case "bin": "trash" case "restore": "arrow.uturn.backward" case "share": "square.and.arrow.up" case "export": "doc.text" case "settings": "textformat.size" case "search": "magnifyingglass" case "info": "info" case "more": "ellipsis" case "back": "chevron.backward" case "compose": "square.and.pencil" default: icon } } } @MainActor final class WritingBar: UIInputView { private let words: WritingWords private var look: WritingLook private let stack = UIStackView() private let offers = UIStackView() private let offersScroll = UIScrollView() private let openRow = UIButton(configuration: .plain()) private var openHeight: NSLayoutConstraint? private var height: NSLayoutConstraint? private var formatButton: UIButton? private var buttons: [UIButton] = [] private var opening: String? var onKey: ((WritingKey) -> Void)? var onOffer: ((WritingTagOffer) -> Void)? var onLinkOffer: ((WritingTagOffer) -> Void)? var onOpen: ((String) -> Void)? static let height: CGFloat = 48 static let openRowHeight: CGFloat = 38 init(words: WritingWords, look: WritingLook) { self.words = words self.look = look super.init(frame: CGRect(x: 0, y: 0, width: 320, height: Self.height), inputViewStyle: .default) allowsSelfSizing = true translatesAutoresizingMaskIntoConstraints = false stack.axis = .horizontal stack.alignment = .center stack.distribution = .equalSpacing stack.translatesAutoresizingMaskIntoConstraints = false addSubview(stack) offers.axis = .horizontal offers.spacing = 8 offers.alignment = .center offers.translatesAutoresizingMaskIntoConstraints = false offersScroll.showsHorizontalScrollIndicator = false offersScroll.translatesAutoresizingMaskIntoConstraints = false offersScroll.isHidden = true offersScroll.addSubview(offers) addSubview(offersScroll) // The cursor in a link: Open it (an address in the phone's browser, a [[note]] in Notes), a row above the keys. openRow.translatesAutoresizingMaskIntoConstraints = false openRow.contentHorizontalAlignment = .leading openRow.isHidden = true openRow.accessibilityIdentifier = "link-open" openRow.addAction(UIAction { [weak self] _ in if let url = self?.opening { self?.onOpen?(url) } }, for: .primaryActionTriggered) addSubview(openRow) // The core's keys in its order, spread across the bar; a `gap` key parts the left keys from the right ones. let keys = words.bar.filter { $0.id != "keyboard" } if keys.contains(where: { $0.id == "gap" }) { stack.distribution = .fill stack.spacing = 2 for key in keys { if key.id == "gap" { let gap = UIView() gap.setContentHuggingPriority(.defaultLow - 1, for: .horizontal) stack.addArrangedSubview(gap) } else { stack.addArrangedSubview(button(key)) } } } else { for key in keys { stack.addArrangedSubview(button(key)) } } let openHeight = openRow.heightAnchor.constraint(equalToConstant: 0) let height = heightAnchor.constraint(equalToConstant: Self.height) self.openHeight = openHeight self.height = height NSLayoutConstraint.activate([ height, openRow.topAnchor.constraint(equalTo: topAnchor), openRow.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: 14), openRow.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -14), openHeight, stack.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: 6), stack.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -6), stack.topAnchor.constraint(equalTo: openRow.bottomAnchor), stack.bottomAnchor.constraint(equalTo: bottomAnchor), offersScroll.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: 10), offersScroll.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -10), offersScroll.topAnchor.constraint(equalTo: stack.topAnchor), offersScroll.bottomAnchor.constraint(equalTo: stack.bottomAnchor), offers.leadingAnchor.constraint(equalTo: offersScroll.contentLayoutGuide.leadingAnchor), offers.trailingAnchor.constraint(equalTo: offersScroll.contentLayoutGuide.trailingAnchor), offers.topAnchor.constraint(equalTo: offersScroll.contentLayoutGuide.topAnchor), offers.bottomAnchor.constraint(equalTo: offersScroll.contentLayoutGuide.bottomAnchor), offers.heightAnchor.constraint(equalTo: offersScroll.frameLayoutGuide.heightAnchor), ]) restyle(look) } required init?(coder: NSCoder) { fatalError("init(coder:) is not used") } func restyle(_ look: WritingLook) { self.look = look backgroundColor = look.theme.bar for button in buttons { button.tintColor = look.theme.ink } formatButton?.tintColor = formatting ? look.theme.accent : look.theme.ink openRow.tintColor = look.theme.link } private func button(_ key: WritingKey) -> UIButton { let button = UIButton(configuration: .plain(), primaryAction: UIAction { [weak self] _ in self?.onKey?(key) }) wear(key, on: button, look: look) button.accessibilityIdentifier = "writing-bar-\(key.id)" button.widthAnchor.constraint(greaterThanOrEqualToConstant: 44).isActive = true button.setContentHuggingPriority(.defaultHigh, for: .horizontal) button.heightAnchor.constraint(equalToConstant: 44).isActive = true if key.id == "format" { formatButton = button } buttons.append(button) return button } /// Whether the panel stands in the keyboard's place: the format key shows the keyboard's key, lit. var formatting = false { didSet { guard let formatButton else { return } if let shown = formatting ? words.key("keyboard") : words.bar("format") { wear(shown, on: formatButton, look: look) } formatButton.tintColor = formatting ? look.theme.accent : look.theme.ink formatButton.accessibilityTraits = formatting ? [.button, .selected] : .button } } /// The tags offered for the tag being typed, in the keys' place; empty brings the keys back. func offer(_ tags: [WritingTagOffer]) { chips(tags.map { ("#" + $0.label, nil) }) { [weak self] i in self?.onOffer?(tags[i]) } } /// The notes a `[[` being typed may name, in the keys' place; empty brings the keys back. func offerLinks(_ notes: [WritingTagOffer]) { chips(notes.map { ($0.label, "notes") }) { [weak self] i in self?.onLinkOffer?(notes[i]) } } /// The link the cursor stands in (an address, or `note:`): the Open row above the keys; nil hides it. func openHere(_ url: String?) { guard url != opening else { return } opening = url if let url { let note = url.hasPrefix("note:") let shown = note ? String(url.dropFirst(5)) : (URL(string: url)?.host ?? url) var config = UIButton.Configuration.plain() var title = AttributeContainer() title.font = look.font([]).withSize(15) config.attributedTitle = AttributedString(words.word("open") + " " + shown, attributes: title) config.image = WritingMarks.image(note ? "note_link" : "link", size: 18) config.imagePadding = 10 config.contentInsets = .zero openRow.configuration = config openRow.accessibilityLabel = words.word("open") + " " + shown } openRow.isHidden = url == nil openHeight?.constant = url == nil ? 0 : Self.openRowHeight height?.constant = Self.height + (url == nil ? 0 : Self.openRowHeight) invalidateIntrinsicContentSize() superview?.setNeedsLayout() } private func chips(_ labels: [(String, String?)], picked: @escaping (Int) -> Void) { offers.arrangedSubviews.forEach { $0.removeFromSuperview() } for (i, (label, icon)) in labels.enumerated() { var config = UIButton.Configuration.filled() config.title = label config.baseBackgroundColor = icon == nil ? look.theme.chip : look.theme.ground config.baseForegroundColor = icon == nil ? look.theme.chipInk : look.theme.ink config.cornerStyle = .capsule config.image = icon.flatMap { WritingMarks.image($0, size: 15) } config.imagePadding = 6 config.contentInsets = NSDirectionalEdgeInsets(top: 6, leading: 12, bottom: 6, trailing: 12) config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { [look] in var a = $0 a.font = look.font([]).withSize(15) return a } let chip = UIButton(configuration: config, primaryAction: UIAction { _ in picked(i) }) chip.tintColor = look.theme.dim chip.accessibilityIdentifier = icon == nil ? "writing-tag-offer" : "link-offer" offers.addArrangedSubview(chip) } let showing = !labels.isEmpty offersScroll.isHidden = !showing stack.isHidden = showing } } /// The formatting panel: the core's keys in its rows, then delete, space and /// return so writing goes on without the keyboard. @MainActor final class WritingPanel: UIInputView { var onKey: ((WritingKey) -> Void)? private var look: WritingLook private let words: WritingWords private let rows = UIStackView() private var buttons: [UIButton] = [] init(words: WritingWords, look: WritingLook, height: CGFloat) { self.words = words self.look = look super.init(frame: CGRect(x: 0, y: 0, width: 320, height: height), inputViewStyle: .keyboard) allowsSelfSizing = false rows.axis = .vertical rows.spacing = 8 rows.distribution = .fillEqually rows.translatesAutoresizingMaskIntoConstraints = false addSubview(rows) NSLayoutConstraint.activate([ rows.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: 10), rows.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -10), rows.topAnchor.constraint(equalTo: topAnchor, constant: 10), rows.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -8), ]) build() restyle(look) } required init?(coder: NSCoder) { fatalError("init(coder:) is not used") } private func build() { if !words.grid.isEmpty { buildGrid() return } // The core's groups in its order; a key with no group joins the row before. var groups: [[WritingKey]] = [] var last: String? for key in words.panel { if groups.isEmpty || (key.group != nil && key.group != last) { groups.append([]) } groups[groups.count - 1].append(key) last = key.group ?? last } // A row wider than six keys is cut into rows of six. let cut = groups.flatMap { group in stride(from: 0, to: group.count, by: 6).map { Array(group[$0..<min($0 + 6, group.count)]) } } for keys in cut { let row = UIStackView() row.axis = .horizontal row.spacing = 8 row.distribution = .fillEqually for key in keys { row.addArrangedSubview(button(key)) } rows.addArrangedSubview(row) } } /// The kit's grid in the keyboard's place: its rows of keys, the editing keys darker, a held key's offers in a /// menu (a corner triangle on the key says it has them); then the slim row, copy at the left and paste at the right. private func buildGrid() { rows.distribution = .fill rows.spacing = 7 for keys in words.grid { let row = UIStackView() row.axis = .horizontal row.spacing = 6 row.distribution = .fillEqually for key in keys { row.addArrangedSubview(button(key)) } rows.addArrangedSubview(row) } for row in rows.arrangedSubviews.dropFirst() { row.heightAnchor.constraint(equalTo: rows.arrangedSubviews[0].heightAnchor).isActive = true } guard !words.foot.isEmpty else { return } let foot = UIStackView() foot.axis = .horizontal foot.distribution = .equalSpacing for (i, key) in words.foot.enumerated() { if i > 0 { foot.addArrangedSubview(UIView()) } let button = button(key, plain: true) button.widthAnchor.constraint(greaterThanOrEqualToConstant: 64).isActive = true foot.addArrangedSubview(button) } foot.heightAnchor.constraint(equalToConstant: 30).isActive = true rows.addArrangedSubview(foot) } private func button(_ key: WritingKey, plain: Bool = false) -> UIButton { let button = UIButton(configuration: .plain(), primaryAction: UIAction { [weak self] _ in UIDevice.current.playInputClick() self?.onKey?(key) }) wear(key, on: button, look: look, size: plain ? 15 : 18) button.accessibilityLabel = key.label if plain { faces[button] = .plain } else if key.grey == true { faces[button] = .grey } else { faces[button] = .key } if let hold = key.hold, !hold.isEmpty { // Held, the key offers the rest (the system's menu on a long press); a tap is still the key itself. button.menu = UIMenu(children: hold.map { other in UIAction(title: other.label, image: other.icon.flatMap { WritingMarks.image($0, size: 20) }) { [weak self] _ in self?.onKey?(other) } }) button.showsMenuAsPrimaryAction = false let corner = WritingHoldCorner() corner.translatesAutoresizingMaskIntoConstraints = false corner.isUserInteractionEnabled = false button.addSubview(corner) NSLayoutConstraint.activate([ corner.widthAnchor.constraint(equalToConstant: 6), corner.heightAnchor.constraint(equalToConstant: 6), corner.trailingAnchor.constraint(equalTo: button.trailingAnchor, constant: -5), corner.bottomAnchor.constraint(equalTo: button.bottomAnchor, constant: -5), ]) corners.append(corner) } button.layer.cornerRadius = 9 button.accessibilityIdentifier = "writing-panel-\(key.id)" if key.id == "delete" { // Held, delete repeats as the keyboard's does. let hold = UILongPressGestureRecognizer(target: self, action: #selector(held(_:))) hold.minimumPressDuration = 0.4 button.addGestureRecognizer(hold) } buttons.append(button) return button } private var repeating: Timer? @objc private func held(_ press: UILongPressGestureRecognizer) { guard let key = words.key("delete") else { return } switch press.state { case .began: repeating = Timer.scheduledTimer(withTimeInterval: 0.08, repeats: true) { [weak self] _ in MainActor.assumeIsolated { self?.onKey?(key) } } case .ended, .cancelled, .failed: repeating?.invalidate() repeating = nil default: break } } private enum Face { case key, grey, plain } private var faces: [UIButton: Face] = [:] private var corners: [WritingHoldCorner] = [] func restyle(_ look: WritingLook) { self.look = look let theme = look.theme backgroundColor = theme.bar // A mark's key stands light on the panel's ground; an editing key darker, as the keyboard's own are. let key = theme.dark ? theme.ink.withAlphaComponent(0.2) : UIColor.white let grey = theme.dark ? theme.ink.withAlphaComponent(0.09) : theme.rule for button in buttons { button.tintColor = theme.ink switch faces[button] ?? .key { case .key: button.backgroundColor = words.grid.isEmpty ? theme.ground : key case .grey: button.backgroundColor = grey case .plain: button.backgroundColor = .clear } if faces[button] != .plain, !words.grid.isEmpty { button.layer.shadowColor = UIColor.black.cgColor button.layer.shadowOpacity = theme.dark ? 0 : 0.18 button.layer.shadowOffset = CGSize(width: 0, height: 1) button.layer.shadowRadius = 0 } } for corner in corners { corner.colour = theme.dim corner.setNeedsDisplay() } } } /// The tiny triangle in a key's corner: the key offers more when held. final class WritingHoldCorner: UIView { var colour: UIColor = .gray override init(frame: CGRect) { super.init(frame: frame) isOpaque = false backgroundColor = .clear } required init?(coder: NSCoder) { fatalError("init(coder:) is not used") } override func draw(_ rect: CGRect) { let path = UIBezierPath() path.move(to: CGPoint(x: rect.maxX, y: rect.minY)) path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY)) path.close() colour.setFill() path.fill() } } extension WritingPanel: UIInputViewAudioFeedback { var enableInputClicksWhenVisible: Bool { true } } #endif