| 1 | import Foundation |
| 2 | |
| 3 | /// Only read formatting from a selection whose projection has caught up with |
| 4 | /// native text input. While it catches up, the toolbar keeps its last valid state. |
| 5 | struct DocumentToolbarSelection: Equatable { |
| 6 | var marks: Set<String> = [] |
| 7 | var blocks: Set<String> = [] |
| 8 | var style = "paragraph" |
| 9 | /// The key of the family the selection is in: Carlito when no font mark is set. |
| 10 | var font = DocsFonts.defaultFamily.key |
| 11 | var size = 12 |
| 12 | var alignment = "left" |
| 13 | var canUndo = false |
| 14 | var canRedo = false |
| 15 | var hasSelection = false |
| 16 | |
| 17 | var styleLabel: String { |
| 18 | if style.hasPrefix("heading"), let level = Int(style.dropFirst(7)) { |
| 19 | return String(format: docsMacString("Heading %d"), level) |
| 20 | } |
| 21 | return String(localized: "docs.editor.toolbar.block.paragraph", bundle: DocsResources.bundle) |
| 22 | } |
| 23 | init() {} |
| 24 | |
| 25 | @MainActor init?(commands: DocumentCommands) { |
| 26 | guard commands.isEnabled else { return nil } |
| 27 | // The marks and the block path once each: this runs on every key. |
| 28 | let active = commands.activeMarks |
| 29 | let path = commands.selectedPath |
| 30 | marks = Set(["strong", "em", "code"].filter { active.contains($0) }) |
| 31 | blocks = Set(["bullet_list", "ordered_list", "blockquote"].filter { type in path?.contains { $0.type == type } == true }) |
| 32 | if let block = path?.last { |
| 33 | style = block.type == "heading" ? "heading" + (block.attrs?["level"] ?? "1") : "paragraph" |
| 34 | alignment = block.attrs?["align"] ?? "left" |
| 35 | } |
| 36 | font = DocsFonts.family(forMarkNames: DocsFonts.marks.filter { active.contains($0) }).key |
| 37 | size = [8,9,10,11,12,14,18,24,36,48,72].first { active.contains("size_\($0)") } ?? (active.contains("size_sm") ? 10 : active.contains("size_lg") ? 14 : active.contains("size_xl") ? 18 : 12) |
| 38 | canUndo = commands.model.projection?.canUndo == true |
| 39 | canRedo = commands.model.projection?.canRedo == true |
| 40 | hasSelection = commands.model.selection.length > 0 |
| 41 | } |
| 42 | } |
| 43 | |