Skip to content
Merged
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
47 changes: 47 additions & 0 deletions Sources/TextBuilder/TextBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,52 @@ import SwiftUI
/// Text("amet, consectetur")
/// }
///
#if compiler(>=5.7)
@resultBuilder
public struct TextBuilder<Separator: TextBuilderSeparator> {
public static func buildPartialBlock(first: Text) -> Text {
first
}

public static func buildPartialBlock(accumulated: Text, next: Text) -> Text {
if next.isNone {
return accumulated
} else if Separator.separator.isEmpty {
return accumulated + next
} else {
return accumulated + Text(Separator.separator) + next
}
}

public static func buildArray(_ components: [Text]) -> Text {
components.joined(separator: Text(Separator.separator))
}

public static func buildEither(first component: Text) -> Text {
component
}

public static func buildEither(second component: Text) -> Text {
component
}

public static func buildExpression(_ string: some StringProtocol) -> Text {
Text(string)
}

public static func buildExpression(_ component: Text) -> Text {
component
}

public static func buildLimitedAvailability(_ component: Text) -> Text {
component
}

public static func buildOptional(_ component: Text?) -> Text {
component ?? Text.none
}
}
#else
@resultBuilder
public struct TextBuilder<Separator: TextBuilderSeparator> {
public static func buildArray(_ texts: [[Text]]) -> [Text] {
Expand Down Expand Up @@ -57,3 +103,4 @@ public struct TextBuilder<Separator: TextBuilderSeparator> {
texts.joined(separator: Text(Separator.separator))
}
}
#endif
19 changes: 19 additions & 0 deletions Tests/TextBuilderTests/TextBuilderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,24 @@ final class TextBuilderTests: XCTestCase {
}

func testComplexTextBuilder() {
#if compiler(>=5.7)
XCTAssertNoDifference(
complexTextBuilderText(),
Text(verbatim: "Lorem").underline().foregroundColor(.blue) +
Text(verbatim: " ") +
Text(verbatim: "sit").bold() +
Text(verbatim: " ") +
Text(verbatim: "amet, consectetur") +
Text(verbatim: " ") +
(
Text(verbatim: "1") +
Text(verbatim: " ") +
Text(verbatim: "2") +
Text(verbatim: " ") +
Text(verbatim: "3")
)
)
#else
XCTAssertNoDifference(
complexTextBuilderText(),
Text(verbatim: "Lorem").underline().foregroundColor(.blue) +
Expand All @@ -69,6 +87,7 @@ final class TextBuilderTests: XCTestCase {
Text(verbatim: " ") +
Text(verbatim: "3")
)
#endif
}
}

Expand Down