Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bugfix - Multi level list #54

Merged
merged 4 commits into from
Jan 26, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions MarkdownKit/Sources/Common/Elements/List/MarkdownList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Foundation

open class MarkdownList: MarkdownLevelElement {

fileprivate static let regex = "^([\\*\\+\\-]{1,%@})\\s+(.+)$"
fileprivate static let regex = "^( {0,%@}[\\*\\+\\-])\\s+(.+)$"

open var maxLevel: Int
open var font: MarkdownFont?
Expand All @@ -22,7 +22,7 @@ open class MarkdownList: MarkdownLevelElement {
return String(format: MarkdownList.regex, level)
}

public init(font: MarkdownFont? = nil, maxLevel: Int = 0, indicator: String = "",
public init(font: MarkdownFont? = nil, maxLevel: Int = 6, indicator: String = "",
separator: String = " ", color: MarkdownColor? = nil) {
self.maxLevel = maxLevel
self.indicator = indicator
Expand All @@ -32,10 +32,20 @@ open class MarkdownList: MarkdownLevelElement {
}

open func formatText(_ attributedString: NSMutableAttributedString, range: NSRange, level: Int) {
var string = (0..<level).reduce("") { (string, _) -> String in
return "\(string)\(separator)"
}
string = "\(string)\(indicator) "
attributedString.replaceCharacters(in: range, with: string)
let levelIndicatorList = [1: "\(indicator) ", 2: "\(indicator) ", 3: "◦ ", 4: "◦ ", 5: "▪︎ ", 6: "▪︎ "]
let levelIndicatorOffsetList = [1: "", 2: "", 3: " ", 4: " ", 5: " ", 6: " "]
guard let indicatorIcon = levelIndicatorList[level],
let offset = levelIndicatorOffsetList[level] else { return }
let indicator = "\(offset)\(indicatorIcon)"
attributedString.replaceCharacters(in: range, with: indicator)
attributedString.addAttributes([.paragraphStyle : defaultParagraphStyle()], range: range)
}

private func defaultParagraphStyle() -> NSMutableParagraphStyle {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 0
paragraphStyle.headIndent = 16
paragraphStyle.paragraphSpacing = 4
return paragraphStyle
}
}