Skip to content

Commit

Permalink
Support alpha modifier on color
Browse files Browse the repository at this point in the history
  • Loading branch information
freemansoft committed May 5, 2024
1 parent cee9aeb commit d5c4092
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/models/color_value.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ class ColorValue {
return ColorValue._(rgb[0], rgb[1], rgb[2], a);
}

/// cascades this amount alpha on the existing alpha
/// ignores any space info
/// Should throw Exception for any value (1.0 < amount) or (amount < 0.0)
ColorValue alphainate(double amount) {
final newA = ((a / 255) * (amount * 255)).round();
return ColorValue._(r, g, b, newA);
}

ColorValue mix(String value, double amount) {
final other = maybeParse(value)!;

Expand Down
2 changes: 2 additions & 0 deletions lib/transformers/color_transformer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ class ColorTransformer extends SingleTokenTransformer {
colorValue = colorValue.lighten(value / 2);
} else if (type == 'darken') {
colorValue = colorValue.darken(value / 2);
} else if (type == 'alpha') {
colorValue = colorValue.alphainate(value);
} else if (color != null && type == 'mix' && color.startsWith('#')) {
colorValue = colorValue.mix(color, value);
}
Expand Down
43 changes: 43 additions & 0 deletions test/transformers/color_transformer_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,33 @@ final colorModifiers = '''
}
}
}
},
"srgb-1-0-test": {
"value": "{purple}",
"type": "color",
"\$extensions": {
"studio.tokens": {
"modify": {
"type": "alpha",
"value": "1.0",
"space": "srgb"
}
}
}
},
"srgb-0-5-test": {
"value": "{purple}",
"type": "color",
"\$extensions": {
"studio.tokens": {
"modify": {
"type": "alpha",
"value": "0.5",
"space": "srgb"
}
}
}
}
}
''';
Expand Down Expand Up @@ -173,4 +200,20 @@ void main() {
equals('const Color(0xFFB200E3)'),
);
});

test('Color modifiers alpha', () {
final parsed = json.decode(colorModifiers) as Map<String, dynamic>;
final parser = TokenParser()..parse(parsed);

final transformer = ColorTransformer();

expect(
transformer.transform(parser.resolve('srgb-1-0-test')!),
equals('const Color(0xFF6400FF)'),
);
expect(
transformer.transform(parser.resolve('srgb-0-5-test')!),
equals('const Color(0x806400FF)'),
);
});
}

0 comments on commit d5c4092

Please sign in to comment.