### Swift: Choosing Appropriate Rainbow APIs Source: https://github.com/onevcat/rainbow/blob/master/PERFORMANCE_GUIDE.md Provides examples of selecting the correct Rainbow API in Swift based on the complexity of styling required. Options range from simple properties for single styles to batch operations for multiple styles and the builder pattern for complex chaining. ```swift // Single style - use simple properties let simple = "Error".red // Multiple styles - use batch operations let multiple = "Warning".applyingAll( color: .named(.yellow), backgroundColor: .named(.black), styles: [.bold, .underline] ) // Complex chaining - use builder pattern let complex = "Success".styled .green .bold .onBlack .underline .build() // Performance-critical code - use direct Rainbow API let direct = Rainbow.generateString(for: entry) ``` -------------------------------- ### Swift User-Defined Style Presets Example Source: https://github.com/onevcat/rainbow/blob/master/IMPROVEMENT_ROADMAP.md An example in Swift demonstrating how users can easily define their own style presets for text coloring and styling, addressing the rejection of the original proposal for static style presets. ```swift // User-defined extension extension String { var error: String { self.red.bold } var success: String { self.green } } ``` -------------------------------- ### Swift: Use Batch Operations for Multiple Styles Source: https://github.com/onevcat/rainbow/blob/master/PERFORMANCE_GUIDE.md This Swift code example shows how to use batch operations to apply multiple styles efficiently, available in v4.2.0+. This method is generally more performant than chaining individual style modifiers. ```swift // Old let old = "text".red.bold.italic // New let new = "text".applyingAll(color: .named(.red), styles: [.bold, .italic]) ``` -------------------------------- ### Swift Basic Conditional Styling Source: https://github.com/onevcat/rainbow/blob/master/IMPROVEMENT_ROADMAP.md Examples of basic conditional styling in Swift using Rainbow, demonstrating how to apply colors and styles based on boolean conditions. ```swift let errorMessage = "Error occurred" .colorIf(isError, .red) .styleIf(isError, .bold) ``` -------------------------------- ### Bash: Running Rainbow Performance Tests Source: https://github.com/onevcat/rainbow/blob/master/PERFORMANCE_GUIDE.md Provides bash commands for executing performance tests within the Rainbow project. These commands allow users to run all performance tests or target specific tests for benchmarking purposes. ```bash # Run all performance tests swift test --filter PerformanceTests # Run specific performance tests swift test --filter PerformanceTests.testBuilderPatternPerformance swift test --filter PerformanceTests.testBatchOperationPerformance ``` -------------------------------- ### Swift: Using Different Color Types in Rainbow Source: https://github.com/onevcat/rainbow/blob/master/PERFORMANCE_GUIDE.md Shows how to apply different color types in Swift using the Rainbow library for terminal output. Examples include standard named colors for maximum compatibility, 256-color (`bit8`), and true-color (`bit24`) for advanced terminals. ```swift // For maximum compatibility let compatible = "text".red // For 256-color terminals let enhanced = "text".bit8(196) // For true-color terminals (use sparingly) let truecolor = "text".bit24(255, 64, 128) ``` -------------------------------- ### Swift: Batch Operations for Multiple Styles Source: https://github.com/onevcat/rainbow/blob/master/PERFORMANCE_GUIDE.md Illustrates the performance difference between applying styles individually and using batch operations. Batch operations (`applyingAll`) in Swift parse and generate the styled string in a single cycle, significantly improving efficiency. ```swift // ❌ Inefficient - multiple parsing and generation cycles let slow = "Hello".red.bold.underline.italic // ✅ Efficient - single parsing and generation cycle let fast = "Hello".applyingAll( color: .named(.red), styles: [.bold, .underline, .italic] ) ``` -------------------------------- ### Swift Package Manager Installation for Rainbow (Swift) Source: https://github.com/onevcat/rainbow/blob/master/README.md Provides the Swift code snippet for adding the Rainbow library as a dependency in a Swift Package Manager `Package.swift` file. This allows for cross-platform software development using Swift. ```swift import PackageDescription let package = Package( name: "YourAwesomeSoftware", dependencies: [ .package(url: "https://github.com/onevcat/Rainbow", .upToNextMajor(from: "4.0.0")) ], targets: [ .target( name: "MyApp", dependencies: ["Rainbow"]) ] ) ``` -------------------------------- ### Verbose Styling with Rainbow in Swift Source: https://github.com/onevcat/rainbow/blob/master/README.md Presents a more explicit way to apply multiple colors and styles to strings using Rainbow in Swift. It includes an example using the `applyingCodes` method and another demonstrating the construction of `Rainbow.Entry` objects for fine-grained control over text segments, colors, backgrounds, and styles. This approach is recommended for performance-critical scenarios or when dealing with large strings. ```swift import Rainbow let output = "The quick brown fox jumps over the lazy dog" .applyingCodes(Color.red, BackgroundColor.yellow, Style.bold) print(output) // Red text on yellow, bold of course :) ``` ```swift let entry = Rainbow.Entry( segments: [ .init(text: "Hello ", color: .named(.magenta)), .init(text: "Rainbow", color: .bit8(214), backgroundColor: .named(.lightBlue), styles: [.underline]), ] ) print(Rainbow.generateString(for: entry)) ``` -------------------------------- ### Swift: Batch Processing Multiple Strings Source: https://github.com/onevcat/rainbow/blob/master/PERFORMANCE_GUIDE.md Compares inefficient individual string processing with more performant batch operations in Swift. Using the builder pattern or `applyingAll` for multiple strings with the same styles can significantly improve efficiency compared to mapping with individual styling. ```swift // ❌ Process strings individually let results = strings.map { $0.red.bold } // ✅ Use builder pattern for better performance let results = strings.map { $0.styled.red.bold.build() } // ✅ Even better - use batch operations if styles are the same let results = strings.map { $0.applyingAll(color: .named(.red), styles: [.bold]) } ``` -------------------------------- ### Swift: Custom String Generation with Rainbow Internal APIs Source: https://github.com/onevcat/rainbow/blob/master/PERFORMANCE_GUIDE.md This Swift code illustrates how to use Rainbow's internal APIs for custom string generation, providing maximum performance in specific scenarios by directly creating an Entry and generating the string. ```swift // Create entry directly let entry = Rainbow.Entry(segments: [ .init(text: "Hello", color: .named(.red), styles: [.bold]) ]) // Generate string directly let result = Rainbow.generateString(for: entry) ``` -------------------------------- ### Swift: Builder Pattern for Efficient Styling Source: https://github.com/onevcat/rainbow/blob/master/PERFORMANCE_GUIDE.md Demonstrates the inefficient traditional chaining versus the optimized builder pattern (`StyledStringBuilder`) for applying multiple text styles in Swift. The builder pattern reduces intermediate string allocations, leading to significant performance gains. ```swift // ❌ Inefficient - creates 4 intermediate strings let slow = "Hello".red.bold.underline.onBlue // ✅ Efficient - lazy evaluation, single string generation let fast = "Hello".styled.red.bold.underline.onBlue.build() ``` -------------------------------- ### Swift: Replace Chained Calls with Builder Pattern Source: https://github.com/onevcat/rainbow/blob/master/PERFORMANCE_GUIDE.md This snippet demonstrates how to replace old chained styling calls with the new builder pattern in Swift, available from v4.2.0 onwards. The builder pattern offers a more performant way to apply multiple styles. ```swift // Old let old = "text".red.bold.underline // New let new = "text".styled.red.bold.underline.build() ``` -------------------------------- ### Swift Gradient Text Function Proposal Source: https://github.com/onevcat/rainbow/blob/master/IMPROVEMENT_ROADMAP.md A proposed Swift extension function for applying gradient effects to text, taking start and end colors as parameters. ```swift extension String { func gradient(from: ColorType, to: ColorType) -> String { // Apply gradient across characters } } ``` -------------------------------- ### Swift: Avoiding Repeated Parsing of Strings Source: https://github.com/onevcat/rainbow/blob/master/PERFORMANCE_GUIDE.md Demonstrates a performance anti-pattern in Swift where the same string is repeatedly styled within a loop, leading to inefficient parsing and generation. The recommended approach is to style a template once and reuse it, applying it to different data. ```swift // ❌ Don't repeatedly style the same string for i in 0..<1000 { print("Item \(i)".red.bold) // Parses and generates 1000 times } // ✅ Style once, reuse the format let template = "Item %@".applyingAll(color: .named(.red), styles: [.bold]) for i in 0..<1000 { print(String(format: template, "\(i)")) // Only formats the number } ``` -------------------------------- ### Maintain Backward Compatibility with Deprecation Warnings (Swift) Source: https://github.com/onevcat/rainbow/blob/master/IMPROVEMENT_ROADMAP.md This Swift code demonstrates how to maintain backward compatibility when renaming or refactoring API methods. It uses type aliases and the `@available` attribute with a `deprecated` and `renamed` parameter to warn users about the old method and guide them to the new one. ```swift public extension String { @available(*, deprecated, renamed: "color256") func bit8(_ color: UInt8) -> String { return color256(color) } @available(*, deprecated, renamed: "trueColor") func bit24(_ r: UInt8, _ g: UInt8, _ b: UInt8) -> String { return trueColor(r, g, b) } } ``` -------------------------------- ### Extract Raw Text from Styled Strings Source: https://context7.com/onevcat/rainbow/llms.txt Extracts plain text from styled terminal strings by stripping all ANSI escape codes. Useful for getting the actual content for display or length calculations, ignoring styling. Can also extract entry information like plain text and whether it's plain. ```swift import Rainbow // Get raw text without any styling let styledText = "Error message".red.bold.underline let rawText = styledText.raw print("Raw: \(rawText)") // Output: "Error message" // Useful for string length calculations let message = "Progress: 50%".green.bold let actualLength = message.raw.count // 13, not counting ANSI codes print("Length: \(actualLength)") // Extract plain text from complex nested strings let complex = "Status: \(\"OK\".green.bold) | Count: \(\"42\".yellow)" print(complex.raw) // Output: "Status: OK | Count: 42" // Get entry information let entry = Rainbow.extractEntry(for: styledText) print("Plain text: \(entry.plainText)") print("Is plain: \(entry.isPlain)") ``` -------------------------------- ### Basic Text Styling with Rainbow (Swift) Source: https://github.com/onevcat/rainbow/blob/master/README.md Demonstrates the basic usage of the Rainbow library in Swift, utilizing String extensions to apply named colors, background colors, and text styles like underline, bold, and blink. It also shows how to reset styles. ```swift import Rainbow print("Red text".red) print("Blue background".onBlue) print("Light green text on white background".lightGreen.onWhite) print("Underline".underline) print("Cyan with bold and blinking".cyan.bold.blink) print("Plain text".red.onYellow.bold.clearColor.clearBackgroundColor.clearStyles) ``` -------------------------------- ### Rainbow Performance Optimizations: Builder Pattern & Batch Operations (Swift) Source: https://github.com/onevcat/rainbow/blob/master/README.md Illustrates Rainbow's performance optimizations in Swift. The builder pattern (`.styled...build()`) is shown for efficient complex styling, and batch operations (`.applyingAll()`) are demonstrated for applying multiple styles in a single operation. ```swift // Traditional chaining - creates multiple intermediate strings let traditional = "Hello".red.bold.underline.onBlue // Optimized builder pattern - lazy evaluation, single string generation let optimized = "Hello".styled.red.bold.underline.onBlue.build() // Traditional - multiple parsing cycles let traditionalBatch = "Warning".red.bold.underline.italic // Optimized - single parsing cycle let optimizedBatch = "Warning".applyingAll( color: .named(.red), styles: [.bold, .underline, .italic] ) ``` -------------------------------- ### Controlling Rainbow Output Target in Shell Source: https://github.com/onevcat/rainbow/blob/master/README.md Demonstrates how Rainbow automatically detects output targets and handles piping to files. It also explains manual control methods: setting `Rainbow.enabled` in code, using environment variables `FORCE_COLOR=1` or `NO_COLOR=1`, and explicitly setting `Rainbow.outputTarget`. ```sh # main.swift print("Hello Rainbow".red) $ .build/debug/RainbowDemo > output.txt # output.txt Hello Rainbow ``` -------------------------------- ### Swift Style Presets Proposal (Rejected) Source: https://github.com/onevcat/rainbow/blob/master/IMPROVEMENT_ROADMAP.md This Swift code snippet was a proposal for defining style presets using static let properties returning closures. It was rejected due to API inconsistency and lack of user flexibility, as users can easily define their own presets. ```swift extension String { static let errorStyle = { $0.red.bold } static let successStyle = { $0.green } static let warningStyle = { $0.yellow } static let infoStyle = { $0.cyan } } // Usage print("Error: File not found".errorStyle()) ``` -------------------------------- ### Rainbow ANSI 256-Color Mode Usage (Swift) Source: https://github.com/onevcat/rainbow/blob/master/README.md Shows how to use Rainbow's support for ANSI 8-bit (256-color) mode in Swift for both text and background colors. It demonstrates applying specific 256-color codes to console output. ```swift print("停车坐爱\("枫林晚".bit8(31)),\("霜叶".bit8(160))红于\("二月花".bit8(198))。") print("\("一道残阳".bit8(202))铺水中,\("半江瑟瑟".bit8(30).onBit8(226))半江红。") ``` -------------------------------- ### Rainbow String Interpolation and Nested Styling (Swift) Source: https://github.com/onevcat/rainbow/blob/master/README.md Demonstrates advanced usage of Rainbow in Swift, showcasing string interpolation for applying styles to specific parts of a string and creating nested colorful strings where inner styles are preserved. ```swift print("接天莲叶\("无穷碧".green),映日荷花\("别样红".red)") print("\("两只黄鹂".yellow)鸣翠柳,一行白鹭\("上青天".lightBlue)。".lightGreen.underline) ``` -------------------------------- ### Swift: Optimized Batch Style Application with Rainbow Source: https://context7.com/onevcat/rainbow/llms.txt Applies multiple styles (color, background, text styles) to a string in a single parsing cycle using Rainbow's `applyingAll` and `applyingStyles` methods. This is more performant than traditional chained styling, especially within loops. It handles optional parameters and demonstrates color, background, and style combinations. ```swift import Rainbow // Traditional - multiple parsing cycles let traditional = "Warning".red.bold.underline.italic // Optimized - single parsing cycle with applyingAll let optimized = "Warning".applyingAll( color: .named(.red), backgroundColor: nil, styles: [.bold, .underline, .italic] ) // Apply only styles in batch let multiStyled = "Text".applyingStyles([.bold, .italic, .underline]) print(multiStyled) // Apply color, background, and styles together let complex = "Alert".applyingAll( color: .bit8(196), backgroundColor: .named(.yellow), styles: [.bold, .blink] ) print(complex) // Omit optional parameters let colorOnly = "Message".applyingAll( color: .named(.green), styles: [.bold] ) print(colorOnly) // Performance benefit in loops let items = ["Error", "Warning", "Info", "Debug"] for item in items { print(item.applyingAll(color: .named(.red), styles: [.bold, .underline])) } // Output: Styled text with optimal performance ``` -------------------------------- ### Rainbow Hex Color Approximation (Swift) Source: https://github.com/onevcat/rainbow/blob/master/README.md Illustrates using approximate Hex colors with the Rainbow library in Swift. It shows how Rainbow converts Hex color values (strings or integers) into the nearest available 8-bit color for console output. ```swift print("黑云压城\("城欲摧".hex("#666")),甲光向日\("金鳞开".hex("000000").onHex("#E6B422"))。") print("日出江花\("红胜火".hex(0xd11a2d)),春来江水\("绿如蓝".hex(0x10aec2))") ``` -------------------------------- ### Swift Conditional Styling with Closures Source: https://github.com/onevcat/rainbow/blob/master/IMPROVEMENT_ROADMAP.md Demonstrates conditional styling in Swift using closures with Rainbow's `colorWhen` and `styleWhen` methods, allowing for dynamic style application. ```swift let result = message .colorWhen({ level == .error }, .red) .styleWhen({ level == .error }, .bold) ``` -------------------------------- ### Performance-Optimized Styling Builder Source: https://context7.com/onevcat/rainbow/llms.txt Employ a lazy evaluation builder pattern for high-performance text styling, especially beneficial with numerous chained operations. The `.styled` property initiates this builder, which generates a single string upon calling `.build()`, contrasting with traditional chaining that can create multiple intermediate strings. This optimized approach offers significant performance gains in loops or scenarios involving extensive styling. ```swift import Rainbow // Traditional chaining - creates multiple intermediate strings let traditional = "Hello".red.bold.underline.onBlue // Optimized builder pattern - lazy evaluation, single string generation let optimized = "Hello".styled.red.bold.underline.onBlue.build() // Performance comparison for loop operations let messages = (1...1000).map { "Message \($0)" } // Traditional approach (slower for many strings) for msg in messages { let _ = msg.red.bold.underline.onWhite } // Optimized builder approach (faster) for msg in messages { let _ = msg.styled.red.bold.underline.onWhite.build() } // Builder supports all color types let advanced = "Text" .styled .bit8(214) .onBit24(40, 40, 40) .bold .underline .build() // Hex colors with builder let hexed = "Text" .styled .hex("#FF5733") .onHex(0x2C3E50) .italic .build() print(advanced) print(hexed) // Output: Styled text with better performance for repeated operations ``` -------------------------------- ### Swift HSL Color Support Usage Source: https://github.com/onevcat/rainbow/blob/master/IMPROVEMENT_ROADMAP.md This Swift code demonstrates the usage of the HSL color support in Rainbow, showcasing how to apply colors and background colors using HSL values. ```swift "Hello".hsl(120, 100, 50) // Green text "World".onHsl(240, 100, 50) // Blue background ``` -------------------------------- ### Conditional Styling with Rainbow in Swift Source: https://github.com/onevcat/rainbow/blob/master/README.md Shows how to apply styles and colors to strings conditionally in Swift using the Rainbow library. It covers basic conditional application of color and style, as well as more advanced scenarios using a fluent builder interface. This reduces the need for complex ternary operators in log messages or UI elements. ```swift // Basic conditional styling let isError = true let isWarning = false print("Error occurred".colorIf(isError, .red).styleIf(isError, .bold)) print("Warning message".colorIf(isWarning, .yellow)) // Log level styling enum LogLevel { case error, warning, info } let level = LogLevel.error let message = "Something happened" print(message .colorIf(level == .error, .red) .colorIf(level == .warning, .yellow) .colorIf(level == .info, .cyan) .styleIf(level == .error, .bold)) ``` ```swift // Advanced Conditional Builder let isActive = true let isWarning = false let isError = false let styledText = "Server Status: Running" .conditionalStyled .when(isActive).green.bold .when(isWarning).yellow .when(isError).red.underline .build() print(styledText) // With closure-based conditions let progress = 75 let statusMessage = "Processing..." .conditionalStyled .when { progress < 33 }.red.italic .when { progress >= 33 && progress < 67 }.yellow .when { progress >= 67 }.green.bold .build() print(statusMessage) ``` -------------------------------- ### Swift Advanced Conditional Styling with Builder Source: https://github.com/onevcat/rainbow/blob/master/IMPROVEMENT_ROADMAP.md This Swift code illustrates advanced conditional styling using Rainbow's ConditionalStyleBuilder, providing a fluent interface for complex styling rules. ```swift let styledText = "Status: Active" .conditionalStyle() .when(isActive).green.bold .when(isWarning).yellow .when(isError).red.underline .build() ``` -------------------------------- ### Manually Construct Styled Strings Source: https://context7.com/onevcat/rainbow/llms.txt Builds styled terminal strings from scratch using Rainbow.Entry and Rainbow.Segment structures. Provides maximum control over text styling by defining individual segments with text, color, background color, and styles. The generated string can then be printed to the terminal. ```swift import Rainbow // Construct entry with multiple segments let entry = Rainbow.Entry( segments: [ .init(text: "Hello ", color: .named(.magenta)), .init(text: "Rainbow", color: .bit8(214), backgroundColor: .named(.lightBlue), styles: [.underline]), .init(text: " "), .init(text: "Nice to ", color: .bit8(31), styles: [.blink]), .init(text: "see you!", color: .bit8(39), styles: [.italic]) ] ) // Generate the styled string let styledString = Rainbow.generateString(for: entry) print(styledString) // Single segment example let singleSegment = Rainbow.Segment( text: "Warning", color: .named(.yellow), backgroundColor: .named(.red), styles: [.bold, .underline] ) let singleEntry = Rainbow.Entry(segments: [singleSegment]) print(Rainbow.generateString(for: singleEntry)) ``` -------------------------------- ### Swift Hex Color Conversion Methods Source: https://github.com/onevcat/rainbow/blob/master/IMPROVEMENT_ROADMAP.md Provides methods for converting hexadecimal color strings to terminal-compatible color formats for both foreground and background text. These methods leverage a ColorApproximation utility. ```swift // Foreground hex methods public func hex(_ color: String, to target: HexColorTarget = .bit8Approximated) -> String { guard let converter = ColorApproximation(color: color) else { return self } return applyingColor(converter.convert(to: target)) } ``` ```swift // Background hex methods public func onHex(_ color: String, to target: HexColorTarget = .bit8Approximated) -> String { guard let converter = ColorApproximation(color: color) else { return self } return applyingBackgroundColor(converter.convert(to: target)) } ``` -------------------------------- ### True Color Terminal Output in Swift Source: https://github.com/onevcat/rainbow/blob/master/README.md Demonstrates the use of 24-bit true color for terminal output using Swift's Rainbow library. It shows how to apply specific RGB color values to strings and supports both direct RGB values and hex string conversions. This requires a terminal emulator that supports 24-bit color. ```swift print("疏影横斜\(\"水清浅\".bit24(36,116,181)),暗香浮动\(\"月黄昏\".bit24(254,215,26))") print("\(\"春色满园\".hex("#ea517f", to: .bit24))关不住,\(\"一枝红杏\".hex("#f43e06", to: .bit24))出墙来。") ``` -------------------------------- ### Apply Basic Named Foreground Colors in Swift Source: https://context7.com/onevcat/rainbow/llms.txt Applies predefined named foreground colors to strings using Swift string extensions. This is the simplest way to add color to terminal output. No external dependencies beyond the Rainbow library are required. ```swift import Rainbow // Single colors print("Error message".red) print("Success message".green) print("Warning".yellow) print("Info".blue) print("Debug".magenta) print("Trace".cyan) // Light variants print("Light red text".lightRed) print("Light green text".lightGreen) print("Light blue text".lightBlue) ``` -------------------------------- ### HSL Color Formatting in Swift Source: https://github.com/onevcat/rainbow/blob/master/README.md Illustrates how to format strings with HSL (Hue, Saturation, Lightness) colors using the Rainbow library in Swift. The functions accept hue (0-360°), saturation (0-100%), and lightness (0-100%) values. This method provides an alternative to RGB for color specification. ```swift print("天街小雨润如酥,草色遥看近却无".hsl(120, 20, 80)) print("最是一年春好处,绝胜烟柳满皇都".hsl(90, 60, 70)) ``` -------------------------------- ### Chain and Nest String Styling in Swift Source: https://context7.com/onevcat/rainbow/llms.txt Demonstrates chaining multiple styling operations and nesting styled strings within Swift's string interpolation. This allows for complex and dynamic text formatting in the console, preserving styles across interpolations. ```swift import Rainbow // Chaining colors and styles let styledText = "Important message".red.bold.underline print(styledText) // Nested string interpolation preserves inner styles print("接天莲叶\(\"无穷碧\".green),映日荷花\(\"别样红\".red)") print("\(\"两只黄鹂\".yellow)鸣翠柳,一行白鹭\(\"上青天\".lightBlue)。".lightGreen.underline) // Complex nesting let message = "Status: \(\"OK\".green.bold) | Errors: \(\"0\".dim)" print(message) ``` -------------------------------- ### Apply Background Colors in Swift Source: https://context7.com/onevcat/rainbow/llms.txt Applies background colors to strings using the `on` prefix convention in Swift. This allows for highlighting text with different background shades. It can be combined with foreground colors for more complex styling. ```swift import Rainbow // Single background colors print("Error".onRed) print("Success".onGreen) print("Highlighted".onYellow) // Combined foreground and background print("White text on blue background".white.onBlue) print("Black text on yellow background".black.onYellow) // Light background variants print("Text".onLightBlack) print("Text".onLightRed) ``` -------------------------------- ### Apply Text Styles (Bold, Italic, Underline) in Swift Source: https://context7.com/onevcat/rainbow/llms.txt Applies various text styles such as bold, italic, underline, blink, strikethrough, dim, and swap to strings using Swift string extensions. Multiple styles can be chained together for complex formatting. ```swift import Rainbow // Individual styles print("Bold text".bold) print("Italic text".italic) print("Underlined text".underline) print("Blinking text".blink) print("Strikethrough text".strikethrough) print("Dim text".dim) print("Swapped colors".swap) // Chained combinations print("Bold and underlined".bold.underline) print("Red, bold, and italic".red.bold.italic) print("Complex styling".cyan.bold.underline.onWhite) ``` -------------------------------- ### Swift StyledStringBuilder for Performance Optimization Source: https://github.com/onevcat/rainbow/blob/master/IMPROVEMENT_ROADMAP.md Implements a StyledStringBuilder to optimize performance by using lazy evaluation, reducing multiple string copies during chained style applications. It's a key component for enhancing performance in the Rainbow library. ```swift public struct StyledStringBuilder { private let text: String private var color: ColorType? private var backgroundColor: BackgroundColorType? private var styles: [Style] = [] // Lazy evaluation - only generates string when build() is called public func build() -> String { // Generate final string only once } } ``` -------------------------------- ### Apply Styles Verbose Mode Source: https://context7.com/onevcat/rainbow/llms.txt Applies colors and styles to terminal text using explicit method calls like applyingCodes, applyingColor, applyingBackgroundColor, and applyingStyle. Allows for granular control over text formatting. Works with predefined Color, BackgroundColor, and Style enums. ```swift import Rainbow // Using applyingCodes method with multiple arguments let output = "The quick brown fox jumps over the lazy dog" .applyingCodes(Color.red, BackgroundColor.yellow, Style.bold) print(output) // Apply color only let redText = "Error".applyingColor(.red) print(redText) // Apply background color only let highlighted = "Important".applyingBackgroundColor(.yellow) print(highlighted) // Apply style only let boldText = "Title".applyingStyle(.bold) print(boldText) ``` -------------------------------- ### Fluent Conditional Styling Builder Source: https://context7.com/onevcat/rainbow/llms.txt Utilize a fluent builder interface for constructing complex conditional styling scenarios. The `conditionalStyled` property allows chaining multiple `.when()` conditions, each followed by style modifiers. The final styled string is generated using the `.build()` method. This approach supports both direct boolean conditions and closure-based evaluations for flexibility. ```swift import Rainbow // Multiple conditions with builder pattern let isActive = true let isWarning = false let isError = false let styledText = "Server Status: Running" .conditionalStyled .when(isActive).green.bold .when(isWarning).yellow .when(isError).red.underline .build() print(styledText) // Closure-based conditions let progress = 75 let statusMessage = "Processing..." .conditionalStyled .when { progress < 33 }.red.italic .when { progress >= 33 && progress < 67 }.yellow .when { progress >= 67 }.green.bold .build() print(statusMessage) // Complex conditional styling let severity = 8 let uptime = 99.9 let systemStatus = "System Health" .conditionalStyled .when { severity >= 8 }.red .when { severity >= 5 && severity < 8 }.yellow .when { severity < 5 }.green .when { uptime < 95.0 }.underline .when { uptime > 99.5 }.bold .build() print(systemStatus) // Output: Conditionally styled text based on runtime evaluation ``` -------------------------------- ### Apply Conditional Styling with Rainbow Source: https://context7.com/onevcat/rainbow/llms.txt Apply text colors and styles conditionally based on runtime logic. This includes methods like `colorIf(_:_:supportedColor:)`, `backgroundColorIf(_:_:supportedColor:)`, and `styleIf(_:_:supportedStyle:)` which take a boolean condition and the desired style. It also supports closure-based conditions with `colorWhen(_:_:supportedColor:)` and `styleWhen(_:_:supportedStyle:)` for more dynamic evaluations. ```swift import Rainbow // Basic conditional styling let isError = true let isWarning = false let message = "Something happened" print(message.colorIf(isError, .red)) print(message.colorIf(isWarning, .yellow)) // Conditional background colors print("Alert".backgroundColorIf(isError, .red)) // Conditional styles print(message.styleIf(isError, .bold)) // Log level styling example enum LogLevel { case error, warning, info } let level = LogLevel.error let logMessage = "System event occurred" print(logMessage .colorIf(level == .error, .red) .colorIf(level == .warning, .yellow) .colorIf(level == .info, .cyan) .styleIf(level == .error, .bold)) // Closure-based conditions let temperature = 95 print("Temperature: \(temperature)°F" .colorWhen({ temperature > 90 }, .red) .styleWhen({ temperature > 100 }, .bold)) // Output: Conditionally colored text in terminal ``` -------------------------------- ### Swift API Improvement: Intuitive Color Naming Source: https://github.com/onevcat/rainbow/blob/master/IMPROVEMENT_ROADMAP.md Proposed changes in Swift for more intuitive naming of color functions, replacing `bit8` and `bit24` with `color256` and `trueColor` respectively. ```swift // More intuitive naming extension String { func color256(_ value: UInt8) -> String // Instead of bit8 func trueColor(_ r: UInt8, _ g: UInt8, _ b: UInt8) -> String // Instead of bit24 // Alternative background color syntax var background: BackgroundColorWrapper { get } } // Usage "text".color256(123) "text".trueColor(255, 0, 0) "text".background.red // Alternative to onRed ``` -------------------------------- ### Apply Colors using HSL Color Space Source: https://context7.com/onevcat/rainbow/llms.txt Applies colors to terminal text using the HSL (Hue, Saturation, Lightness) color model. Supports HSL values, HSL tuples, and background colors. Can convert HSL to 24-bit color for better terminal support. Requires a terminal that supports HSL or 24-bit color. ```swift import Rainbow // HSL format: hue (0-360°), saturation (0-100%), lightness (0-100%) print("Spring green".hsl(120, 20, 80)) print("Vibrant green".hsl(90, 60, 70)) // Background HSL colors print("Text".onHsl(0, 100, 50)) print("Another".onHsl(240, 80, 60)) // Convert to 24-bit instead of 8-bit approximation print("True HSL color".hsl(180, 50, 50, to: .bit24)) // Using HSL tuples let springColor: HSL = (hue: 120, saturation: 20, lightness: 80) print("Using tuple".hsl(springColor)) // Chinese poetry example print("\(\"天街\".hsl(0, 0, 70))小雨润如酥,\(\"草色\".hsl(120, 20, 80))遥看近却无") print("\(\"最是\".hsl(90, 60, 70))一年春好处,绝胜\(\"烟柳\".hsl(120, 30, 75))满皇都") ``` -------------------------------- ### Control Rainbow Colorization Globally Source: https://context7.com/onevcat/rainbow/llms.txt Manage the global enabling and disabling of text colorization. Rainbow automatically disables colorization when output is not a TTY (e.g., redirected to a file) and respects NO_COLOR/FORCE_COLOR environment variables. Colorization can be explicitly controlled via the `Rainbow.enabled` property. ```swift import Rainbow // Disable all colorization Rainbow.enabled = false print("This will not be colored".red.bold) // Output: plain text // Re-enable colorization Rainbow.enabled = true print("This will be colored".red.bold) // Output: colored text // Check if enabled if Rainbow.enabled { print("Colors are active".green) } // Automatically disabled when output is not a TTY: // $ ./myapp > output.txt (colors disabled) // $ ./myapp (colors enabled) // Environment variable override: // $ NO_COLOR=1 ./myapp (colors disabled) // $ FORCE_COLOR=1 ./myapp (colors forced on) // Output: Colored or plain text depending on configuration ``` -------------------------------- ### Apply Hex Colors with Approximation in Swift Source: https://context7.com/onevcat/rainbow/llms.txt Applies colors to terminal text using hex color codes in Swift. The library automatically approximates hex colors to the nearest 8-bit or 24-bit color if true color is not supported or specified. Supports hex strings and integers. ```swift import Rainbow // Hex string formats (with or without #) print("Grey text".hex("#666")) print("Black on gold".hex("000000").onHex("#E6B422")) print("Red text".hex("#d11a2d")) // Hex integer format (0x prefix) print("Red text".hex(0xd11a2d)) print("Cyan text".hex(0x10aec2)) // Convert to 24-bit instead of 8-bit approximation print("True color".hex("#ea517f", to: .bit24)) print("Another true color".hex("#f43e06", to: .bit24)) // Chinese poetry example print("黑云压城\(\"城欲摧\".hex("#666")),甲光向日\(\"金鳞开\".hex("000000").onHex("#E6B422"))。") print("日出江花\(\"红胜火\".hex(0xd11a2d)),春来江水\(\"绿如蓝\".hex(0x10aec2))") ``` -------------------------------- ### Control Rainbow Output Target Source: https://context7.com/onevcat/rainbow/llms.txt Manually control or inspect the output target for Rainbow's color application. While Rainbow typically auto-detects the output target, this feature allows forcing modes like `.console` or `.unknown` (plain text) for specific scenarios, such as testing. Resetting to `.current` restores automatic detection. ```swift import Rainbow // Check current output target switch Rainbow.outputTarget { case .console: print("Output is going to a console".green) case .unknown: print("Output target is unknown (file, pipe, etc.)") } // Manually set output target (rarely needed) Rainbow.outputTarget = .console // Force console mode print("This will be colored".red) Rainbow.outputTarget = .unknown // Force plain text mode print("This will NOT be colored".red) // Reset to automatic detection Rainbow.outputTarget = .current // Typical use case: testing func testColorOutput() { let originalTarget = Rainbow.outputTarget Rainbow.outputTarget = .console // Test color output let result = "Test".red Rainbow.outputTarget = originalTarget // Restore } // Output: Behavior depends on output target setting ``` -------------------------------- ### Clear Terminal Styles and Colors Source: https://context7.com/onevcat/rainbow/llms.txt Removes specific colors or styles from already-styled terminal strings. Provides methods to clear foreground color, background color, all styles, or individual styles using removingStyle. Useful for resetting text formatting. ```swift import Rainbow // Apply and then clear colors/styles let styled = "Text".red.onYellow.bold print(styled) // Clear specific components print(styled.clearColor) // Removes foreground color print(styled.clearBackgroundColor) // Removes background color print(styled.clearStyles) // Removes all styles // Clear everything print("Plain text".red.onYellow.bold.clearColor.clearBackgroundColor.clearStyles) // Remove specific style let multistyled = "Text".bold.underline.italic print(multistyled.removingStyle(.underline)) // Removes only underline ``` -------------------------------- ### Use 8-Bit (256) Color Mode in Swift Source: https://context7.com/onevcat/rainbow/llms.txt Applies colors from the 8-bit (256-color) palette to terminal text using Swift string extensions. It supports both foreground and background colors via `bit8` and `onBit8` methods, accepting color codes from 0 to 255. ```swift import Rainbow // Apply 8-bit foreground colors (0-255) print("Custom color".bit8(31)) print("Another color".bit8(160)) print("Vibrant color".bit8(198)) // Apply 8-bit background colors print("Text with custom background".onBit8(226)) print("Combined".bit8(202).onBit8(30)) // Chinese poetry example print("停车坐爱\(\"枫林晚\".bit8(31)),\(\"霜叶\".bit8(160))红于\(\"二月花\".bit8(198))。") print("\(\"一道残阳\".bit8(202))铺水中,\(\"半江瑟瑟\".bit8(30).onBit8(226))半江红。") ``` -------------------------------- ### Apply 24-Bit True Color using RGB Source: https://context7.com/onevcat/rainbow/llms.txt Applies 24-bit RGB colors to terminal text using specified R, G, B components (0-255). Supports direct RGB values, RGB tuples, and background colors. Can convert hex codes to 24-bit color. Requires a terminal that supports 24-bit color. ```swift import Rainbow // Apply 24-bit RGB colors (R, G, B components 0-255) print("True blue".bit24(36, 116, 181)) print("True yellow".bit24(254, 215, 26)) // Using RGB tuples let customColor: RGB = (255, 100, 50) print("Custom RGB color".bit24(customColor)) // Background colors print("Text".onBit24(200, 200, 200)) print("Combined".bit24(255, 0, 0).onBit24(0, 0, 255)) // With hex conversion to 24-bit print("\(\"春色满园\".hex(\"#ea517f\", to: .bit24))关不住,\(\"一枝红杏\".hex(\"#f43e06\", to: .bit24))出墙来。") // Chinese poetry example print("疏影横斜\(\"水清浅\".bit24(36,116,181)),暗香浮动\(\"月黄昏\".bit24(254,215,26))") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.