Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / css / serialize.lucb

#==============================================================================================
#
#   serialize - CSS serialization: declarations, component values, positional lists
#
#   DESCRIPTION:
#       Port of LibWeb/CSS/Serialize.cpp (lines 125-131 and 180-354) and the template of
#       Serialize.h (lines 33-46). The identifier, string, URL and number serializers (lines
#       18-178) are css_syntax's (DESIGN.md §4.1.3: tokens use them); this half needs the
#       engine's style values.
#
#       Copyright (c) 2021-2025, Sam Atkins <sam@ladybird.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

## Ported from Libraries/LibWeb/CSS/Serialize.cpp:126 Web::CSS::serialize_unicode_ranges.
# NOTE: No spec currently exists for serializing a <'unicode-range'>.
pub func css_serialize_unicode_ranges(builder: ak.StringBuilder*, unicode_ranges: const ak.Vector[web_fonts.UnicodeRange]*):
    css_serialize_a_comma_separated_list(builder, unicode_ranges, ak.Function2[ak.StringBuilder*, const web_fonts.UnicodeRange*, unit](call = css_serialize_unicode_range_item, context = none))

## The lambda of serialize_unicode_ranges: `serialize_a_string(builder, unicode_range.to_string())`.
func css_serialize_unicode_range_item(context: void*?, builder: ak.StringBuilder*, unicode_range: const web_fonts.UnicodeRange*):
    _ = context
    let text = web_fonts.unicode_range_to_string(unicode_range)
    css_syntax.serialize_a_string_string_builder(builder, ak.string_bytes_as_string_view(&text))

## Ported from Libraries/LibWeb/CSS/Serialize.h:36 Web::CSS::serialize_a_comma_separated_list.
# https://www.w3.org/TR/cssom/#serialize-a-comma-separated-list
pub func css_serialize_a_comma_separated_list[T](builder: ak.StringBuilder*, items: const ak.Vector[T]*, serialize_item: ak.Function2[ak.StringBuilder*, const T*, unit]):
    # To serialize a comma-separated list concatenate all items of the list in list order
    # while separating them by ", ", i.e., COMMA (U+002C) followed by a single SPACE (U+0020).
    for i in 0..<ak.vector_size(items):
        let item = ak.vector_at_const(items, i)
        ak.function2_call(&serialize_item, builder, item)
        if (i + 1) < ak.vector_size(items):
            ak.string_builder_append(builder, ", ")

## Ported from Libraries/LibWeb/CSS/Serialize.cpp:181 Web::CSS::serialize_a_css_declaration.
# https://drafts.csswg.org/cssom/#serialize-a-css-declaration
pub func css_serialize_a_css_declaration(property: ak.StringView, value: ak.StringView, important: css_syntax.Important = css_syntax.Important.no) -> ak.String:
    # 1. Let s be the empty string.
    var builder = ak.string_builder_new()

    # 2. Append property to s.
    # AD-HOC: There's no place currently on the spec where the property name properly escaped,
    #         and this needs to be done when custom properties have special characters.
    #         Related spec issues:
    #          - https://github.com/w3c/csswg-drafts/issues/11729
    #          - https://github.com/w3c/csswg-drafts/issues/12258
    css_syntax.serialize_an_identifier_string_builder(&builder, property)

    # 3. Append ": " (U+003A U+0020) to s.
    ak.string_builder_append(&builder, ": ")

    # 4. If value contains any non-whitespace characters, append value to s.
    if not ak.string_view_is_whitespace(&value):
        ak.string_builder_append_string_view(&builder, value)

    # 5. If the important flag is set, append " !important" (U+0020 U+0021 U+0069 U+006D U+0070 U+006F U+0072 U+0074
    #    U+0061 U+006E U+0074) to s.
    if important == css_syntax.Important.yes:
        ak.string_builder_append(&builder, " !important")

    # 6. Append ";" (U+003B) to s.
    ak.string_builder_append_u8(&builder, ';')

    # 7. Return s.
    return ak.string_builder_to_string_without_validation(&builder)

