summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/Extensions/NSAttributedString+Markdown.swift
blob: 173888f6065e5e90d66ab3287edb67700970d066 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//
//  NSAttributedString+Markdown.swift
//  MullvadVPN
//
//  Created by pronebird on 19/11/2021.
//  Copyright © 2021 Mullvad VPN AB. All rights reserved.
//

import UIKit

extension NSAttributedString {
    enum MarkdownElement {
        case bold
    }

    convenience init(
        markdownString: String,
        options: MarkdownStylingOptions,
        applyEffect: ((MarkdownElement, String) -> [NSAttributedString.Key: Any])? = nil
    ) {
        let attributedString = NSMutableAttributedString()
        let paragraphs = markdownString.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n\n")

        for (paragraphIndex, paragraph) in paragraphs.enumerated() {
            let attributedParagraph = NSMutableAttributedString()

            // Replace \n with \u2028 to prevent attributed string from picking up single line breaks as paragraphs.
            let components = paragraph.replacingOccurrences(of: "\n", with: "\u{2028}")
                .components(separatedBy: "**")

            if paragraphIndex > 0 {
                // Add single line break to add spacing between paragraphs.
                attributedParagraph.append(NSAttributedString(string: "\n"))
            }

            for (stringIndex, string) in components.enumerated() {
                var attributes: [NSAttributedString.Key: Any] = [:]

                if stringIndex % 2 == 0 {
                    attributes[.font] = options.font
                } else {
                    attributes[.font] = options.boldFont
                    attributes.merge(applyEffect?(.bold, string) ?? [:], uniquingKeysWith: { $1 })
                }

                attributedParagraph.append(NSAttributedString(string: string, attributes: attributes))
            }

            attributedString.append(attributedParagraph)
        }

        attributedString.addAttribute(
            .paragraphStyle,
            value: options.paragraphStyle,
            range: NSRange(location: 0, length: attributedString.length)
        )

        self.init(attributedString: attributedString)
    }
}