Skip to content

Commit

Permalink
Add support for opacity to Color. (#143)
Browse files Browse the repository at this point in the history
  • Loading branch information
jverkoey authored Aug 10, 2024
1 parent 18ec341 commit 7734f82
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
50 changes: 50 additions & 0 deletions Sources/Slipstream/TailwindCSS/Color.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,19 @@ public struct Color {
/// Creates a Color instance using a Tailwind CSS palette instance.
public init(_ colorPalette: ColorPalette, darkness: Int) {
self.storage = .palette(colorPalette, darkness: darkness)
self.opacity = 1
}

/// Multiplies the opacity of the color by the given amount.
public func opacity(_ opacity: Double) -> Self {
var copy = self
copy.opacity *= opacity
return copy
}

init(_ value: Storage) {
self.storage = value
self.opacity = 1
}

enum Storage {
Expand All @@ -25,9 +34,18 @@ public struct Color {
case palette(ColorPalette, darkness: Int)
}
private let storage: Storage
private var opacity: Double

/// Returns the Tailwind CSS color class for this color.
func toTailwindColorClass() -> String {
if opacity < 1 {
return colorClass + "/" + opacityClass
}
return colorClass
}

/// Returns the Tailwind CSS color class for this color.
private var colorClass: String {
switch storage {
case .black:
return "black"
Expand All @@ -37,4 +55,36 @@ public struct Color {
return colorPalette.closestTailwindColorStop(for: darkness)
}
}

/// Maps the opacity to the closest Tailwind CSS opacity class.
///
/// - Parameter size: The size in points to be mapped.
/// - Returns: The Tailwind CSS placement class.
var opacityClass: String {
let mapping: [(name: String, opacity: Double)] = [
("0", 0.0),
("5", 0.05),
("10", 0.10),
("15", 0.15),
("20", 0.20),
("25", 0.25),
("30", 0.30),
("35", 0.35),
("40", 0.40),
("45", 0.45),
("50", 0.50),
("55", 0.55),
("60", 0.60),
("65", 0.65),
("70", 0.70),
("75", 0.75),
("80", 0.80),
("85", 0.85),
("90", 0.90),
("95", 0.95),
("100", 0.100),
]
let closestClass = mapping.min { abs($0.opacity - opacity) < abs($1.opacity - opacity) }
return closestClass?.name ?? "0"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,10 @@ struct BackgroundColorTests {
@Test func colorWithDarkness() throws {
try #expect(renderHTML(Div {}.background(.cyan, darkness: 500)) == #"<div class="bg-cyan-500"></div>"#)
}

@Test func colorWithOpacity() throws {
try #expect(renderHTML(Div {}.background(.init(.cyan, darkness: 500).opacity(0))) == #"<div class="bg-cyan-500/0"></div>"#)
try #expect(renderHTML(Div {}.background(.init(.cyan, darkness: 500).opacity(0.5))) == #"<div class="bg-cyan-500/50"></div>"#)
try #expect(renderHTML(Div {}.background(.init(.cyan, darkness: 500).opacity(20))) == #"<div class="bg-cyan-500"></div>"#)
}
}

0 comments on commit 7734f82

Please sign in to comment.