## Ported from Libraries/LibWeb/CSS/Serialize.cpp:214 Web::CSS::needs_comment_between.
# https://drafts.csswg.org/css-syntax/#serialization
func css_needs_comment_between(first: const css_syntax.ComponentValue*, second: const css_syntax.ComponentValue*) -> bool:
    # For any consecutive pair of tokens, if the first token shows up in the row headings of the following table, and
    # the second token shows up in the column headings, and there’s a ✗ in the cell denoted by the intersection of the
    # chosen row and column, the pair of tokens must be serialized with a comment between them.
    #
    # If the tokenizer preserves comments, and there were comments originally between the token pair, the preserved
    # comment(s) should be used; otherwise, an empty comment (/**/) must be inserted. (Preserved comments may be
    # reinserted even if the following tables don’t require a comment between two tokens.)
    #
    # Single characters in the row and column headings represent a <delim-token> with that value, except for "(",
    # which represents a (-token.
    #
    #            │ ident │ function │ url │ bad url │ - │ number │ percentage │ dimension │ CDC │ ( │ * │ %
    # ───────────┼───────┼──────────┼─────┼─────────┼───┼────────┼────────────┼───────────┼─────┼───┼───┼───
    # ident      │ ✗     │ ✗        │ ✗   │ ✗       │ ✗ │ ✗      │ ✗          │ ✗         │ ✗   │ ✗ │   │
    # at-keyword │ ✗     │ ✗        │ ✗   │ ✗       │ ✗ │ ✗      │ ✗          │ ✗         │ ✗   │   │   │
    # hash       │ ✗     │ ✗        │ ✗   │ ✗       │ ✗ │ ✗      │ ✗          │ ✗         │ ✗   │   │   │
    # dimension  │ ✗     │ ✗        │ ✗   │ ✗       │ ✗ │ ✗      │ ✗          │ ✗         │ ✗   │   │   │
    # #          │ ✗     │ ✗        │ ✗   │ ✗       │ ✗ │ ✗      │ ✗          │ ✗         │ ✗   │   │   │
    # -          │ ✗     │ ✗        │ ✗   │ ✗       │ ✗ │ ✗      │ ✗          │ ✗         │ ✗   │   │   │
    # number     │ ✗     │ ✗        │ ✗   │ ✗       │   │ ✗      │ ✗          │ ✗         │ ✗   │   │   │ ✗
    # @          │ ✗     │ ✗        │ ✗   │ ✗       │ ✗ │        │            │           │ ✗   │   │   │
    # .          │       │          │     │         │   │ ✗      │ ✗          │ ✗         │     │   │   │
    # +          │       │          │     │         │   │ ✗      │ ✗          │ ✗         │     │   │   │
    # /          │       │          │     │         │   │        │            │           │     │   │ ✗ │

    if css_syntax.component_value_is(first, .ident):
        if css_syntax.component_value_is_function(second):
            return true
        # NB: ( may also be part of a block.
        if css_component_value_is_paren_block(second):
            return true
        if not css_syntax.component_value_is_token(second):
            return false
        if css_syntax.component_value_is_delim(second, (u32)'-'):
            return true
        return css_token_type_is_one_of(css_component_value_token_type(second),
                                        [.ident, .url, .bad_url, .number, .percentage, .dimension, .cdc, .open_paren])

    if (css_syntax.component_value_is(first, .at_keyword) or css_syntax.component_value_is(first, .hash_) or css_syntax.component_value_is(first, .dimension) or css_syntax.component_value_is_delim(first, (u32)'#') or css_syntax.component_value_is_delim(first, (u32)'-')):
        if css_syntax.component_value_is_function(second):
            return true
        if not css_syntax.component_value_is_token(second):
            return false
        let second_token = css_syntax.component_value_token(second)
        if css_syntax.token_type(&second_token) == .delim:
            return css_syntax.token_delim(&second_token) == (u32)'-'
        return css_token_type_is_one_of(css_syntax.token_type(&second_token), [.ident, .url, .bad_url, .number, .percentage, .dimension, .cdc])

    if css_syntax.component_value_is(first, .number):
        if css_syntax.component_value_is_function(second):
            return true
        if not css_syntax.component_value_is_token(second):
            return false
        let second_token = css_syntax.component_value_token(second)
        if css_syntax.token_type(&second_token) == .delim:
            return css_syntax.token_delim(&second_token) == (u32)'%'
        return css_token_type_is_one_of(css_syntax.token_type(&second_token), [.ident, .url, .bad_url, .number, .percentage, .dimension, .cdc])

    if css_syntax.component_value_is_delim(first, (u32)'@'):
        if css_syntax.component_value_is_function(second):
            return true
        if not css_syntax.component_value_is_token(second):
            return false
        let second_token = css_syntax.component_value_token(second)
        if css_syntax.token_type(&second_token) == .delim:
            return css_syntax.token_delim(&second_token) == (u32)'-'
        return css_token_type_is_one_of(css_syntax.token_type(&second_token), [.ident, .url, .bad_url, .cdc])

    if css_syntax.component_value_is_delim(first, (u32)'.') or css_syntax.component_value_is_delim(first, (u32)'+'):
        return css_syntax.component_value_is(second, .number) or css_syntax.component_value_is(second, .percentage) or css_syntax.component_value_is(second, .dimension)

    if css_syntax.component_value_is_delim(first, (u32)'/'):
        return css_syntax.component_value_is_delim(second, (u32)'*')

    return false

