| 1 | import Foundation |
| 2 | |
| 3 | @MainActor struct DocumentCommands { |
| 4 | let model: DocsModel |
| 5 | let content: NSAttributedString |
| 6 | var isAvailable: Bool { model.detail?.can_write == true && !model.inputBlocked } |
| 7 | var isEnabled: Bool { |
| 8 | isAvailable && !model.composing && !model.hasPendingInput |
| 9 | && model.renderedGeneration == model.projectionGeneration |
| 10 | } |
| 11 | func hasMark(_ name: String) -> Bool { activeMarks.contains(name) } |
| 12 | /// Every mark `hasMark` finds at the selection: at a caret, the typing |
| 13 | /// marks or those the caret would type with; over a range, any mark any |
| 14 | /// of its runs has. Read once for the toolbar's whole state. |
| 15 | var activeMarks: Set<String> { |
| 16 | guard validSelection else { return [] } |
| 17 | if model.selection.length == 0 { return Set((model.typingMarks ?? marksAtCaret).keys) } |
| 18 | var active = Set<String>() |
| 19 | var seen = Set<Data>() |
| 20 | content.enumerateAttribute(.docsMarks, in: model.selection) { value, _, _ in |
| 21 | if let data = value as? Data, seen.insert(data).inserted, |
| 22 | let marks = try? JSONDecoder().decode([String: JSONValue].self, from: data) { |
| 23 | active.formUnion(marks.keys) |
| 24 | } |
| 25 | } |
| 26 | return active |
| 27 | } |
| 28 | var selectedBlock: CRDTNode? { selectedBlocks.first.flatMap { path(to: $0)?.last } } |
| 29 | func hasBlock(_ type: String) -> Bool { |
| 30 | guard let id = selectedBlocks.first else { return false } |
| 31 | return path(to: id)?.contains { $0.type == type } == true |
| 32 | } |
| 33 | /// The path to the selection's first block (the toolbar's whole state |
| 34 | /// reads it once). |
| 35 | var selectedPath: [CRDTNode]? { selectedBlocks.first.flatMap { path(to: $0) } } |
| 36 | @discardableResult func perform(_ action: String) -> Bool { |
| 37 | guard isEnabled else { return false } |
| 38 | switch action { |
| 39 | case "bold": return format("strong") |
| 40 | case "italic": return format("em") |
| 41 | case "code": return format("code") |
| 42 | case "undo": return model.projection?.canUndo == true && model.enqueue(["op": .string("undo")]) |
| 43 | case "redo": return model.projection?.canRedo == true && model.enqueue(["op": .string("redo")]) |
| 44 | case "indent": return indent(1) |
| 45 | case "outdent": return indent(-1) |
| 46 | case "hard-break": |
| 47 | guard let command = TextEditMapping.displayCommand(in: content, range: model.selection, replacement: "\u{2028}") else { return false } |
| 48 | return model.enqueue(command) |
| 49 | case "clear-format": return clearFormatting() |
| 50 | default: return false |
| 51 | } |
| 52 | } |
| 53 | /// Sets a mark, or, with an exclusive group, replaces whichever of the |
| 54 | /// group is set. 12 pt is the default size and is spelled as no size |
| 55 | /// mark. Fonts go through setFont, which knows the default family. |
| 56 | @discardableResult func format(_ name: String, exclusive: [String] = []) -> Bool { |
| 57 | applyMark(name == "size_12" ? nil : name, exclusive: exclusive) |
| 58 | } |
| 59 | /// The font picker's command, as the web's pickFont/fontMark: the |
| 60 | /// default (Carlito) clears every font mark, any other family replaces |
| 61 | /// them with its own, and Sans is font_sans like any other family. A |
| 62 | /// family this build does not know changes nothing. |
| 63 | @discardableResult func setFont(_ key: String) -> Bool { |
| 64 | guard case .some(let mark) = DocsFonts.mark(forPick: key) else { return false } |
| 65 | return applyMark(mark, exclusive: DocsFonts.marks) |
| 66 | } |
| 67 | private func applyMark(_ name: String?, exclusive: [String]) -> Bool { |
| 68 | guard isEnabled, validSelection else { return false } |
| 69 | var marks = model.typingMarks ?? marksAtCaret |
| 70 | var applied: [String: JSONValue] = [:] |
| 71 | for key in exclusive { marks.removeValue(forKey: key); applied[key] = .null } |
| 72 | if let name { |
| 73 | if hasMark(name) && exclusive.isEmpty { marks.removeValue(forKey: name); applied[name] = .null } |
| 74 | else { marks[name] = .object([:]); applied[name] = .object([:]) } |
| 75 | } |
| 76 | if model.selection.length == 0 { model.typingMarks = marks; return true } |
| 77 | return submit(Self.markCommands(content: content, selection: model.selection, marks: applied)) |
| 78 | } |
| 79 | @discardableResult func block(_ type: String, level: Int = 1) -> Bool { |
| 80 | guard isEnabled else { return false } |
| 81 | if ["bullet_list", "ordered_list"].contains(type) { |
| 82 | return submit(Self.listCommands(type: type, paths: selectedBlocks.compactMap { path(to: $0) })) |
| 83 | } |
| 84 | let blocks = selectedBlocks.filter { id in |
| 85 | guard let node = path(to: id)?.last else { return false } |
| 86 | return !["paragraph", "heading", "code_block"].contains(type) |
| 87 | || ["paragraph", "heading", "code_block"].contains(node.type) |
| 88 | } |
| 89 | let ordered = type == "blockquote" ? Array(blocks.reversed()) : blocks |
| 90 | return submit(ordered.map { ["op": .string("block"), "node": .string($0), "type": .string(type), "level": .number(Double(level))] }) |
| 91 | } |
| 92 | /// A list conversion replaces its descendants. Convert each containing list |
| 93 | /// once; lift items from the end so copied trailing items are never targets. |
| 94 | static func listCommands(type: String, paths: [[CRDTNode]]) -> [[String: JSONValue]] { |
| 95 | var converted = Set<String>() |
| 96 | var lifted = Set<String>() |
| 97 | return paths.reversed().compactMap { path in |
| 98 | guard let block = path.last else { return nil } |
| 99 | if let list = path.last(where: { ["bullet_list", "ordered_list"].contains($0.type) }) { |
| 100 | if list.type != type { |
| 101 | guard converted.insert(list.id).inserted else { return nil } |
| 102 | } else if let item = path.last(where: { $0.type == "list_item" }) { |
| 103 | guard lifted.insert(item.id).inserted else { return nil } |
| 104 | } |
| 105 | } |
| 106 | return ["op": .string("block"), "node": .string(block.id), "type": .string(type)] |
| 107 | } |
| 108 | } |
| 109 | @discardableResult func blockAttribute(_ name: String, value: String?) -> Bool { |
| 110 | guard isEnabled else { return false } |
| 111 | let blocks = selectedBlocks.filter { id in |
| 112 | guard let node = path(to: id)?.last else { return false } |
| 113 | return name != "align" || node.type == "paragraph" |
| 114 | } |
| 115 | return submit(blocks.map { ["op": .string("attribute"), "node": .string($0), "name": .string(name), "value": value.map(JSONValue.string) ?? .null] }) |
| 116 | } |
| 117 | private var validSelection: Bool { |
| 118 | model.selection.location >= 0 && model.selection.length >= 0 |
| 119 | && model.selection.location <= content.length && model.selection.length <= content.length - model.selection.location |
| 120 | } |
| 121 | private var marksAtCaret: [String: JSONValue] { |
| 122 | TextEditMapping.marks(in: content, at: model.selection.location) |
| 123 | } |
| 124 | private var selectedBlocks: [String] { |
| 125 | guard validSelection, content.length > 0 else { return [] } |
| 126 | let range = model.selection.length == 0 ? NSRange(location: min(model.selection.location, content.length - 1), length: 1) : model.selection |
| 127 | var found: [String] = [] |
| 128 | content.enumerateAttribute(.docsBlock, in: range) { value, _, _ in |
| 129 | if let id = value as? String, !found.contains(id) { found.append(id) } |
| 130 | } |
| 131 | return found |
| 132 | } |
| 133 | static func markCommands(content: NSAttributedString, selection: NSRange, marks: [String: JSONValue]) -> [[String: JSONValue]] { |
| 134 | var commands: [[String: JSONValue]] = [] |
| 135 | content.enumerateAttribute(.docsNode, in: selection) { value, range, _ in |
| 136 | guard value is String, content.attribute(.docsMarks, at: range.location, effectiveRange: nil) is Data, var command = TextEditMapping.command(in: content, range: range, replacement: "") else { return } |
| 137 | command["op"] = .string("format"); command["marks"] = .object(marks); command.removeValue(forKey: "text") |
| 138 | commands.append(command) |
| 139 | } |
| 140 | return commands |
| 141 | } |
| 142 | private func clearFormatting() -> Bool { |
| 143 | guard validSelection, model.selection.length > 0 else { return false } |
| 144 | var removed: [String: JSONValue] = [:] |
| 145 | content.enumerateAttribute(.docsMarks, in: model.selection) { value, _, _ in |
| 146 | if let data = value as? Data, let marks = try? JSONDecoder().decode([String: JSONValue].self, from: data) { |
| 147 | for name in marks.keys { removed[name] = .null } |
| 148 | } |
| 149 | } |
| 150 | var commands = Self.markCommands(content: content, selection: model.selection, marks: removed) |
| 151 | for id in selectedBlocks { |
| 152 | guard let node = path(to: id)?.last, ["paragraph", "heading", "code_block"].contains(node.type) else { continue } |
| 153 | for name in ["align", "indent"] { commands.append(["op": .string("attribute"), "node": .string(id), "name": .string(name), "value": .null]) } |
| 154 | commands.append(["op": .string("block"), "node": .string(id), "type": .string("paragraph")]) |
| 155 | } |
| 156 | return submit(commands) |
| 157 | } |
| 158 | private func indent(_ delta: Int) -> Bool { |
| 159 | var commands: [[String: JSONValue]] = [] |
| 160 | var lists = Set<String>() |
| 161 | let blocks = delta < 0 ? Array(selectedBlocks.reversed()) : selectedBlocks |
| 162 | for id in blocks { |
| 163 | guard let path = path(to: id), let node = path.last else { continue } |
| 164 | if let item = path.last(where: { $0.type == "list_item" }) { |
| 165 | if lists.insert(item.id).inserted { |
| 166 | commands.append(["op": .string("list_indent"), "node": .string(id), "delta": .number(Double(delta))]) |
| 167 | } |
| 168 | } else if ["paragraph", "heading"].contains(node.type) { |
| 169 | let current = max(0, min(8, Int(node.attrs?["indent"] ?? "0") ?? 0)) |
| 170 | let next = max(0, min(8, current + delta)) |
| 171 | if next != current { commands.append(["op": .string("attribute"), "node": .string(id), "name": .string("indent"), "value": next == 0 ? .null : .string(String(next))]) } |
| 172 | } |
| 173 | } |
| 174 | return submit(commands) |
| 175 | } |
| 176 | /// The nodes from the top level down to `id`. Searched first in the |
| 177 | /// top-level block the selection is in (`.docsTopBlock`), so the |
| 178 | /// toolbar's state, read on every key, costs one block and not the |
| 179 | /// document; then everywhere, as before. |
| 180 | private func path(to id: String) -> [CRDTNode]? { |
| 181 | func search(_ nodes: [CRDTNode], _ path: inout [CRDTNode]) -> Bool { |
| 182 | for node in nodes { |
| 183 | path.append(node) |
| 184 | if node.id == id || search(node.children ?? [], &path) { return true } |
| 185 | path.removeLast() |
| 186 | } |
| 187 | return false |
| 188 | } |
| 189 | let children = model.projection?.children ?? [] |
| 190 | var path: [CRDTNode] = [] |
| 191 | if validSelection, content.length > 0, |
| 192 | let top = content.attribute(.docsTopBlock, at: min(model.selection.location, content.length - 1), effectiveRange: nil) as? String, |
| 193 | let block = children.first(where: { $0.id == top }), search([block], &path) { |
| 194 | return path |
| 195 | } |
| 196 | path = [] |
| 197 | return search(children, &path) ? path : nil |
| 198 | } |
| 199 | private func submit(_ commands: [[String: JSONValue]]) -> Bool { |
| 200 | guard !commands.isEmpty else { return false } |
| 201 | return model.enqueue(["op": .string("batch"), "commands": .array(commands.map(JSONValue.object))]) |
| 202 | } |
| 203 | } |
| 204 | |