Skip to content

Commit 158e011

Browse files
committed
feat: add withOpacity extension method to StacColor
- Add StacColorExtension with withOpacity() method - Support opacity values from 0.0 to 1.0 with automatic clamping - Convert opacity to percentage format (@<opacity>) for consistency - Include comprehensive documentation with Dart and JSON examples - Enable easy opacity manipulation for both hex colors and theme colors
1 parent fa00e73 commit 158e011

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

packages/stac_core/lib/foundation/colors/stac_color/stac_colors.dart

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,49 @@
44
/// or theme color names (e.g., 'primary', 'secondary').
55
typedef StacColor = String;
66

7+
/// Extension on [StacColor] to provide additional functionality.
8+
extension StacColorExtension on StacColor {
9+
/// Creates a new color with the specified opacity.
10+
///
11+
/// This method appends the opacity value to the color string in the format
12+
/// `@<opacity>` where opacity is expressed as a percentage (0-100).
13+
///
14+
/// {@tool snippet}
15+
/// Dart Example:
16+
/// ```dart
17+
/// StacColors.primary.withOpacity(0.8) // Returns "primary@80"
18+
/// StacColors.blue.withOpacity(0.5) // Returns "blue@50"
19+
/// '#FF0000'.withOpacity(0.3) // Returns "#FF0000@30"
20+
/// ```
21+
/// {@end-tool}
22+
///
23+
/// {@tool snippet}
24+
/// JSON Example:
25+
/// ```json
26+
/// {
27+
/// "color": "primary@80",
28+
/// "backgroundColor": "secondary@50"
29+
/// }
30+
/// ```
31+
/// {@end-tool}
32+
///
33+
/// The opacity value should be between 0.0 (completely transparent) and 1.0
34+
/// (completely opaque). Values outside this range will be clamped.
35+
StacColor withOpacity(double opacity) {
36+
// Clamp opacity to valid range (0.0 to 1.0)
37+
final clampedOpacity = opacity.clamp(0.0, 1.0);
38+
39+
// Convert to percentage (0-100) and round to nearest integer
40+
final opacityPercentage = (clampedOpacity * 100).round();
41+
42+
// Remove any existing opacity suffix by splitting on '@' and taking the first part
43+
final baseColor = split('@').first;
44+
45+
// Return the base color string with new opacity suffix
46+
return '$baseColor@$opacityPercentage';
47+
}
48+
}
49+
750
/// A collection of predefined colors for the Stac framework.
851
///
952
/// This class provides a comprehensive set of Material Design colors,

0 commit comments

Comments
 (0)