Repository Public
1// SP Notes iOS2// File: Editor/SlashMenu.swift3// Description: The slash menu: typing « / » at the start of a paragraph or after a space opens a filterable list of blocks anchored4// to the caret. What is typed after the slash filters it; a tap, or Return on a hardware keyboard (arrows to move,5// Escape to close), removes the typed text and runs the command. Never opens inside a code block.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesDesign10import UIKit1112@MainActor13final class SlashMenuController {14 weak var editor: EditorController?15 /// Location of the « / » that opened the session.16 private(set) var anchor: Int?17 private(set) var query = ""18 private(set) var results: [EditorCommand] = []19 private(set) var selectedIndex = 020 /// Set when a « / » that may open the menu is about to be inserted by the text view.21 var pendingAnchor: Int?22 let view = SlashMenuView()2324 var isActive: Bool { anchor != nil }25 var selected: EditorCommand? { results.indices.contains(selectedIndex) ? results[selectedIndex] : nil }2627 init() {28 view.onChoose = { [weak self] command in self?.choose(command) }29 }3031 /// Whether a « / » typed at `location` opens the menu: in a text block that is not code, at its start or after white space.32 func canBegin(at location: Int) -> Bool {33 guard let editor else { return false }34 let paragraph = editor.paragraphRange(at: location)35 let style = editor.style(at: paragraph.location)36 guard AttributedCodec.isTextual(style), !style.isCode, style.type != "detailsSummary" else { return false }37 if location == paragraph.location { return true }38 guard location > 0, location <= editor.storage.length else { return false }39 let previous = (editor.storage.string as NSString).character(at: location - 1)40 guard let scalar = Unicode.Scalar(previous) else { return false }41 return CharacterSet.whitespaces.contains(scalar) || previous == EditorCharacter.softBreakScalar42 }4344 /// Re-reads the query after any change of text or selection; closes the session when it no longer holds.45 func refresh() {46 guard let editor else { return }47 let storage = editor.storage48 if let pending = pendingAnchor {49 pendingAnchor = nil50 if pending < storage.length, (storage.string as NSString).substring(with: NSRange(location: pending, length: 1)) == "/" { anchor = pending }51 }52 guard let anchor else { return }53 let selection = editor.textView.selectedRange54 let paragraph = editor.paragraphRange(at: anchor)55 guard selection.length == 0, selection.location > anchor, selection.location < NSMaxRange(paragraph), anchor < storage.length,56 (storage.string as NSString).substring(with: NSRange(location: anchor, length: 1)) == "/" else { cancel(); return }57 let typed = (storage.string as NSString).substring(with: NSRange(location: anchor + 1, length: selection.location - anchor - 1))58 guard !typed.contains(EditorCharacter.attachment), !typed.contains(EditorCharacter.softBreak) else { cancel(); return }59 let found = InsertCatalog.search(typed)60 // nothing matches and the user moved on to a sentence: this was a plain « / »61 if found.isEmpty, typed.contains(" ") || typed.count > 18 { cancel(); return }62 if typed != query || results != found { selectedIndex = 0 }63 query = typed64 results = found65 show()66 }6768 private func show() {69 guard let editor, let anchor else { return }70 let textView = editor.textView71 view.update(results: results, selected: selectedIndex, query: query)72 guard let position = textView.position(from: textView.beginningOfDocument, offset: min(anchor + 1, max(0, editor.storage.length - 1))) else { return }73 let caret = textView.caretRect(for: position)74 let width = min(320, max(220, textView.bounds.width - 32))75 var height = view.preferredHeight76 let x = min(max(12, caret.minX - 8), max(12, textView.bounds.width - width - 12))77 // Below the line when it fits in what is visible above the keyboard, above it otherwise; when neither side has the78 // room, the larger side is used and the list is shortened (it scrolls) rather than hidden behind the keyboard.79 let visibleTop = textView.contentOffset.y + textView.adjustedContentInset.top80 let visibleBottom = textView.contentOffset.y + textView.bounds.height - textView.adjustedContentInset.bottom81 let below = visibleBottom - (caret.maxY + 6) - 8, above = (caret.minY - 6) - visibleTop - 882 var y = caret.maxY + 683 if height > below {84 if height <= above { y = caret.minY - 6 - height }85 else if below >= above || textView.window == nil { height = max(view.minimumHeight, min(height, below)) }86 else { height = max(view.minimumHeight, min(height, above)); y = caret.minY - 6 - height }87 }88 let frame = CGRect(x: x, y: y, width: width, height: height)89 if view.superview !== textView {90 view.alpha = 091 textView.addSubview(view)92 view.frame = frame93 let reduce = UIAccessibility.isReduceMotionEnabled94 if !reduce { view.transform = CGAffineTransform(translationX: 0, y: 6) }95 UIView.animate(withDuration: NVMotion.duration(.fast, reduceMotion: reduce), delay: 0, options: [.curveEaseOut, .allowUserInteraction]) {96 self.view.alpha = 197 self.view.transform = .identity98 }99 } else {100 view.frame = frame101 }102 textView.bringSubviewToFront(view)103 }104105 func move(_ delta: Int) {106 guard isActive, !results.isEmpty else { return }107 selectedIndex = (selectedIndex + delta + results.count) % results.count108 view.update(results: results, selected: selectedIndex, query: query)109 }110111 /// Runs the highlighted command. False when the menu is closed or shows nothing.112 @discardableResult113 func commit() -> Bool {114 guard isActive, let command = selected else { return false }115 choose(command)116 return true117 }118119 func choose(_ command: EditorCommand) {120 guard let editor, let anchor else { return }121 let caret = editor.textView.selectedRange.location122 let typed = NSRange(location: anchor, length: max(1, caret - anchor))123 cancel()124 // the « /query » text goes away and the command runs: one undo step brings the typed characters back125 editor.replace(typed, with: NSAttributedString(), selectAfter: NSRange(location: anchor, length: 0), actionName: command.title)126 editor.onCommand?(command.action)127 }128129 func cancel() {130 anchor = nil131 pendingAnchor = nil132 query = ""133 results = []134 selectedIndex = 0135 view.removeFromSuperview()136 }137}138139/// The floating list of the slash menu (a card on glass-like elevated surface).140@MainActor141final class SlashMenuView: UIView {142 var onChoose: ((EditorCommand) -> Void)?143 private let scroll = UIScrollView()144 private let stack = UIStackView()145 private let empty = UILabel()146 private var rows: [SlashMenuRow] = []147 private var shown: [EditorCommand] = []148 static let rowHeight: CGFloat = 46149 static let visibleRows: CGFloat = 5.5150151 override init(frame: CGRect) {152 super.init(frame: frame)153 accessibilityIdentifier = "slash-menu"154 backgroundColor = NVUIColor.bgElevated155 layer.cornerRadius = NVRadius.lg156 layer.cornerCurve = .continuous157 layer.borderWidth = 1158 layer.shadowColor = UIColor.black.cgColor159 layer.shadowOpacity = 0.16160 layer.shadowRadius = 20161 layer.shadowOffset = CGSize(width: 0, height: 8)162 scroll.layer.cornerRadius = NVRadius.lg163 scroll.layer.cornerCurve = .continuous164 scroll.clipsToBounds = true165 scroll.translatesAutoresizingMaskIntoConstraints = false166 stack.axis = .vertical167 stack.translatesAutoresizingMaskIntoConstraints = false168 addSubview(scroll)169 scroll.addSubview(stack)170 empty.text = String(localized: "Aucun bloc ne correspond")171 empty.font = .preferredFont(forTextStyle: .subheadline)172 empty.adjustsFontForContentSizeCategory = true173 empty.textColor = NVUIColor.fgMuted174 empty.textAlignment = .center175 empty.translatesAutoresizingMaskIntoConstraints = false176 addSubview(empty)177 NSLayoutConstraint.activate([178 scroll.leadingAnchor.constraint(equalTo: leadingAnchor), scroll.trailingAnchor.constraint(equalTo: trailingAnchor),179 scroll.topAnchor.constraint(equalTo: topAnchor), scroll.bottomAnchor.constraint(equalTo: bottomAnchor),180 stack.leadingAnchor.constraint(equalTo: scroll.contentLayoutGuide.leadingAnchor), stack.trailingAnchor.constraint(equalTo: scroll.contentLayoutGuide.trailingAnchor),181 stack.topAnchor.constraint(equalTo: scroll.contentLayoutGuide.topAnchor, constant: 4), stack.bottomAnchor.constraint(equalTo: scroll.contentLayoutGuide.bottomAnchor, constant: -4),182 stack.widthAnchor.constraint(equalTo: scroll.frameLayoutGuide.widthAnchor),183 empty.centerXAnchor.constraint(equalTo: centerXAnchor), empty.centerYAnchor.constraint(equalTo: centerYAnchor),184 empty.leadingAnchor.constraint(greaterThanOrEqualTo: leadingAnchor, constant: 12),185 ])186 registerForTraitChanges([UITraitUserInterfaceStyle.self]) { (view: SlashMenuView, _) in view.applyColours() }187 applyColours()188 }189 required init?(coder: NSCoder) { fatalError("not used") }190191 private func applyColours() { layer.borderColor = NVUIColor.line.resolvedColor(with: traitCollection).cgColor }192193 private var rowHeight: CGFloat { max(Self.rowHeight, UIFontMetrics(forTextStyle: .body).scaledValue(for: Self.rowHeight)) }194 /// One row and a half: enough to see that the list scrolls.195 var minimumHeight: CGFloat { rowHeight * 1.5 + 8 }196 var preferredHeight: CGFloat { shown.isEmpty ? rowHeight + 8 : min(CGFloat(shown.count), Self.visibleRows) * rowHeight + 8 }197 /// Titles shown, in order (tests).198 var titles: [String] { shown.map(\.title) }199200 func update(results: [EditorCommand], selected: Int, query: String) {201 if results != shown {202 shown = results203 rows.forEach { $0.removeFromSuperview() }204 rows = results.map { command in205 let row = SlashMenuRow(command: command, height: rowHeight)206 row.addAction(UIAction { [weak self] _ in self?.onChoose?(command) }, for: .touchUpInside)207 stack.addArrangedSubview(row)208 return row209 }210 }211 empty.isHidden = !results.isEmpty212 for (index, row) in rows.enumerated() { row.isChosen = index == selected }213 if rows.indices.contains(selected) {214 layoutIfNeeded()215 scroll.scrollRectToVisible(rows[selected].frame.insetBy(dx: 0, dy: -4), animated: false)216 }217 }218}219220@MainActor221final class SlashMenuRow: UIControl {222 let command: EditorCommand223 private let tile = UIView()224 var isChosen = false { didSet { backgroundColor = isChosen ? NVUIColor.bgHover : .clear; accessibilityTraits = isChosen ? [.button, .selected] : .button } }225226 init(command: EditorCommand, height: CGFloat) {227 self.command = command228 super.init(frame: .zero)229 isAccessibilityElement = true230 accessibilityLabel = command.title231 accessibilityHint = command.group.title232 accessibilityIdentifier = "slash-" + command.id233 accessibilityTraits = .button234 addInteraction(UIPointerInteraction(delegate: nil))235 tile.backgroundColor = NVUIColor.accentSoft236 tile.layer.cornerRadius = 8237 tile.isUserInteractionEnabled = false238 tile.translatesAutoresizingMaskIntoConstraints = false239 let icon = UIImageView(image: UIImage(systemName: command.symbol, withConfiguration: UIImage.SymbolConfiguration(pointSize: 14, weight: .semibold)))240 icon.tintColor = NVUIColor.accent241 icon.contentMode = .center242 icon.translatesAutoresizingMaskIntoConstraints = false243 let title = UILabel()244 title.text = command.title245 title.font = .preferredFont(forTextStyle: .subheadline)246 title.adjustsFontForContentSizeCategory = true247 title.textColor = NVUIColor.fg248 title.translatesAutoresizingMaskIntoConstraints = false249 let group = UILabel()250 group.text = command.group.title251 group.font = .preferredFont(forTextStyle: .caption2)252 group.adjustsFontForContentSizeCategory = true253 group.textColor = NVUIColor.fgMuted254 group.setContentHuggingPriority(.required, for: .horizontal)255 group.setContentCompressionResistancePriority(.required, for: .horizontal)256 group.translatesAutoresizingMaskIntoConstraints = false257 addSubview(tile); tile.addSubview(icon); addSubview(title); addSubview(group)258 NSLayoutConstraint.activate([259 heightAnchor.constraint(equalToConstant: height),260 tile.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10), tile.centerYAnchor.constraint(equalTo: centerYAnchor),261 tile.widthAnchor.constraint(equalToConstant: 30), tile.heightAnchor.constraint(equalToConstant: 30),262 icon.centerXAnchor.constraint(equalTo: tile.centerXAnchor), icon.centerYAnchor.constraint(equalTo: tile.centerYAnchor),263 title.leadingAnchor.constraint(equalTo: tile.trailingAnchor, constant: 10), title.centerYAnchor.constraint(equalTo: centerYAnchor),264 group.leadingAnchor.constraint(greaterThanOrEqualTo: title.trailingAnchor, constant: 8), group.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12),265 group.centerYAnchor.constraint(equalTo: centerYAnchor),266 ])267 }268 required init?(coder: NSCoder) { fatalError("not used") }269270 override var isHighlighted: Bool { didSet { alpha = isHighlighted ? 0.6 : 1 } }271 /// The text view's own taps (caret placement, atoms) never take a touch that lands on a row.272 override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {273 if gestureRecognizer is UITapGestureRecognizer, gestureRecognizer.view !== self { return false }274 return super.gestureRecognizerShouldBegin(gestureRecognizer)275 }276}277