fluentApplyOpacityToColor function
Returns color carrying opacity, or color unchanged when it is already
translucent and preserveOriginalOpacity holds.
Ports applyOpacityToColor (useChartAnnotationLayer.styles.ts:34-59).
Upstream parses a CSS string with d3-color and returns the input verbatim
when it will not parse; Dart already has a parsed Color, so the
unparseable arm has no counterpart and the alpha channel is read directly.
preserveOriginalOpacity defaults to true, and
ChartAnnotationLayer.tsx:497 passes style.opacity == null for it — so an
author who names an opacity always wins, while one who only names a
translucent colour keeps it.
Implementation
Color? fluentApplyOpacityToColor(
Color? color,
double opacity, {
bool preserveOriginalOpacity = true,
}) {
if (color == null) {
return null;
}
// useChartAnnotationLayer.styles.ts:50-55.
if (preserveOriginalOpacity && color.a < 1) {
return color;
}
// :57 — Math.max(0, Math.min(1, opacity)).
return color.withValues(alpha: math.max(0, math.min(1, opacity)));
}