Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / css / css_import_rule.lucb

#==============================================================================================
#
#   css_import_rule - CSS::CSSImportRule: an @import rule and the style sheet it loads
#
#   DESCRIPTION:
#       Port of LibWeb/CSS/CSSImportRule.cpp (lines 1-310) and the inline members of
#       CSSImportRule.h (lines 22-70): the URL, layer, supports condition and media list of the
#       rule, fetching the imported style sheet (phase 2: fetch_a_style_resource reaches the
#       Fetch stubs), its serialization and the dump. CSSImportRule is also a critical
#       subresource of its parent style sheet (CSSStyleSheet::Subresource, a mixin here).
#
#       Copyright (c) 2021, the SerenityOS developers.
#       Copyright (c) 2021-2026, Sam Atkins <sam@ladybird.org>
#       Copyright (c) 2022-2024, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2025, Lorenz Ackermann <me@lorenzackermann.xyz>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

## AK/Debug.h's CSS_LOADER_DEBUG (0 in the reference build).
let css_loader_debug: bool = false

# mark: CSSImportRule.h =========================================================================

## Ported from Libraries/LibWeb/CSS/CSSImportRule.h:31 Web::CSS::CSSImportRule::url.
pub func css_import_rule_url(this: CssImportRule*) -> CssUrl:
    return this.m_url

## Ported from Libraries/LibWeb/CSS/CSSImportRule.h:31 Web::CSS::CSSImportRule::href.
pub func css_import_rule_href(this: CssImportRule*) -> ak.String:
    return css_url_url(&this.m_url)

## Ported from Libraries/LibWeb/CSS/CSSImportRule.h:34 Web::CSS::CSSImportRule::loaded_style_sheet.
pub func css_import_rule_loaded_style_sheet(this: CssImportRule*) -> CssCssStyleSheet*?:
    return this.m_style_sheet

## Ported from Libraries/LibWeb/CSS/CSSImportRule.h:34 Web::CSS::CSSImportRule::loaded_style_sheet (const).
pub func css_import_rule_loaded_style_sheet_const(this: CssImportRule*) -> CssCssStyleSheet*?:
    return this.m_style_sheet

## Ported from Libraries/LibWeb/CSS/CSSImportRule.h:36 Web::CSS::CSSImportRule::style_sheet_for_bindings.
pub func css_import_rule_style_sheet_for_bindings(this: CssImportRule*) -> CssCssStyleSheet*?:
    return this.m_style_sheet

## Ported from Libraries/LibWeb/CSS/CSSImportRule.h:43 Web::CSS::CSSImportRule::internal_layer_name.
pub func css_import_rule_internal_layer_name(this: CssImportRule*) -> ak.FlyString?:
    return this.m_layer_internal

## Ported from Libraries/LibWeb/CSS/CSSImportRule.h:55 Web::CSS::CSSImportRule::parent_style_sheet_for_subresource (override).
pub func css_import_rule_parent_style_sheet_for_subresource_impl(base: CssStyleSheetSubresource*) -> CssCssStyleSheet*?:
    let this = css_import_rule_from_subresource(base)
    return this.css_rule_base.m_parent_style_sheet

## The CSSImportRule a Subresource mixin lives in (C++'s `this` adjustment from the second base).
func css_import_rule_from_subresource(subresource: CssStyleSheetSubresource*) -> CssImportRule*:
    return (CssImportRule*)((u8*)subresource - memory.offset_of(CssImportRule, subresource))

## CSSImportRule::visit_edges overrides Subresource::visit_edges too (one C++ override of both bases'
## virtuals): the mixin's slot visits the whole rule.
func css_import_rule_subresource_visit_edges_impl(base: CssStyleSheetSubresource*, visitor: gc.CellVisitor*):
    css_import_rule_visit_edges_impl(css_import_rule_from_subresource(base).cell(), visitor)

# mark: Construction ============================================================================

## Ported from Libraries/LibWeb/CSS/CSSImportRule.cpp:31 Web::CSS::CSSImportRule::create.
pub func css_import_rule_create(realm: Realm*, url: CssUrl, document: DomDocument*?, layer: ak.FlyString?, supports: CssSupports*?, media: CssMediaList*) -> CssImportRule*:
    return realm_create_css_import_rule(realm, realm, url, document, layer, supports, media)