## `first_is_one_of(type, ...)` over token types.
func css_token_type_is_one_of(type_: css_syntax.TokenType, types: const css_syntax.TokenType[]) -> bool:
    for candidate in types:
        if candidate == type_:
            return true
    return false

## Ported from Libraries/LibWeb/CSS/Serialize.cpp:304 Web::CSS::serialize_a_series_of_component_values.
# https://drafts.csswg.org/css-syntax/#serialization
pub func css_serialize_a_series_of_component_values(component_values: const css_syntax.ComponentValue[]) -> ak.String:
    var tokens = css_syntax.token_stream_create_span(component_values)
    var builder = ak.string_builder_new()

    while css_syntax.token_stream_has_next_token(&tokens):
        let current_token = css_syntax.token_stream_consume_a_token(&tokens)
        let next_token = css_syntax.token_stream_next_token(&tokens)
        let text = css_syntax.component_value_to_string(&current_token)
        ak.string_builder_append_string_view(&builder, ak.string_bytes_as_string_view(&text))
        if css_needs_comment_between(&current_token, &next_token):
            ak.string_builder_append(&builder, "/**/")

    return ak.string_builder_to_string_without_validation(&builder)

## Ported from Libraries/LibWeb/CSS/Serialize.cpp:320 Web::CSS::serialize_a_positional_value_list.
pub func css_serialize_a_positional_value_list(values: const ak.Vector[CssStyleValue*]*, mode: css_syntax.SerializationMode) -> ak.String:
    match ak.vector_size(values):
        2:
            let first_property_serialized = css_style_value_to_string(*ak.vector_at_const(values, 0), mode)
            let second_property_serialized = css_style_value_to_string(*ak.vector_at_const(values, 1), mode)

            if ak.string_equals(&first_property_serialized, &second_property_serialized):
                return first_property_serialized

            return css_string_formatted("{} {}", [css_arg_string(&first_property_serialized), css_arg_string(&second_property_serialized)])
        4:
            let first_property_serialized = css_style_value_to_string(*ak.vector_at_const(values, 0), mode)
            let second_property_serialized = css_style_value_to_string(*ak.vector_at_const(values, 1), mode)
            let third_property_serialized = css_style_value_to_string(*ak.vector_at_const(values, 2), mode)
            let fourth_property_serialized = css_style_value_to_string(*ak.vector_at_const(values, 3), mode)

            if (ak.string_equals(&first_property_serialized, &second_property_serialized) and ak.string_equals(&first_property_serialized, &third_property_serialized) and ak.string_equals(&first_property_serialized, &fourth_property_serialized)):
                return first_property_serialized

            if ak.string_equals(&first_property_serialized, &third_property_serialized) and ak.string_equals(&second_property_serialized, &fourth_property_serialized):
                return css_string_formatted("{} {}", [css_arg_string(&first_property_serialized), css_arg_string(&second_property_serialized)])

            if ak.string_equals(&second_property_serialized, &fourth_property_serialized):
                return css_string_formatted("{} {} {}", [css_arg_string(&first_property_serialized), css_arg_string(&second_property_serialized), css_arg_string(&third_property_serialized)])

            return css_string_formatted("{} {} {} {}", [css_arg_string(&first_property_serialized), css_arg_string(&second_property_serialized), css_arg_string(&third_property_serialized), css_arg_string(&fourth_property_serialized)])
        _:
            trap("VERIFY_NOT_REACHED")

## `MUST(String::formatted(fmtstr, arguments...))` for the CSS fragments of this module: AK's
## format string over ak's type-erased arguments (DESIGN.md §2.11).
func css_string_formatted(fmtstr: str, arguments: const ak.TypeErasedParameter[]) -> ak.String:
    var params = ak.type_erased_format_params_create(arguments)
    return ak.string_vformatted(ak.sv(fmtstr), &params) else trap("MUST: String::formatted")

## A String as an AK format argument (`{}` formats its bytes).
func css_arg_string(string: const ak.String*) -> ak.TypeErasedParameter:
    return ak.arg_string_view(ak.string_bytes_as_string_view(string))

## A FlyString as an AK format argument.
func css_arg_fly_string(string: const ak.FlyString*) -> ak.TypeErasedParameter:
    return ak.arg_string_view(ak.fly_string_bytes_as_string_view(string))