changeChannels method

SassColor changeChannels(
  1. Map<String, double> newValues, {
  2. ColorSpace? space,
  3. String? colorName,
})

Changes one or more of this color's channels and returns the result.

The keys of newValues are channel names and the values are the new values of those channels.

If space is passed, this converts this color to space, sets the channels, then converts the result back to its original color space.

Throws a SassScriptException if any of the keys aren't valid channel names for this color, or if the same channel is set multiple times.

If this color came from a function argument, colorName is the argument name (without the $). This is used for error reporting.

Implementation

SassColor changeChannels(Map<String, double> newValues,
    {ColorSpace? space, String? colorName}) {
  if (newValues.isEmpty) return this;

  if (space != null && space != this.space) {
    return toSpace(space)
        .changeChannels(newValues, colorName: colorName)
        .toSpace(this.space);
  }

  double? new0;
  double? new1;
  double? new2;
  double? alpha;
  var channels = this.space.channels;

  void setChannel0(double value) {
    if (new0 != null) {
      throw SassScriptException(
          'Multiple values supplied for "${channels[0]}": $new0 and '
          '$value.',
          colorName);
    }
    new0 = value;
  }

  void setChannel1(double value) {
    if (new1 != null) {
      throw SassScriptException(
          'Multiple values supplied for "${channels[1]}": $new1 and '
          '$value.',
          colorName);
    }
    new1 = value;
  }

  void setChannel2(double value) {
    if (new2 != null) {
      throw SassScriptException(
          'Multiple values supplied for "${channels[2]}": $new2 and '
          '$value.',
          colorName);
    }
    new2 = value;
  }

  for (var entry in newValues.entries) {
    var channel = entry.key;
    if (channel == channels[0].name) {
      setChannel0(entry.value);
    } else if (channel == channels[1].name) {
      setChannel1(entry.value);
    } else if (channel == channels[2].name) {
      setChannel2(entry.value);
    } else if (channel == 'alpha') {
      if (alpha != null) {
        throw SassScriptException(
            'Multiple values supplied for "alpha": $alpha and '
            '${entry.value}.',
            colorName);
      }
      alpha = entry.value;
    } else {
      throw SassScriptException(
          "Color $this doesn't have a channel named \"$channel\".",
          colorName);
    }
  }

  return SassColor.forSpaceInternal(this.space, new0 ?? channel0OrNull,
      new1 ?? channel1OrNull, new2 ?? channel2OrNull, alpha ?? alphaOrNull);
}