## Ported from Libraries/LibWeb/CSS/CSSImportRule.cpp:32 Web::CSS::CSSImportRule::CSSImportRule.
pub func css_import_rule_construct(this: CssImportRule*, realm: Realm*, url: CssUrl, document: DomDocument*?, layer: ak.FlyString?, supports: CssSupports*?, media: CssMediaList*):
    css_rule_construct(this.css_rule(), realm, CssRuleType.import_)
    this.subresource.vtable = &css_import_rule_subresource_vtable
    this.m_url = url
    this.m_document = document
    this.m_layer = layer
    this.m_supports = supports
    this.m_media = media

    if let layer_name = this.m_layer:
        if ak.fly_string_is_empty(&layer_name):
            this.m_layer_internal = css_layer_block_rule_next_unique_anonymous_layer_name()
            return
    this.m_layer_internal = this.m_layer

## Ported from Libraries/LibWeb/CSS/CSSImportRule.cpp:53 Web::CSS::CSSImportRule::initialize (override).
pub func css_import_rule_initialize_impl(base: JsCell*, realm: Realm*):
    web_set_prototype_for_interface(base, realm, BindInterfaceName.css_import_rule)
    js_cell_initialize_impl(base, realm)

## Ported from Libraries/LibWeb/CSS/CSSImportRule.cpp:59 Web::CSS::CSSImportRule::visit_edges (override).
pub func css_import_rule_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (CssImportRule*)base
    css_rule_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_t(visitor, this.m_document)
    gc.cell_visitor_visit_t_2(visitor, this.m_media)
    gc.cell_visitor_visit_t(visitor, this.m_style_sheet)

## Ported from Libraries/LibWeb/CSS/CSSImportRule.cpp:67 Web::CSS::CSSImportRule::set_parent_style_sheet (override).
pub func css_import_rule_set_parent_style_sheet_impl(base: CssRule*, parent_style_sheet: CssCssStyleSheet*?):
    let this = (CssImportRule*)base
    if let old_parent = this.css_rule_base.m_parent_style_sheet:
        css_css_style_sheet_remove_critical_subresource(old_parent, &this.subresource)

    css_rule_set_parent_style_sheet_impl(base, parent_style_sheet)

    if let new_parent = this.css_rule_base.m_parent_style_sheet:
        css_css_style_sheet_add_critical_subresource(new_parent, &this.subresource)

    if let style_sheet = this.m_style_sheet:
        if let parent = parent_style_sheet:
            let owners = css_css_style_sheet_owning_documents_or_shadow_roots(parent)
            for owning_document_or_shadow_root in ak.hash_table_begin_const(&owners):
                css_css_style_sheet_add_owning_document_or_shadow_root(style_sheet, *owning_document_or_shadow_root else trap("null owner"))

    if css_style_sheet_subresource_loading_state(&this.subresource) != CssStyleSheetLoadingState.unloaded:
        return

    # Only try to fetch if we now have a parent
    if parent_style_sheet != none:
        css_import_rule_fetch(this)

# mark: Serialization ===========================================================================

## Ported from Libraries/LibWeb/CSS/CSSImportRule.cpp:91 Web::CSS::CSSImportRule::serialized (override).
# https://www.w3.org/TR/cssom/#serialize-a-css-rule
pub func css_import_rule_serialized_impl(base: CssRule*) -> ak.String:
    let this = (CssImportRule*)base
    var builder = ak.string_builder_new()
    # The result of concatenating the following:

    # 1. The string "@import" followed by a single SPACE (U+0020).
    ak.string_builder_append(&builder, "@import ")

    # 2. The result of performing serialize a URL on the rule’s location.
    let url_text = css_url_to_string(&this.m_url)
    ak.string_builder_append_string_view(&builder, ak.string_bytes_as_string_view(&url_text))

    # AD-HOC: Serialize the rule's layer if it exists.
    if let layer = this.m_layer:
        if ak.fly_string_is_empty(&layer):
            ak.string_builder_append(&builder, " layer")
        else:
            dump_appendff(&builder, " layer({})", [css_arg_fly_string(&layer)])

    # AD-HOC: Serialize the rule's supports condition if it exists.
    #         This isn't currently specified, but major browsers include this in their serialization of import rules
    if let supports = this.m_supports:
        let supports_text = css_supports_to_string(supports)
        dump_appendff(&builder, " supports({})", [css_arg_string(&supports_text)])

    # 3. If the rule’s associated media list is not empty, a single SPACE (U+0020) followed by the result of performing serialize a media query list on the media list.
    if css_media_list_length(this.m_media) != 0:
        let media_text = css_media_list_media_text(this.m_media)
        dump_appendff(&builder, " {}", [css_arg_string(&media_text)])

    # 4. The string ";", i.e., SEMICOLON (U+003B).
    ak.string_builder_append_u8(&builder, ';')

    return ak.string_builder_to_string(&builder) else trap("MUST: StringBuilder::to_string")

