Skip to content

Truly independent web browser

54.9 KB
Raw Blame
/*
 * Copyright (c) 2026-present, the Ladybird developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

//! CSS image and gradient parsing, mirroring ValueParsing.cpp and GradientParsing.cpp.

use std::cmp::Ordering;
use std::sync::Arc;

use crate::css::calc::{
    CalcNode, CalcNumericValue, FfiNumericType, length_percentage_calculated_style_value,
    resolve_calculated_number_without_context, resolve_calculated_percentage_without_context,
    simplify_parsed_calculation,
};
use crate::css::math_functions::math_function_from_name;
use crate::css::style_compute::px_length_unit;
use crate::css::style_value::{
    ConicGradientPayload, ImagePayload, ImageSetPayload, LightDarkPayload, LinearGradientPayload,
    RadialGradientPayload, RadialSizePayload, StyleValueBox, UrlPayload,
};
use crate::css::style_value_arc::StyleValueArc;

use crate::css::css_string::CssString;
use crate::css::css_tokenizer::ParserTokenKind;
use crate::css::parser::color_parser::{
    color_syntax, make_legacy_color, parse_color_interpolation_method, parse_color_value,
};
use crate::css::parser::component_value::{ComponentKind, ComponentValue};
use crate::css::parser::positions_shapes_parser::{
    center_position, edge, parse_position_from_stream, parse_radial_size, position,
};
use crate::css::parser::token_stream::TokenStream;
use crate::css::property_metadata::property_id;
use crate::css::style_value::{
    ImageResourceContext, RetainedColorStop, RetainedColorStopList, RetainedImageSetOption, RetainedImageSetOptionList,
    RetainedRequestUrlModifierList, RetainedString, RetainedStyleValueData, RetainedStyleValueDataList, StyleValueData,
};

use super::value_parser::{
    NumericRange, ParseContext, ParseOutcome, equals_ascii_case_insensitive, parse_angle_from_stream,
    parse_angle_percentage_from_stream, parse_calculated_numeric_value_with_ranges,
    parse_length_percentage_from_stream, parse_number_from_stream, parse_percentage_value,
    parse_resolution_from_stream, parse_url_value,
};
use crate::css::value_codes::{COLOR_SYNTAX_LEGACY, VALUE_TYPE_LENGTH, VALUE_TYPE_PERCENTAGE};

fn retained(value: StyleValueData) -> RetainedStyleValueData {
    RetainedStyleValueData::from_owned(value)
}

fn value_list(values: Vec<StyleValueData>) -> StyleValueData {
    StyleValueData::ValueList {
        values: RetainedStyleValueDataList::from_retained_values(values.into_iter().map(retained).collect()),
        separator: 1,
        collapsible: true,
    }
}

fn image_resource_context() -> ImageResourceContext {
    // The stylesheet supplies its resource context when the value is computed. Inline images
    // follow their element's document, which can change after parsing in a template document.
    ImageResourceContext {
        base_url: RetainedString::from_ascii(String::new()),
        has_base_url: false,
        has_parent_style_sheet_origin_clean: false,
        parent_style_sheet_origin_clean: false,
        should_absolutize_url_for_computed_value: false,
    }
}

fn image_from_url(url: StyleValueData) -> Option<StyleValueData> {
    let StyleValueData::Url(url_payload) = url else {
        return None;
    };
    let UrlPayload {
        url,
        url_type,
        modifiers,
    } = url_payload.into_inner();
    Some(StyleValueData::Image(StyleValueBox::new(ImagePayload {
        url,
        url_type,
        url_modifiers: modifiers,
        resource_context: image_resource_context(),
    })))
}

fn image_from_string(string: &[u16]) -> Option<StyleValueData> {
    Some(StyleValueData::Image(StyleValueBox::new(ImagePayload {
        url: RetainedString::from_utf16(string)?,
        url_type: 0,
        url_modifiers: RetainedRequestUrlModifierList::from_vec(Vec::new()),
        resource_context: image_resource_context(),
    })))
}

fn parse_type(_context: &ParseContext, value: &ComponentValue) -> Option<CssString> {
    let (name, arguments) = value.function()?;
    if !equals_ascii_case_insensitive(name, b"type") {
        return None;
    }
    let mut arguments = arguments.iter().filter(|value| !value.is_whitespace());
    let string = arguments.next()?.string()?;
    if arguments.next().is_some() {
        return None;
    }
    Some(CssString::from_utf16(string))
}

fn parse_image_set(context: &ParseContext, property: u16, arguments: &[ComponentValue]) -> Option<StyleValueData> {
    if context.contains_attr_tainted_values {
        return None;
    }
    let mut options = Vec::new();
    for option in arguments.split(ComponentValue::is_comma) {
        let mut tokens = TokenStream::new(option);
        tokens.discard_whitespace();
        let image = if let Some(string) = tokens.next_token().string() {
            let image = image_from_string(string)?;
            tokens.discard_a_token();
            image
        } else {
            parse_image_value(context, property, &mut tokens, false)?
        };

        let mut resolution = None;
        let mut type_string = None;
        loop {
            tokens.discard_whitespace();
            if !tokens.has_next_token() {
                break;
            }
            let mut resolution_tokens = tokens.clone();
            if resolution.is_none()
                && let Some(parsed) =
                    parse_resolution_from_stream(context, property, &mut resolution_tokens, NumericRange::INFINITE)
            {
                tokens = resolution_tokens;
                resolution = Some(parsed);
                continue;
            }
            if type_string.is_none()
                && let Some(parsed) = parse_type(context, tokens.next_token())
            {
                tokens.discard_a_token();
                type_string = Some(parsed);
                continue;
            }
            return None;
        }
        options.push(RetainedImageSetOption::from_retained_values(
            retained(image),
            retained(resolution.unwrap_or(StyleValueData::Resolution { value: 1.0, unit: 3 })),
            type_string,
        ));
    }
    (!options.is_empty()).then(|| {
        StyleValueData::ImageSet(StyleValueBox::new(ImageSetPayload {
            options: RetainedImageSetOptionList::from_vec(options),
        }))
    })
}

fn optional_retained(value: Option<StyleValueData>) -> RetainedStyleValueData {
    value.map_or_else(RetainedStyleValueData::none, retained)
}

struct ParsedColorStop {
    color: StyleValueData,
    position: Option<StyleValueData>,
    second_position: Option<StyleValueData>,
}

enum ColorStopElement {
    Stop(Box<ParsedColorStop>),
    Hint(StyleValueData),
}

fn parse_color_stop_element(
    context: &ParseContext,
    property: u16,
    tokens: &mut TokenStream<'_>,
    angular: bool,
) -> Option<ColorStopElement> {
    tokens.discard_whitespace();
    if !tokens.has_next_token() {
        return None;
    }
    let parse_position = |tokens: &mut TokenStream<'_>| {
        if angular {
            if matches!(tokens.next_token().kind, ComponentKind::Token(ParserTokenKind::Number { value, .. }) if value == 0.0)
            {
                tokens.discard_a_token();
                return Some(StyleValueData::Angle { value: 0.0, unit: 0 });
            }
            parse_angle_percentage_from_stream(
                context,
                property,
                tokens,
                NumericRange::INFINITE,
                NumericRange::INFINITE,
            )
        } else {
            parse_length_percentage_from_stream(
                context,
                property,
                tokens,
                NumericRange::INFINITE,
                NumericRange::INFINITE,
            )
        }
    };

    let mut position_tokens = tokens.clone();
    if let Some(position) = parse_position(&mut position_tokens) {
        *tokens = position_tokens;
        tokens.discard_whitespace();
        if !tokens.has_next_token() || tokens.next_token().is_comma() {
            return Some(ColorStopElement::Hint(position));
        }
        let color = parse_color_value(context, property, tokens, false)?;
        return Some(ColorStopElement::Stop(Box::new(ParsedColorStop {
            color,
            position: Some(position),
            second_position: None,
        })));
    }

    let color = parse_color_value(context, property, tokens, false)?;
    tokens.discard_whitespace();
    let mut positions = Vec::new();
    for _ in 0..2 {
        if !tokens.has_next_token() || tokens.next_token().is_comma() {
            break;
        }
        positions.push(parse_position(tokens)?);
        tokens.discard_whitespace();
    }
    Some(ColorStopElement::Stop(Box::new(ParsedColorStop {
        color,
        position: positions.first().cloned(),
        second_position: positions.get(1).cloned(),
    })))
}

fn retained_color_stop(hint: Option<StyleValueData>, stop: ColorStopElement) -> Option<RetainedColorStop> {
    let ColorStopElement::Stop(stop) = stop else {
        return None;
    };
    let ParsedColorStop {
        color,
        position,
        second_position,
    } = *stop;
    Some(RetainedColorStop::from_retained_values(
        optional_retained(hint),
        retained(color),
        optional_retained(position),
        optional_retained(second_position),
    ))
}

fn parse_color_stop_list(
    context: &ParseContext,
    property: u16,
    tokens: &mut TokenStream<'_>,
    angular: bool,
) -> Option<(RetainedColorStopList, u8)> {
    let first = parse_color_stop_element(context, property, tokens, angular)?;
    let mut color_syntax_value = match &first {
        ColorStopElement::Stop(stop) => color_syntax(&stop.color),
        ColorStopElement::Hint(_) => return None,
    };
    let mut stops = vec![retained_color_stop(None, first)?];
    loop {
        tokens.discard_whitespace();
        if !tokens.has_next_token() {
            break;
        }
        if !tokens.next_token().is_comma() {
            return None;
        }
        tokens.discard_a_token();
        let element = parse_color_stop_element(context, property, tokens, angular)?;
        let (hint, stop) = match element {
            ColorStopElement::Hint(hint) => {
                tokens.discard_whitespace();
                if !tokens.next_token().is_comma() {
                    return None;
                }
                tokens.discard_a_token();
                (
                    Some(hint),
                    parse_color_stop_element(context, property, tokens, angular)?,
                )
            }
            stop => (None, stop),
        };
        if let ColorStopElement::Stop(stop) = &stop {
            color_syntax_value = color_syntax_value.max(color_syntax(&stop.color));
        }
        stops.push(retained_color_stop(hint, stop)?);
    }
    Some((RetainedColorStopList::from_vec(stops), color_syntax_value))
}

fn strip_ascii_prefix<'a>(value: &'a [u16], prefix: &[u8]) -> Option<&'a [u16]> {
    if value.len() < prefix.len() || !equals_ascii_case_insensitive(&value[..prefix.len()], prefix) {
        return None;
    }
    Some(&value[prefix.len()..])
}

fn side(identifier: &[u16]) -> Option<u8> {
    if equals_ascii_case_insensitive(identifier, b"top") {
        Some(0)
    } else if equals_ascii_case_insensitive(identifier, b"bottom") {
        Some(1)
    } else if equals_ascii_case_insensitive(identifier, b"left") {
        Some(2)
    } else if equals_ascii_case_insensitive(identifier, b"right") {
        Some(3)
    } else {
        None
    }
}

fn corner(first: u8, second: u8) -> Option<u8> {
    match (first, second) {
        (0, 2) | (2, 0) => Some(4),
        (0, 3) | (3, 0) => Some(5),
        (1, 2) | (2, 1) => Some(6),
        (1, 3) | (3, 1) => Some(7),
        _ => None,
    }
}

// https://drafts.csswg.org/css-images-4/#linear-gradients
// <linear-gradient-syntax> = [ [ <angle> | <zero> | to <side-or-corner> ] || <color-interpolation-method> ]? , <color-stop-list>
fn parse_linear_gradient(
    context: &ParseContext,
    property: u16,
    mut name: &[u16],
    arguments: &[ComponentValue],
) -> Option<StyleValueData> {
    let webkit = strip_ascii_prefix(name, b"-webkit-");
    if let Some(stripped) = webkit {
        name = stripped;
    }
    let repeating = strip_ascii_prefix(name, b"repeating-");
    if let Some(stripped) = repeating {
        name = stripped;
    }
    if !equals_ascii_case_insensitive(name, b"linear-gradient") {
        return None;
    }

    let mut tokens = TokenStream::new(arguments);
    tokens.discard_whitespace();
    if !tokens.has_next_token() {
        return None;
    }
    let mut interpolation_method = parse_color_interpolation_method(&mut tokens);
    tokens.discard_whitespace();
    let mut direction_value = None;
    let mut side_or_corner = if webkit.is_some() { 0 } else { 1 };
    let mut has_direction = true;
    let mut angle_tokens = tokens.clone();
    if let Some(angle) = parse_angle_from_stream(context, property, &mut angle_tokens, NumericRange::INFINITE) {
        tokens = angle_tokens;
        direction_value = Some(angle);
    } else if matches!(tokens.next_token().kind, ComponentKind::Token(ParserTokenKind::Number { value, .. }) if value == 0.0)
    {
        tokens.discard_a_token();
        direction_value = Some(StyleValueData::Angle { value: 0.0, unit: 0 });
    } else {
        let is_side = tokens.next_token().ident().is_some_and(|identifier| {
            if webkit.is_some() {
                side(identifier).is_some()
            } else {
                equals_ascii_case_insensitive(identifier, b"to")
            }
        });
        if is_side {
            if webkit.is_none() {
                tokens.discard_a_token();
                tokens.discard_whitespace();
            }
            let first = side(tokens.consume_a_token().ident()?)?;
            tokens.discard_whitespace();
            let second = tokens.next_token().ident().and_then(side);
            side_or_corner = if let Some(second) = second {
                tokens.discard_a_token();
                corner(first, second)?
            } else {
                first
            };
        } else {
            has_direction = false;
        }
    }
    if interpolation_method.is_none() {
        tokens.discard_whitespace();
        interpolation_method = parse_color_interpolation_method(&mut tokens);
    }
    tokens.discard_whitespace();
    if !tokens.has_next_token() {
        return None;
    }
    if has_direction || interpolation_method.is_some() {
        if !tokens.next_token().is_comma() {
            return None;
        }
        tokens.discard_a_token();
    }
    let (color_stop_list, color_syntax) = parse_color_stop_list(context, property, &mut tokens, false)?;
    Some(StyleValueData::LinearGradient(StyleValueBox::new(
        LinearGradientPayload {
            has_direction_value: direction_value.is_some(),
            direction_value: optional_retained(direction_value),
            side_or_corner,
            color_stop_list,
            gradient_type: u8::from(webkit.is_some()),
            repeating: repeating.is_some(),
            color_interpolation_method: optional_retained(interpolation_method),
            color_syntax,
        },
    )))
}

// https://drafts.csswg.org/css-images-4/#conic-gradients
// conic-gradient( [ [ [ from [ <angle> | <zero> ] ]? [ at <position> ]? ] || <color-interpolation-method> ]? , <angular-color-stop-list> )
fn parse_conic_gradient(
    context: &ParseContext,
    property: u16,
    name: &[u16],
    arguments: &[ComponentValue],
) -> Option<StyleValueData> {
    let (repeating, name) = strip_ascii_prefix(name, b"repeating-").map_or((false, name), |name| (true, name));
    if !equals_ascii_case_insensitive(name, b"conic-gradient") {
        return None;
    }
    let mut tokens = TokenStream::new(arguments);
    tokens.discard_whitespace();
    if !tokens.has_next_token() {
        return None;
    }
    let mut from_angle = None;
    let mut position = None;
    let mut interpolation_method = None;
    while let Some(identifier) = tokens.next_token().ident() {
        if equals_ascii_case_insensitive(identifier, b"from") {
            if from_angle.is_some() || position.is_some() {
                return None;
            }
            tokens.discard_a_token();
            tokens.discard_whitespace();
            let mut angle_tokens = tokens.clone();
            from_angle = parse_angle_from_stream(context, property, &mut angle_tokens, NumericRange::INFINITE);
            if from_angle.is_some() {
                tokens = angle_tokens;
            } else if matches!(tokens.next_token().kind, ComponentKind::Token(ParserTokenKind::Number { value, .. }) if value == 0.0)
            {
                tokens.discard_a_token();
                from_angle = Some(StyleValueData::Angle { value: 0.0, unit: 0 });
            } else {
                return None;
            }
        } else if equals_ascii_case_insensitive(identifier, b"at") {
            if position.is_some() {
                return None;
            }
            tokens.discard_a_token();
            position = Some(parse_position_from_stream(context, property, &mut tokens, false)?);
        } else if equals_ascii_case_insensitive(identifier, b"in") {
            if interpolation_method.is_some() {
                return None;
            }
            interpolation_method = Some(parse_color_interpolation_method(&mut tokens)?);
        } else {
            break;
        }
        tokens.discard_whitespace();
        if !tokens.has_next_token() {
            return None;
        }
    }
    if from_angle.is_some() || position.is_some() || interpolation_method.is_some() {
        if !tokens.next_token().is_comma() {
            return None;
        }
        tokens.discard_a_token();
    }
    let (color_stop_list, color_syntax) = parse_color_stop_list(context, property, &mut tokens, true)?;
    Some(StyleValueData::ConicGradient(StyleValueBox::new(
        ConicGradientPayload {
            from_angle: optional_retained(from_angle),
            position: retained(position.unwrap_or_else(center_position)),
            color_stop_list,
            repeating,
            color_interpolation_method: optional_retained(interpolation_method),
            color_syntax,
        },
    )))
}

fn default_radial_size() -> StyleValueData {
    radial_size_with_extent(2)
}

fn radial_size_with_extent(extent: u8) -> StyleValueData {
    StyleValueData::RadialSize(StyleValueBox::new(RadialSizePayload {
        component_count: 1,
        is_extent_0: true,
        extent_0: extent,
        value_0: RetainedStyleValueData::none(),
        is_extent_1: false,
        extent_1: 0,
        value_1: RetainedStyleValueData::none(),
    }))
}

fn parse_ending_shape(tokens: &mut TokenStream<'_>) -> Option<u8> {
    let start = tokens.current_index();
    tokens.discard_whitespace();
    let Some(identifier) = tokens.next_token().ident() else {
        tokens.position = start;
        return None;
    };
    let shape = if equals_ascii_case_insensitive(identifier, b"circle") {
        0
    } else if equals_ascii_case_insensitive(identifier, b"ellipse") {
        1
    } else {
        tokens.position = start;
        return None;
    };
    tokens.discard_a_token();
    Some(shape)
}

fn radial_size_shape(size: &StyleValueData) -> Option<(u8, bool)> {
    let StyleValueData::RadialSize(radial_size_payload) = size else {
        return None;
    };
    let RadialSizePayload {
        component_count,
        is_extent_0,
        ..
    } = &**radial_size_payload;
    Some((*component_count, *is_extent_0))
}

// https://compat.spec.whatwg.org/#css-gradients-webkit-radial-gradient
// https://www.w3.org/TR/2011/WD-css3-images-20110217/#radial-gradients
fn parse_webkit_radial_gradient(
    context: &ParseContext,
    property: u16,
    name: &[u16],
    arguments: &[ComponentValue],
) -> Option<StyleValueData> {
    use crate::css::css_enums::{keyword, keyword_from_ascii_case_insensitive};
    let (repeating, name) = strip_ascii_prefix(name, b"repeating-").map_or((false, name), |name| (true, name));
    if !equals_ascii_case_insensitive(name, b"radial-gradient") {
        return None;
    }
    let mut tokens = TokenStream::new(arguments);
    let position = parse_position_from_stream(context, property, &mut tokens, false);
    if position.is_some() {
        // The legacy syntax only accepts one- or two-component positions.
        if arguments[..tokens.current_index()]
            .iter()
            .filter(|token| !token.is_whitespace())
            .count()
            > 2
        {
            return None;
        }
        tokens.discard_whitespace();
        if !tokens.next_token().is_comma() {
            return None;
        }
        tokens.discard_a_token();
    }

    let mut ending_shape = None;
    let mut size_keyword = None;
    let mut extent = 2;
    loop {
        tokens.discard_whitespace();
        if ending_shape.is_none()
            && let Some(shape) = parse_ending_shape(&mut tokens)
        {
            ending_shape = Some(shape);
            continue;
        }
        let Some(identifier) = tokens.next_token().ident() else {
            break;
        };
        let Some(code) = keyword_from_ascii_case_insensitive(identifier) else {
            break;
        };
        match code {
            code @ (keyword::CLOSEST_CORNER
            | keyword::CLOSEST_SIDE
            | keyword::FARTHEST_CORNER
            | keyword::FARTHEST_SIDE
            | keyword::CONTAIN
            | keyword::COVER)
                if size_keyword.is_none() =>
            {
                size_keyword = Some(code);
                extent = match code {
                    keyword::CLOSEST_CORNER => 0,
                    keyword::CLOSEST_SIDE | keyword::CONTAIN => 1,
                    keyword::FARTHEST_SIDE => 3,
                    _ => 2,
                };
                tokens.discard_a_token();
            }
            _ => break,
        }
    }
    let has_shape_or_size = ending_shape.is_some() || size_keyword.is_some();
    let size = if has_shape_or_size {
        size_keyword = Some(size_keyword.unwrap_or(keyword::COVER));
        radial_size_with_extent(extent)
    } else if let Some(size) = parse_radial_size(context, property, &mut tokens) {
        let StyleValueData::RadialSize(payload) = &size else {
            unreachable!()
        };
        if payload.component_count != 2 || payload.is_extent_0 || payload.is_extent_1 {
            return None;
        }
        size
    } else {
        default_radial_size()
    };
    let has_radii = radial_size_shape(&size)?.0 == 2;
    tokens.discard_whitespace();
    if has_shape_or_size || has_radii {
        if !tokens.next_token().is_comma() {
            return None;
        }
        tokens.discard_a_token();
    }

    let mut stops = Vec::new();
    for stop in arguments[tokens.current_index()..].split(ComponentValue::is_comma) {
        let mut stop_tokens = TokenStream::new(stop);
        stop_tokens.discard_whitespace();
        let color = retained(parse_color_value(context, property, &mut stop_tokens, false)?);
        let mut positions = Vec::new();
        stop_tokens.discard_whitespace();
        while stop_tokens.has_next_token() && positions.len() < 2 {
            positions.push(retained(parse_length_percentage_from_stream(
                context,
                property,
                &mut stop_tokens,
                NumericRange::INFINITE,
                NumericRange::INFINITE,
            )?));
            stop_tokens.discard_whitespace();
        }
        if stop_tokens.has_next_token() {
            return None;
        }
        if positions.is_empty() {
            positions.push(RetainedStyleValueData::none());
        }
        for position in positions {
            stops.push(RetainedColorStop::from_retained_values(
                RetainedStyleValueData::none(),
                color.clone(),
                position,
                RetainedStyleValueData::none(),
            ));
        }
    }
    Some(StyleValueData::RadialGradient(StyleValueBox::new(
        RadialGradientPayload {
            ending_shape: ending_shape.unwrap_or(1),
            webkit: true,
            has_explicit_position: position.is_some(),
            webkit_size_keyword: size_keyword.unwrap_or(0),
            size: retained(size),
            position: retained(position.unwrap_or_else(center_position)),
            color_stop_list: RetainedColorStopList::from_vec(stops),
            repeating,
            color_interpolation_method: RetainedStyleValueData::none(),
            color_syntax: 0,
        },
    )))
}

// https://drafts.csswg.org/css-images-4/#radial-gradients
// <radial-gradient-syntax> = [ [ [ <radial-shape> || <radial-size> ]? [ at <position> ]? ] || <color-interpolation-method> ]? , <color-stop-list>
fn parse_radial_gradient(
    context: &ParseContext,
    property: u16,
    name: &[u16],
    arguments: &[ComponentValue],
) -> Option<StyleValueData> {
    if let Some(name) = strip_ascii_prefix(name, b"-webkit-") {
        return parse_webkit_radial_gradient(context, property, name, arguments);
    }
    let (repeating, name) = strip_ascii_prefix(name, b"repeating-").map_or((false, name), |name| (true, name));
    if !equals_ascii_case_insensitive(name, b"radial-gradient") {
        return None;
    }
    let mut tokens = TokenStream::new(arguments);
    tokens.discard_whitespace();
    if !tokens.has_next_token() {
        return None;
    }
    let mut expect_comma = false;
    let mut interpolation_method = parse_color_interpolation_method(&mut tokens);
    tokens.discard_whitespace();
    let mut ending_shape = parse_ending_shape(&mut tokens);
    let mut size = parse_radial_size(context, property, &mut tokens);
    if ending_shape.is_none() && size.is_some() {
        ending_shape = parse_ending_shape(&mut tokens);
    }
    if size.is_some() {
        expect_comma = true;
    }
    let size = size.take().unwrap_or_else(default_radial_size);
    let (component_count, first_is_extent) = radial_size_shape(&size)?;
    let ending_shape = if let Some(shape) = ending_shape {
        expect_comma = true;
        if (shape == 0 && component_count != 1) || (shape == 1 && component_count != 2 && !first_is_extent) {
            return None;
        }
        shape
    } else {
        u8::from(component_count != 1 || first_is_extent)
    };
    tokens.discard_whitespace();
    if !tokens.has_next_token() {
        return None;
    }
    let mut position = None;
    if tokens
        .next_token()
        .ident()
        .is_some_and(|identifier| equals_ascii_case_insensitive(identifier, b"at"))
    {
        tokens.discard_a_token();
        position = Some(parse_position_from_stream(context, property, &mut tokens, false)?);
        expect_comma = true;
    }
    tokens.discard_whitespace();
    if interpolation_method.is_none() {
        interpolation_method = parse_color_interpolation_method(&mut tokens);
        tokens.discard_whitespace();
    }
    if interpolation_method.is_some() {
        expect_comma = true;
    }
    if !tokens.has_next_token() {
        return None;
    }
    if expect_comma {
        if !tokens.next_token().is_comma() {
            return None;
        }
        tokens.discard_a_token();
    }
    let (color_stop_list, color_syntax) = parse_color_stop_list(context, property, &mut tokens, false)?;
    Some(StyleValueData::RadialGradient(StyleValueBox::new(
        RadialGradientPayload {
            ending_shape,
            webkit: false,
            has_explicit_position: false,
            webkit_size_keyword: 0,
            size: retained(size),
            position: retained(position.unwrap_or_else(center_position)),
            color_stop_list,
            repeating,
            color_interpolation_method: optional_retained(interpolation_method),
            color_syntax,
        },
    )))
}

fn consume_comma(tokens: &mut TokenStream<'_>) -> Option<()> {
    tokens.discard_whitespace();
    if !tokens.next_token().is_comma() {
        return None;
    }
    tokens.discard_a_token();
    Some(())
}

fn resolve_number(value: &StyleValueData) -> Option<f64> {
    match value {
        StyleValueData::Number { value } => Some(*value),
        calculated @ StyleValueData::Calculated(_) => resolve_calculated_number_without_context(calculated),
        _ => None,
    }
}

fn resolve_percentage(value: &StyleValueData) -> Option<f64> {
    match value {
        StyleValueData::Percentage { value } => Some(*value),
        calculated @ StyleValueData::Calculated(_) => resolve_calculated_percentage_without_context(calculated),
        _ => None,
    }
}

fn parse_percentage_from_stream(
    context: &ParseContext,
    property: u16,
    tokens: &mut TokenStream<'_>,
) -> Option<StyleValueData> {
    tokens.discard_whitespace();
    let value = tokens.next_token();
    let parsed = if let Some((name, values)) = value.function()
        && math_function_from_name(name).is_some()
    {
        parse_calculated_numeric_value_with_ranges(
            context,
            property,
            VALUE_TYPE_PERCENTAGE,
            None,
            NumericRange::INFINITE,
            name,
            values,
        )
    } else {
        parse_percentage_value(value, NumericRange::INFINITE)
    }?;
    tokens.discard_a_token();
    Some(parsed)
}

/// One coordinate of a -webkit-gradient() point. Keywords become percentages, and numbers are pixels.
#[derive(Clone, Copy)]
enum WebKitGradientCoordinate {
    Number(f64),
    Percentage(f64),
}

impl WebKitGradientCoordinate {
    fn partial_cmp(self, other: Self) -> Option<Ordering> {
        // NB: A pixel offset and a percentage of the gradient box can only be ordered when their signs differ or
        //     when one of them is zero.
        fn compare_number_to_percentage(number: f64, percentage: f64) -> Option<Ordering> {
            if number == 0.0 && percentage == 0.0 {
                Some(Ordering::Equal)
            } else if number <= 0.0 && percentage >= 0.0 {
                Some(Ordering::Less)
            } else if number >= 0.0 && percentage <= 0.0 {
                Some(Ordering::Greater)
            } else {
                None
            }
        }
        match (self, other) {
            (Self::Number(a), Self::Number(b)) | (Self::Percentage(a), Self::Percentage(b)) => a.partial_cmp(&b),
            (Self::Number(a), Self::Percentage(b)) => compare_number_to_percentage(a, b),
            (Self::Percentage(a), Self::Number(b)) => compare_number_to_percentage(b, a).map(Ordering::reverse),
        }
    }

    fn to_position_offset(self) -> StyleValueData {
        match self {
            Self::Number(value) => StyleValueData::Length {
                value,
                unit: px_length_unit(),
            },
            Self::Percentage(value) => StyleValueData::Percentage { value },
        }
    }
}

// FIXME: Other engines accept a calc() coordinate that cannot be resolved at parse time, and resolve it later.
fn parse_webkit_gradient_coordinate(
    context: &ParseContext,
    property: u16,
    tokens: &mut TokenStream<'_>,
    start_keyword: &[u8],
    end_keyword: &[u8],
) -> Option<WebKitGradientCoordinate> {
    tokens.discard_whitespace();
    if let Some(identifier) = tokens.next_token().ident() {
        let value = if equals_ascii_case_insensitive(identifier, start_keyword) {
            0.0
        } else if equals_ascii_case_insensitive(identifier, b"center") {
            50.0
        } else if equals_ascii_case_insensitive(identifier, end_keyword) {
            100.0
        } else {
            return None;
        };
        tokens.discard_a_token();
        return Some(WebKitGradientCoordinate::Percentage(value));
    }
    let mut number_tokens = tokens.clone();
    if let Some(number) = parse_number_from_stream(context, property, &mut number_tokens, NumericRange::INFINITE) {
        *tokens = number_tokens;
        return Some(WebKitGradientCoordinate::Number(resolve_number(&number)?));
    }
    let percentage = resolve_percentage(&parse_percentage_from_stream(context, property, tokens)?)?;
    Some(WebKitGradientCoordinate::Percentage(percentage))
}

struct WebKitGradientPoint {
    x: WebKitGradientCoordinate,
    y: WebKitGradientCoordinate,
}

impl WebKitGradientPoint {
    fn is_identical_to(&self, other: &Self) -> bool {
        self.x.partial_cmp(other.x) == Some(Ordering::Equal) && self.y.partial_cmp(other.y) == Some(Ordering::Equal)
    }

    fn to_position(&self) -> StyleValueData {
        position(
            edge(None, Some(self.x.to_position_offset())),
            edge(None, Some(self.y.to_position_offset())),
        )
    }
}

fn parse_webkit_gradient_point(
    context: &ParseContext,
    property: u16,
    tokens: &mut TokenStream<'_>,
) -> Option<WebKitGradientPoint> {
    let x = parse_webkit_gradient_coordinate(context, property, tokens, b"left", b"right")?;
    let y = parse_webkit_gradient_coordinate(context, property, tokens, b"top", b"bottom")?;
    Some(WebKitGradientPoint { x, y })
}

fn parse_webkit_gradient_radius(context: &ParseContext, property: u16, tokens: &mut TokenStream<'_>) -> Option<f64> {
    let radius = resolve_number(&parse_number_from_stream(
        context,
        property,
        tokens,
        NumericRange::NON_NEGATIVE,
    )?)?;
    (radius >= 0.0).then_some(radius)
}

// NB: A modern gradient line spans the whole gradient box, so this keeps only the direction from the first point to
//     the second point.
fn side_or_corner_from_points(first: &WebKitGradientPoint, second: &WebKitGradientPoint) -> u8 {
    let horizontal = first.x.partial_cmp(second.x).unwrap_or(Ordering::Equal);
    let vertical = first.y.partial_cmp(second.y).unwrap_or(Ordering::Equal);
    match (horizontal, vertical) {
        (Ordering::Less, Ordering::Less) => 7,
        (Ordering::Less, Ordering::Equal) => 3,
        (Ordering::Less, Ordering::Greater) => 5,
        (Ordering::Equal, Ordering::Greater) => 0,
        (Ordering::Equal, _) => 1,
        (Ordering::Greater, Ordering::Less) => 6,
        (Ordering::Greater, Ordering::Equal) => 2,
        (Ordering::Greater, Ordering::Greater) => 4,
    }
}

#[allow(clippy::arc_with_non_send_sync)]
fn shared_calc_node(node: CalcNode) -> Arc<CalcNode> {
    Arc::new(node)
}

fn hundred_percent_calc_node() -> Arc<CalcNode> {
    shared_calc_node(CalcNode::Numeric(CalcNumericValue::Percentage(100.0)))
}

/// Maps -webkit-gradient() color stop offsets onto the gradient line of the modern gradient.
#[derive(Clone, Copy)]
struct WebKitGradientStopMapping {
    start: f64,
    scale: f64,
}

impl WebKitGradientStopMapping {
    const IDENTITY: Self = Self { start: 0.0, scale: 1.0 };
}

/// The offset of a -webkit-gradient() color stop along the gradient line.
#[derive(Clone)]
enum WebKitGradientStopOffset {
    /// A fraction of the gradient line.
    Fraction(f64),
    /// A calculation in percentages of the gradient line.
    Calculation(Arc<CalcNode>),
}

impl WebKitGradientStopOffset {
    /// Maps the offset to `start + offset * scale`, where `start` is a percentage of the gradient line.
    fn mapped(self, mapping: WebKitGradientStopMapping) -> Self {
        let WebKitGradientStopMapping { start, scale } = mapping;
        if start == 0.0 && scale == 1.0 {
            return self;
        }
        match self {
            Self::Fraction(value) => Self::Fraction(start / 100.0 + value * scale),
            Self::Calculation(node) => Self::Calculation(shared_calc_node(CalcNode::Sum(vec![
                shared_calc_node(CalcNode::Numeric(CalcNumericValue::Percentage(start))),
                shared_calc_node(CalcNode::Product(vec![
                    node,
                    shared_calc_node(CalcNode::Numeric(CalcNumericValue::Number {
                        value: scale,
                        number_type: 0,
                    })),
                ])),
            ]))),
        }
    }

    fn to_style_value(&self) -> Option<StyleValueData> {
        match self {
            Self::Fraction(value) => Some(StyleValueData::Percentage { value: value * 100.0 }),
            Self::Calculation(node) => {
                let (_, numeric_type) = simplify_parsed_calculation(node.clone(), Some(VALUE_TYPE_LENGTH))?;
                Some(length_percentage_calculated_style_value(
                    node.clone(),
                    FfiNumericType::from_calc(Some(numeric_type)),
                ))
            }
        }
    }
}

// <number> | <percentage>, where a number is a fraction of the gradient line.
fn parse_webkit_gradient_stop_offset(
    context: &ParseContext,
    property: u16,
    tokens: &mut TokenStream<'_>,
) -> Option<WebKitGradientStopOffset> {
    let mut number_tokens = tokens.clone();
    if let Some(number) = parse_number_from_stream(context, property, &mut number_tokens, NumericRange::INFINITE) {
        *tokens = number_tokens;
        if let Some(value) = resolve_number(&number) {
            return Some(WebKitGradientStopOffset::Fraction(value));
        }
        let StyleValueData::Calculated(calculated) = &number else {
            return None;
        };
        return Some(WebKitGradientStopOffset::Calculation(shared_calc_node(
            CalcNode::Product(vec![
                calculated.rust_calculation.node_arc(),
                hundred_percent_calc_node(),
            ]),
        )));
    }
    let percentage = parse_percentage_from_stream(context, property, tokens)?;
    if let Some(value) = resolve_percentage(&percentage) {
        return Some(WebKitGradientStopOffset::Fraction(value / 100.0));
    }
    let StyleValueData::Calculated(calculated) = &percentage else {
        return None;
    };
    Some(WebKitGradientStopOffset::Calculation(
        calculated.rust_calculation.node_arc(),
    ))
}

// [ , [ from( <color> ) | to( <color> ) | color-stop( <number> | <percentage> , <color> ) ] ]*
fn parse_webkit_gradient_stops(
    context: &ParseContext,
    property: u16,
    tokens: &mut TokenStream<'_>,
    mapping: WebKitGradientStopMapping,
) -> Option<RetainedColorStopList> {
    let mut stops = Vec::new();
    loop {
        tokens.discard_whitespace();
        if !tokens.has_next_token() {
            break;
        }
        consume_comma(tokens)?;
        tokens.discard_whitespace();
        let (name, arguments) = tokens.consume_a_token().function()?;
        let mut stop_tokens = TokenStream::new(arguments);
        let offset = if equals_ascii_case_insensitive(name, b"from") {
            WebKitGradientStopOffset::Fraction(0.0)
        } else if equals_ascii_case_insensitive(name, b"to") {
            WebKitGradientStopOffset::Fraction(1.0)
        } else if equals_ascii_case_insensitive(name, b"color-stop") {
            let offset = parse_webkit_gradient_stop_offset(context, property, &mut stop_tokens)?;
            consume_comma(&mut stop_tokens)?;
            offset
        } else {
            return None;
        };
        // INTEROP: Other engines reject currentcolor as a -webkit-gradient() stop color.
        stop_tokens.discard_whitespace();
        if stop_tokens
            .next_token()
            .ident()
            .is_some_and(|identifier| equals_ascii_case_insensitive(identifier, b"currentcolor"))
        {
            return None;
        }
        let color = parse_color_value(context, property, &mut stop_tokens, false)?;
        stop_tokens.discard_whitespace();
        if stop_tokens.has_next_token() {
            return None;
        }
        stops.push((offset, color));
    }

    // NB: Without stops, the gradient is transparent. A single stop fills the whole gradient with its color.
    match stops.len() {
        0 => {
            let transparent: Vec<u16> = "transparent".encode_utf16().collect();
            for offset in [0.0, 1.0] {
                stops.push((
                    WebKitGradientStopOffset::Fraction(offset),
                    make_legacy_color([0, 0, 0, 0], Some(&transparent)),
                ));
            }
        }
        1 => stops.push(stops[0].clone()),
        _ => {
            // NB: Stops may come in any order. Only offsets known at parse time can be sorted. The offsets are
            //     fractions, so that 0.29 and 29% compare equal and keep their authored order.
            if stops
                .iter()
                .all(|(offset, _)| matches!(offset, WebKitGradientStopOffset::Fraction(_)))
            {
                stops.sort_by(|(a, _), (b, _)| match (a, b) {
                    (WebKitGradientStopOffset::Fraction(a), WebKitGradientStopOffset::Fraction(b)) => {
                        a.partial_cmp(b).unwrap_or(Ordering::Equal)
                    }
                    _ => Ordering::Equal,
                });
            }
        }
    }

    // NB: A negative scale reverses the stops. Reverse their order too, so that they still run along the gradient
    //     line, including stops that could not be sorted above.
    if mapping.scale < 0.0 {
        stops.reverse();
    }

    let stops = stops
        .into_iter()
        .map(|(offset, color)| {
            Some(RetainedColorStop::from_retained_values(
                RetainedStyleValueData::none(),
                retained(color),
                retained(offset.mapped(mapping).to_style_value()?),
                RetainedStyleValueData::none(),
            ))
        })
        .collect::<Option<Vec<_>>>()?;
    Some(RetainedColorStopList::from_vec(stops))
}

// INTEROP: -webkit-gradient() is the original WebKit gradient syntax. No specification defines it, but all engines
//          still parse it. It maps onto a modern linear or radial gradient in the sRGB color space.
// https://webkit.org/blog/175/introducing-css-gradients/
// -webkit-gradient( linear, <point>, <point> [, <stop>]* )
// -webkit-gradient( radial, <point>, <radius>, <point>, <radius> [, <stop>]* )
fn parse_webkit_gradient(
    context: &ParseContext,
    property: u16,
    arguments: &[ComponentValue],
) -> Option<StyleValueData> {
    let mut tokens = TokenStream::new(arguments);
    tokens.discard_whitespace();
    let kind = tokens.consume_a_token().ident()?;
    consume_comma(&mut tokens)?;
    if equals_ascii_case_insensitive(kind, b"linear") {
        let first = parse_webkit_gradient_point(context, property, &mut tokens)?;
        consume_comma(&mut tokens)?;
        let second = parse_webkit_gradient_point(context, property, &mut tokens)?;
        // NB: A gradient line of zero length paints the color of its last stop everywhere. Placing every stop at the
        //     start of the gradient line does the same.
        let mapping = if first.is_identical_to(&second) {
            WebKitGradientStopMapping { start: 0.0, scale: 0.0 }
        } else {
            WebKitGradientStopMapping::IDENTITY
        };
        let color_stop_list = parse_webkit_gradient_stops(context, property, &mut tokens, mapping)?;
        return Some(StyleValueData::LinearGradient(StyleValueBox::new(
            LinearGradientPayload {
                has_direction_value: false,
                direction_value: RetainedStyleValueData::none(),
                side_or_corner: side_or_corner_from_points(&first, &second),
                color_stop_list,
                gradient_type: 0,
                repeating: false,
                color_interpolation_method: RetainedStyleValueData::none(),
                color_syntax: COLOR_SYNTAX_LEGACY,
            },
        )));
    }
    if !equals_ascii_case_insensitive(kind, b"radial") {
        return None;
    }
    let first_point = parse_webkit_gradient_point(context, property, &mut tokens)?;
    consume_comma(&mut tokens)?;
    let first_radius = parse_webkit_gradient_radius(context, property, &mut tokens)?;
    consume_comma(&mut tokens)?;
    let second_point = parse_webkit_gradient_point(context, property, &mut tokens)?;
    consume_comma(&mut tokens)?;
    let second_radius = parse_webkit_gradient_radius(context, property, &mut tokens)?;

    // NB: A modern radial gradient has a single center, so this keeps the larger circle. The stops run from the
    //     smaller radius to the larger radius, so they are reversed when the larger circle is the first one.
    let (point, radius, smaller_radius, reverse_stops) = if second_radius >= first_radius {
        (second_point, second_radius, first_radius, false)
    } else {
        (first_point, first_radius, second_radius, true)
    };
    let smaller_radius_percentage = if radius > 0.0 {
        smaller_radius / radius * 100.0
    } else {
        0.0
    };
    let span = 1.0 - smaller_radius_percentage / 100.0;
    let mapping = if reverse_stops {
        WebKitGradientStopMapping {
            start: 100.0,
            scale: -span,
        }
    } else {
        WebKitGradientStopMapping {
            start: smaller_radius_percentage,
            scale: span,
        }
    };
    let color_stop_list = parse_webkit_gradient_stops(context, property, &mut tokens, mapping)?;
    Some(StyleValueData::RadialGradient(StyleValueBox::new(
        RadialGradientPayload {
            ending_shape: 0,
            webkit: false,
            has_explicit_position: false,
            webkit_size_keyword: 0,
            size: retained(StyleValueData::RadialSize(StyleValueBox::new(RadialSizePayload {
                component_count: 1,
                is_extent_0: false,
                extent_0: 0,
                value_0: retained(StyleValueData::Length {
                    value: radius,
                    unit: px_length_unit(),
                }),
                is_extent_1: false,
                extent_1: 0,
                value_1: RetainedStyleValueData::none(),
            }))),
            position: retained(point.to_position()),
            color_stop_list,
            repeating: false,
            color_interpolation_method: RetainedStyleValueData::none(),
            color_syntax: COLOR_SYNTAX_LEGACY,
        },
    )))
}

fn parse_gradient(
    context: &ParseContext,
    property: u16,
    name: &[u16],
    arguments: &[ComponentValue],
) -> Option<StyleValueData> {
    if equals_ascii_case_insensitive(name, b"-webkit-gradient") {
        return parse_webkit_gradient(context, property, arguments);
    }
    parse_linear_gradient(context, property, name, arguments)
        .or_else(|| parse_conic_gradient(context, property, name, arguments))
        .or_else(|| parse_radial_gradient(context, property, name, arguments))
}

pub(crate) fn parse_image_value(
    context: &ParseContext,
    property: u16,
    tokens: &mut TokenStream<'_>,
    allow_image_set: bool,
) -> Option<StyleValueData> {
    tokens.discard_whitespace();
    if let Some(url) = parse_url_value(context, tokens.next_token()) {
        tokens.discard_a_token();
        return image_from_url(url);
    }
    if allow_image_set
        && let Some((name, arguments)) = tokens.next_token().function()
        && (equals_ascii_case_insensitive(name, b"image-set")
            || equals_ascii_case_insensitive(name, b"-webkit-image-set"))
    {
        let parsed = parse_image_set(context, property, arguments)?;
        tokens.discard_a_token();
        return Some(parsed);
    }
    if let Some((name, arguments)) = tokens.next_token().function()
        && let Some(parsed) = parse_gradient(context, property, name, arguments)
    {
        tokens.discard_a_token();
        return Some(parsed);
    }
    if let Some((name, arguments)) = tokens.next_token().function()
        && equals_ascii_case_insensitive(name, b"light-dark")
        && let Some(parsed) = parse_light_dark_image(context, property, arguments, allow_image_set)
    {
        tokens.discard_a_token();
        return Some(parsed);
    }
    None
}

// https://drafts.csswg.org/css-color-5/#light-dark
fn parse_light_dark_image(
    context: &ParseContext,
    property: u16,
    arguments: &[ComponentValue],
    allow_image_set: bool,
) -> Option<StyleValueData> {
    // <light-dark-image> = light-dark( [ <image> | none ] , [ <image> | none ] )
    // FIXME: Support none, which computes to image(transparent).
    let mut tokens = TokenStream::new(arguments);
    let light = parse_image_value(context, property, &mut tokens, allow_image_set)?;
    tokens.discard_whitespace();
    if !tokens.next_token().is_comma() {
        return None;
    }
    tokens.discard_a_token();
    let dark = parse_image_value(context, property, &mut tokens, allow_image_set)?;
    tokens.discard_whitespace();
    if tokens.has_next_token() {
        return None;
    }
    Some(StyleValueData::LightDark(StyleValueBox::new(LightDarkPayload {
        color_base: crate::css::style_value::ColorBase {
            has_color_type: false,
            color_type: 0,
            color_syntax: crate::css::value_codes::COLOR_SYNTAX_MODERN,
        },
        light: retained(light),
        dark: retained(dark),
    })))
}

pub(crate) fn is_image_function_name(name: &[u16]) -> bool {
    [
        "image-set",
        "-webkit-image-set",
        "linear-gradient",
        "repeating-linear-gradient",
        "-webkit-linear-gradient",
        "-webkit-repeating-linear-gradient",
        "-webkit-gradient",
        "conic-gradient",
        "repeating-conic-gradient",
        "radial-gradient",
        "repeating-radial-gradient",
    ]
    .iter()
    .any(|expected| equals_ascii_case_insensitive(name, expected.as_bytes()))
}

fn parse_image_or_none(context: &ParseContext, property: u16, values: &[ComponentValue]) -> Option<StyleValueData> {
    let mut tokens = TokenStream::new(values);
    tokens.discard_whitespace();
    let parsed = if tokens
        .next_token()
        .ident()
        .is_some_and(|identifier| equals_ascii_case_insensitive(identifier, b"none"))
    {
        tokens.discard_a_token();
        StyleValueData::Keyword {
            keyword: crate::css::css_enums::keyword::NONE,
        }
    } else if property == property_id::MASK_IMAGE
        && let Some(url) = parse_url_value(context, tokens.next_token())
    {
        tokens.discard_a_token();
        if matches!(&url, StyleValueData::Url(url) if url.url.is_fragment()) {
            // NB: Preserve the SVG resource path for local mask references.
            url
        } else {
            image_from_url(url)?
        }
    } else {
        parse_image_value(context, property, &mut tokens, true)?
    };
    tokens.discard_whitespace();
    (!tokens.has_next_token()).then_some(parsed)
}

pub(crate) fn parse_image_property(context: &ParseContext, property: u16, values: &[ComponentValue]) -> ParseOutcome {
    if !matches!(
        property,
        property_id::BACKGROUND_IMAGE
            | property_id::MASK_IMAGE
            | property_id::LIST_STYLE_IMAGE
            | property_id::BORDER_IMAGE_SOURCE
    ) {
        return ParseOutcome::NotHandled;
    }
    let parsed = if matches!(property, property_id::BACKGROUND_IMAGE | property_id::MASK_IMAGE) {
        values
            .split(ComponentValue::is_comma)
            .map(|item| parse_image_or_none(context, property, item))
            .collect::<Option<Vec<_>>>()
            .map(value_list)
    } else {
        parse_image_or_none(context, property, values)
    };
    parsed.map_or(ParseOutcome::NotHandled, |parsed| {
        ParseOutcome::Parsed(StyleValueArc::new(parsed))
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::css::css_tokenizer::tokenize_for_parser;
    use crate::css::parser::component_value::consume_a_list_of_component_values;

    fn context() -> ParseContext<'static> {
        ParseContext::default()
    }

    fn parse(property: u16, source: &str) -> ParseOutcome {
        let values = consume_a_list_of_component_values(tokenize_for_parser(source.as_bytes())).unwrap();
        parse_image_property(&context(), property, &values)
    }

    #[test]
    fn parses_url_images_and_image_sets() {
        for source in [
            "url(image.png)",
            "image-set(url(one.png) 1x, \"two.png\" 2x)",
            "-webkit-image-set(url(one.png), url(two.png) 2x)",
        ] {
            assert!(matches!(
                parse(property_id::BORDER_IMAGE_SOURCE, source),
                ParseOutcome::Parsed(_)
            ));
        }
        assert!(matches!(
            parse(property_id::MASK_IMAGE, "url(#mask)"),
            ParseOutcome::Parsed(_)
        ));
    }

    #[test]
    fn parses_image_lists_and_rejects_invalid_options() {
        assert!(matches!(
            parse(property_id::BACKGROUND_IMAGE, "none, url(image.png)"),
            ParseOutcome::Parsed(_)
        ));
        let ParseOutcome::Parsed(value) = parse(property_id::BACKGROUND_IMAGE, "url(#mask)") else {
            panic!("fragment background image should parse");
        };
        let StyleValueData::ValueList { values, .. } = &*value else {
            panic!("background-image should be a list");
        };
        assert_eq!(values.as_slice().len(), 1);
        assert!(matches!(values.as_slice()[0].data(), StyleValueData::Image { .. }));
        for source in ["image-set()", "image-set(url(one.png) 1x 2x)"] {
            assert!(matches!(
                parse(property_id::BACKGROUND_IMAGE, source),
                ParseOutcome::NotHandled
            ));
        }
    }

    #[test]
    fn parses_linear_gradients() {
        for source in [
            "linear-gradient(#000, #fff)",
            "repeating-linear-gradient(to left top in oklab, #000 10% 20%, 30%, #fff)",
            "-webkit-linear-gradient(left, #000, #fff)",
            "-webkit-repeating-linear-gradient(45deg, #000, #fff)",
            "-webkit-gradient(linear, left top, right top, from(#000), to(#fff))",
            "-webkit-gradient(linear, 0 0, 0 100%, color-stop(0.5, #000), color-stop(calc(0.5 + 0.1 * sign(1em - 1px)), #fff))",
            "-webkit-gradient(linear, center top, center bottom)",
        ] {
            let ParseOutcome::Parsed(value) = parse(property_id::BACKGROUND_IMAGE, source) else {
                panic!("gradient should parse: {source}");
            };
            let StyleValueData::ValueList { values, .. } = &*value else {
                panic!("background-image should be a list");
            };
            assert!(matches!(
                values.as_slice()[0].data(),
                StyleValueData::LinearGradient { .. }
            ));
        }
    }

    #[test]
    fn parses_conic_and_radial_gradients() {
        for source in [
            "conic-gradient(from 0 at left top in hsl longer hue, #000 0, #fff 100%)",
            "repeating-conic-gradient(#000 0deg 20deg, 30deg, #fff)",
            "radial-gradient(circle closest-side at 20% 30% in oklab, #000, #fff)",
            "repeating-radial-gradient(ellipse 10px 20px, #000 10%, #fff 20%)",
            "-webkit-gradient(radial, 50 50, 0, 50% 50%, 10, from(#000), to(#fff))",
        ] {
            assert!(
                matches!(parse(property_id::MASK_IMAGE, source), ParseOutcome::Parsed(_)),
                "{source}"
            );
        }
    }

    #[test]
    fn rejects_invalid_gradient_components() {
        for source in [
            "linear-gradient(10%, #000)",
            "linear-gradient(to left right, #000, #fff)",
            "conic-gradient(from 10px, #000, #fff)",
            "radial-gradient(circle 10px 20px, #000, #fff)",
            "radial-gradient(ellipse 10px, #000, #fff)",
            "-webkit-gradient(conic, left top, right top, from(#000))",
            "-webkit-gradient(linear, top left, right top, from(#000))",
            "-webkit-gradient(linear, left top, right top from(#000))",
            "-webkit-gradient(linear, left top, right top, color-stop(10px, #000))",
            "-webkit-gradient(radial, 0 0, -1, 0 0, 10, from(#000))",
            "-webkit-gradient(linear, left top, right top, from(currentcolor))",
        ] {
            assert!(matches!(
                parse(property_id::BORDER_IMAGE_SOURCE, source),
                ParseOutcome::NotHandled
            ));
        }
    }
}