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

Added SwiftUITextOutputFormat to output a Text struct #92

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions Sources/Splash/Output/AttributedStringOutputFormat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

#if !os(Linux)
#if canImport(SwiftUI)

import Foundation

Expand Down Expand Up @@ -65,3 +66,4 @@ private extension NSMutableAttributedString {
}

#endif
#endif
81 changes: 81 additions & 0 deletions Sources/Splash/Output/SwiftUITextOutputFormat.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
//
// SwiftUITextOutputFormat.swift
//
// Created by Andrew Eades on 02/01/2020.
// Copyright © 2020 Andrew Eades. All rights reserved.
//


#if !os(Linux)
#if canImport(SwiftUI)

import SwiftUI

import Foundation

/// Output format to use to generate an NSAttributedString from the
/// highlighted code. A `Theme` is used to determine what fonts and
/// colors to use for the various tokens.
public struct SwiftUITextOutputFormat: OutputFormat {
public var theme: Theme

public init(theme: Theme) {
self.theme = theme
}

public func makeBuilder() -> Builder {
return Builder(theme: theme)
}
}

public extension SwiftUITextOutputFormat {
struct Builder: OutputBuilder {
private let theme: Theme
private var texts = [Text]()

fileprivate init(theme: Theme) {
self.theme = theme
}

public mutating func addToken(_ token: String, ofType type: TokenType) {
let tokenColor = swiftUIColor(forType: type)

texts.append(Text(token).foregroundColor(tokenColor))
}

public mutating func addPlainText(_ plainText: String) {
let tokenColor = SwiftUI.Color(theme.plainTextColor)

texts.append(Text(plainText).foregroundColor(tokenColor))
}

public mutating func addWhitespace(_ whitespace: String) {
let tokenColor = SwiftUI.Color.white

texts.append(Text(whitespace).foregroundColor(tokenColor))
}

public func build() -> Text {

let highlightedText = texts.reduce(Text(""), +)

return highlightedText
}

private func swiftUIColor(forType type: TokenType) -> SwiftUI.Color {
var tokenColor: SwiftUI.Color

if let color = theme.tokenColors[type] {
tokenColor = SwiftUI.Color(color)
} else {
tokenColor = SwiftUI.Color.white
}

return tokenColor
}

}
}

#endif
#endif