# mark: Fetching ================================================================================

## The captures of fetch()'s processResponse lambda.
struct CssImportRuleFetchProcessResponse:
    var strong_this: CssImportRule*
    var parent_style_sheet: CssCssStyleSheet*
    var document: DomDocument*?

## fetch()'s ScopeGuard: stop delaying the load event, and report the loading state.
func css_import_rule_fetch_finished(strong_this: CssImportRule*, document: DomDocument*?):
    # AD-HOC: Stop delaying the load event.
    dom_document_remove_pending_css_import_rule(document else trap("null document"), strong_this)
    if css_style_sheet_subresource_loading_state(&strong_this.subresource) != CssStyleSheetLoadingState.error_:
        # If we have no critical subresources, or they're loaded already, we can report that immediately.
        let sheet_loading_state = css_css_style_sheet_loading_state(strong_this.m_style_sheet else trap("null m_style_sheet"))
        if sheet_loading_state == CssStyleSheetLoadingState.loaded or sheet_loading_state == CssStyleSheetLoadingState.error_:
            css_style_sheet_subresource_set_loading_state(&strong_this.subresource, sheet_loading_state)

## fetch()'s processResponse lambda.
func css_import_rule_fetch_process_response(context: void*?, response: FetchResponse*, maybe_byte_stream: FetchAlgorithmsBodyBytes):
    let captures = (CssImportRuleFetchProcessResponse*)(context else trap("no captures"))
    let strong_this = captures.strong_this
    let parent_style_sheet = captures.parent_style_sheet
    defer css_import_rule_fetch_finished(strong_this, captures.document)

    # 1. If byteStream is not a byte stream, return.
    var byte_stream: ak.ByteBuffer? = none
    match maybe_byte_stream:
        .byte_buffer(bytes): byte_stream = bytes
        _: _ = response
    if byte_stream == none:
        # AD-HOC: This means the fetch failed, so we should report this as a load failure.
        css_style_sheet_subresource_set_loading_state(&strong_this.subresource, CssStyleSheetLoadingState.error_)
        return
    let bytes = byte_stream else trap("unreachable")

    # FIXME: 2. If parentStylesheet is in quirks mode and response is CORS-same-origin, let content type be "text/css".
    #           Otherwise, let content type be the Content Type metadata of response.
    let content_type = "text/css"

    # 3. If content type is not "text/css", return.
    if content_type != "text/css":
        if css_loader_debug:
            ak.dbgln(f"CSSImportRule: Rejecting loaded style sheet; content type isn't text/css; is: '{content_type}'")
        return

    # 4. Let importedStylesheet be the result of parsing byteStream given parsedUrl.
    # FIXME: Tidy up our parsing API. For now, do the decoding here.
    # FIXME: Spec issue: parsedURL is not defined - we instead need to get that from the response.
    #        https://github.com/w3c/csswg-drafts/issues/12288
    let url = fetch_response_url(fetch_response_unsafe_response(response)) else trap("null response URL")

    var mime_type_charset: ak.String? = none
    if let extracted_mime_type = fetch_extract_mime_type(fetch_response_header_list(response)):
        if let charset = ak.ordered_hash_map_get_k_const(mime_type_parameters(&extracted_mime_type), ak.string_from_str("charset")):
            mime_type_charset = *charset
    # The environment encoding of an imported style sheet is the encoding of the style sheet that imported it. [css-syntax-3]
    # FIXME: Save encoding on Stylesheet to get it here
    let environment_encoding: ak.StringView? = none
    let decoded = css_decode_bytes(environment_encoding, mime_type_charset, &bytes) catch _:
        if css_loader_debug:
            let url_text = web_url.url_to_string(&url)
            ak.dbgln(f"CSSImportRule: Failed to decode CSS file: {ak.string_view_text(ak.string_bytes_as_string_view(&url_text))}")
        return
    var parsing_params: CssParsingParams = ---
    css_parsing_params_construct_dom_document(&parsing_params, strong_this.m_document else trap("null document"))
    let imported_style_sheet = parse_css_stylesheet(parsing_params, ak.string_bytes_as_string_view(&decoded), url, strong_this.m_media)

    # 5. Set importedStylesheet’s origin-clean flag to parentStylesheet’s origin-clean flag.
    css_style_sheet_set_origin_clean(imported_style_sheet.css_style_sheet(), css_style_sheet_is_origin_clean(parent_style_sheet.css_style_sheet()))

    # 6. If response is not CORS-same-origin, unset importedStylesheet’s origin-clean flag.
    if not fetch_response_is_cors_cross_origin(response):
        css_style_sheet_set_origin_clean(imported_style_sheet.css_style_sheet(), false)

    # 7. Set rule’s styleSheet to importedStylesheet.
    css_import_rule_set_style_sheet(strong_this, imported_style_sheet)

