| 1 | import Foundation |
| 2 | |
| 3 | /// A flat list of layout rows. Depth changes indentation, never view nesting. |
| 4 | /// Indentation stops at four levels so deeply nested replies remain readable |
| 5 | /// at phone width; every item and all of its content are still present. |
| 6 | enum MarkdownPresentation { |
| 7 | static func pasteLabel(_ node: ChatMarkdownNode) -> String { node.label ?? String(localized: "chat.paste.text", bundle: .module) } |
| 8 | struct Row: Identifiable { |
| 9 | var node: ChatMarkdownNode |
| 10 | var indentation: Int |
| 11 | var marker: String? |
| 12 | var id: Int { node.sourceOffset } |
| 13 | } |
| 14 | static func groups(_ nodes: [ChatMarkdownNode]) -> [ChatMarkdownNode] { |
| 15 | var out: [ChatMarkdownNode] = [] |
| 16 | for node in nodes { |
| 17 | if ["text", "emphasis", "strong", "link", "code", "break"].contains(node.kind) { |
| 18 | if out.last?.kind == "inlineGroup" { out[out.count - 1].children.append(node) } |
| 19 | else { out.append(ChatMarkdownNode(sourceOffset: node.sourceOffset, kind: "inlineGroup", children: [node])) } |
| 20 | } else { out.append(node) } |
| 21 | } |
| 22 | return out |
| 23 | } |
| 24 | static func rows(_ nodes: [ChatMarkdownNode]) -> [Row] { |
| 25 | var stack = groups(nodes).reversed().map { Row(node: $0, indentation: 0, marker: nil) } |
| 26 | var out: [Row] = [] |
| 27 | while let row = stack.popLast() { |
| 28 | if ["unordered", "ordered"].contains(row.node.kind) { |
| 29 | for (index, item) in row.node.children.enumerated().reversed() { |
| 30 | let children = groups(item.children) |
| 31 | for (offset, child) in children.enumerated().reversed() { |
| 32 | stack.append(Row(node: child, indentation: row.indentation + 1, |
| 33 | marker: offset == 0 ? (row.node.kind == "ordered" ? "\(index + 1)." : "•") : nil)) |
| 34 | } |
| 35 | } |
| 36 | } else { |
| 37 | var visible = row |
| 38 | visible.indentation = min(4, max(0, row.indentation - 1)) |
| 39 | out.append(visible) |
| 40 | } |
| 41 | } |
| 42 | return out |
| 43 | } |
| 44 | } |
| 45 | |