Files
TUIkit/Sources/TUIKit/Modifiers/DimmedModifier.swift
T
phranck 45e73faafb refactor: Rename package from SwiftTUI to TUIKit
BREAKING CHANGE: Package name changed due to name collision with
existing rensbreur/SwiftTUI package.

Changes:
- Rename package from SwiftTUI to TUIKit in Package.swift
- Rename Sources/SwiftTUI to Sources/TUIKit
- Rename Sources/SwiftTUIExample to Sources/TUIKitExample
- Rename Tests/SwiftTUITests to Tests/TUIKitTests
- Rename SwiftTUI.swift to TUIKit.swift
- Update all imports: import SwiftTUI -> import TUIKit
- Update all code references: SwiftTUI.renderToBuffer -> TUIKit.renderToBuffer
- Update documentation comments
- Rename swiftTUIVersion to tuiKitVersion

All 181 tests passing.
2026-01-28 19:32:09 +01:00

88 lines
2.5 KiB
Swift

//
// DimmedModifier.swift
// TUIKit
//
// A modifier that applies a dimming effect to the entire view content.
//
/// A modifier that applies the ANSI dim effect to the entire content.
///
/// This is useful for de-emphasizing background content when showing
/// overlays, alerts, or dialogs.
public struct DimmedModifier<Content: View>: View {
/// The content to dim.
let content: Content
public var body: Never {
fatalError("DimmedModifier renders via Renderable")
}
}
// MARK: - Renderable
extension DimmedModifier: Renderable {
public func renderToBuffer(context: RenderContext) -> FrameBuffer {
let contentBuffer = TUIKit.renderToBuffer(content, context: context)
guard !contentBuffer.isEmpty else {
return contentBuffer
}
// Apply dim effect to each line
let dimmedLines = contentBuffer.lines.map { line -> String in
applyDim(to: line)
}
return FrameBuffer(lines: dimmedLines)
}
/// Applies the ANSI dim effect to a string.
///
/// If the string already contains ANSI codes, this wraps the entire line.
/// The dim code (ESC[2m) reduces the intensity of the text.
///
/// - Parameter text: The text to dim.
/// - Returns: The dimmed text with ANSI codes.
private func applyDim(to text: String) -> String {
guard !text.isEmpty else { return text }
// ANSI dim code
let dimCode = "\u{1B}[2m"
let resetCode = "\u{1B}[0m"
// If the line is empty (just spaces), keep it as is
if text.stripped.trimmingCharacters(in: .whitespaces).isEmpty {
return text
}
// Wrap the entire line in dim codes
// Note: This adds dim at the start and reset at the end
// Any existing styles will still work, but will be dimmed
return dimCode + text + resetCode
}
}
// MARK: - View Extension
extension View {
/// Applies a dimming effect to the view content.
///
/// This reduces the visual intensity of the content using the ANSI dim
/// escape code. Useful for background content when displaying overlays.
///
/// # Example
///
/// ```swift
/// VStack {
/// Text("This content will be dimmed")
/// Text("All text is affected")
/// }
/// .dimmed()
/// ```
///
/// - Returns: A view with the dimming effect applied.
public func dimmed() -> some View {
DimmedModifier(content: self)
}
}