## Ported from Libraries/LibWeb/CSS/CSSImportRule.cpp:127 Web::CSS::CSSImportRule::fetch.
# https://drafts.csswg.org/css-cascade-4/#fetch-an-import
func css_import_rule_fetch(this: CssImportRule*):
    if css_loader_debug:
        let url_text = css_url_to_string(&this.m_url)
        ak.dbgln(f"CSSImportRule: Loading import URL: {ak.string_view_text(ak.string_bytes_as_string_view(&url_text))}")
    # To fetch an @import, given an @import rule rule:

    # 1. Let parentStylesheet be rule’s parent CSS style sheet. [CSSOM]
    let parent_style_sheet = css_rule_parent_style_sheet(this.css_rule()) else trap("VERIFY: parent_style_sheet()")

    # 2. If rule has a <supports-condition>, and that condition is not true, return.
    if let supports = this.m_supports:
        if not css_supports_matches(supports):
            return

    # AD-HOC: Track pending import rules to block rendering until they are done.
    dom_document_add_pending_css_import_rule(this.m_document else trap("null document"), this)
    css_style_sheet_subresource_set_loading_state(&this.subresource, CssStyleSheetLoadingState.loading)

    # 3. Fetch a style resource from rule’s URL, with ruleOrDeclaration rule, destination "style", CORS mode "no-cors", and
    #    processResponse being the following steps given response response and byte stream, null or failure byteStream:
    let rule_or_declaration = CssRuleOrDeclaration(environment_settings_object = html_relevant_settings_object_js_object((JsObject*)parent_style_sheet),
                                                   value = .css_rule_or_declaration_rule(CssRuleOrDeclarationRule(parent_style_sheet = parent_style_sheet)))
    var href_url: CssUrl = ---
    css_url_construct(&href_url, css_import_rule_href(this), CssUrlType.url, ak.Vector[CssRequestUrlModifier]())
    let captures = new CssImportRuleFetchProcessResponse(strong_this = this, parent_style_sheet = parent_style_sheet, document = this.m_document) else trap("out of memory")
    _ = css_fetch_a_style_resource(.css_url(href_url), rule_or_declaration, FetchRequestDestination.style, CssCorsMode.no_cors,
                                   ak.Function2[FetchResponse*, FetchAlgorithmsBodyBytes, unit](call = css_import_rule_fetch_process_response, context = captures))

## Ported from Libraries/LibWeb/CSS/CSSImportRule.cpp:218 Web::CSS::CSSImportRule::set_style_sheet.
func css_import_rule_set_style_sheet(this: CssImportRule*, style_sheet: CssCssStyleSheet*):
    this.m_style_sheet = style_sheet
    css_css_style_sheet_set_owner_css_rule(style_sheet, this.css_rule())

    if let parent = this.css_rule_base.m_parent_style_sheet:
        let owners = css_css_style_sheet_owning_documents_or_shadow_roots(parent)
        for owning_document_or_shadow_root in ak.hash_table_begin_const(&owners):
            css_css_style_sheet_add_owning_document_or_shadow_root(style_sheet, *owning_document_or_shadow_root else trap("null owner"))

    if let document = css_css_style_sheet_owning_document(style_sheet):
        css_css_style_sheet_load_pending_image_resources(style_sheet, document)

    css_css_style_sheet_invalidate_owners(style_sheet, DomStyleInvalidationReason.css_import_rule)

# mark: The CSSImportRule interface =============================================================

## Ported from Libraries/LibWeb/CSS/CSSImportRule.cpp:235 Web::CSS::CSSImportRule::media.
# https://drafts.csswg.org/cssom/#dom-cssimportrule-media
pub func css_import_rule_media(this: CssImportRule*) -> CssMediaList*:
    # The media attribute must return the value of the media attribute of the associated CSS style sheet.
    # AD-HOC: Return our own MediaList.
    #         https://github.com/w3c/csswg-drafts/issues/12063
    return this.m_media

## Ported from Libraries/LibWeb/CSS/CSSImportRule.cpp:244 Web::CSS::CSSImportRule::layer_name.
# https://drafts.csswg.org/cssom/#dom-cssimportrule-layername
pub func css_import_rule_layer_name(this: CssImportRule*) -> ak.FlyString?:
    # The layerName attribute must return the layer name declared in the at-rule itself, or an empty string if the
    # layer is anonymous, or null if the at-rule does not declare a layer.
    if this.m_layer == none:
        return none
    return this.m_layer

## Ported from Libraries/LibWeb/CSS/CSSImportRule.cpp:254 Web::CSS::CSSImportRule::supports_text.
# https://drafts.csswg.org/cssom/#dom-cssimportrule-supportstext
pub func css_import_rule_supports_text(this: CssImportRule*) -> ak.String?:
    # The supportsText attribute must return the <supports-condition> declared in the at-rule itself, or null if the
    # at-rule does not declare a supports condition.
    let supports = this.m_supports else return none
    return css_supports_to_string(supports)

## Ported from Libraries/LibWeb/CSS/CSSImportRule.cpp:263 Web::CSS::CSSImportRule::internal_qualified_layer_name.
pub func css_import_rule_internal_qualified_layer_name(this: CssImportRule*) -> ak.FlyString?:
    if this.m_layer == none:
        return none

    let parent_name = css_rule_parent_layer_internal_qualified_name(this.css_rule())
    let layer_internal = this.m_layer_internal else trap("VERIFY: m_layer_internal")
    if ak.fly_string_is_empty(&parent_name):
        return layer_internal
    return ak.fly_string_from_string(css_string_formatted("{}.{}", [css_arg_fly_string(&parent_name), css_arg_fly_string(&layer_internal)]))

## Ported from Libraries/LibWeb/CSS/CSSImportRule.cpp:274 Web::CSS::CSSImportRule::matches.
pub func css_import_rule_matches(this: CssImportRule*) -> bool:
    if let supports = this.m_supports:
        if not css_supports_matches(supports):
            return false
    return css_media_list_matches(this.m_media)

## Ported from Libraries/LibWeb/CSS/CSSImportRule.cpp:281 Web::CSS::CSSImportRule::dump (override).
pub func css_import_rule_dump_impl(base: CssRule*, builder: ak.StringBuilder*, indent_levels: i32):
    let this = (CssImportRule*)base
    css_rule_dump_impl(base, builder, indent_levels)

    dump_indent(builder, indent_levels + 1)
    let url_text = css_url_to_string(&this.m_url)
    dump_appendff(builder, "Document URL: {}\n", [css_arg_string(&url_text)])

    dump_indent(builder, indent_levels + 1)
    let loading_state_name = css_css_style_sheet_loading_state_name(css_style_sheet_subresource_loading_state(&this.subresource))
    dump_appendff(builder, "Loading state: {}\n", [ak.arg_string_view(loading_state_name)])

    if let layer = this.m_layer:
        let layer_internal = this.m_layer_internal else trap("VERIFY: m_layer_internal")
        dump_indent(builder, indent_levels + 1)
        dump_appendff(builder, "Layer: `{}` (internal: `{}`)\n", [css_arg_fly_string(&layer), css_arg_fly_string(&layer_internal)])

    if css_media_list_length(this.m_media) != 0:
        css_media_list_dump(this.m_media, builder, indent_levels + 1)

    if let supports = this.m_supports:
        css_supports_dump(supports, builder, indent_levels + 1)

    if let style_sheet = this.m_style_sheet:
        dump_sheet_string_builder(builder, style_sheet.css_style_sheet(), indent_levels + 1)
    else:
        dump_indent(builder, indent_levels + 1)
        ak.string_builder_append(builder, "Style sheet not loaded\n")