dymokomi/luce-browser-engine
Source of release 0.6.1
0.6.1 / src / web / css / css_style_sheet_1.lucb
#==============================================================================================
#
# css_style_sheet_1 - CSS::CSSStyleSheet: creation, the constructor, rule insertion/removal
#
# DESCRIPTION:
# Port of LibWeb/CSS/CSSStyleSheet.cpp (lines 1-323): create(), the CSSStyleSheet()
# constructor of the CSSOM, the constructor, visit_edges, insertRule(), deleteRule(),
# replace(), replaceSync(), addRule() and removeRule(). The rest of the file is
# css_style_sheet_2.
#
# Copyright (c) 2019-2022, Andreas Kling <andreas@ladybird.org>
# Copyright (c) 2022-2026, Sam Atkins <sam@ladybird.org>
# Copyright (c) 2024-2025, Tim Ledbetter <tim.ledbetter@ladybird.org>
# SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================
# mark: Creation ================================================================================
## Ported from Libraries/LibWeb/CSS/CSSStyleSheet.cpp:35 Web::CSS::CSSStyleSheet::create.
pub func css_css_style_sheet_create(realm: Realm*, rules: CssRuleList*, media: CssMediaList*, location: web_url.Url?) -> CssCssStyleSheet*:
return realm_create_css_css_style_sheet(realm, realm, rules, media, location)
## Ported from Libraries/LibWeb/CSS/CSSStyleSheet.cpp:41 Web::CSS::CSSStyleSheet::construct_impl.
# https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssstylesheet
pub func css_css_style_sheet_construct_impl(realm: Realm*, options: CssStyleSheetInit? = none) -> CssCssStyleSheet*!:
# 1. Construct a new CSSStyleSheet object sheet.
let no_rules = ak.Vector[CssRule*]()
let sheet = css_css_style_sheet_create(realm, css_rule_list_create(realm, ak.vector_span_const(&no_rules)), css_media_list_create(realm, ak.Vector[CssMediaQuery*]()), none)
let style_sheet = sheet.css_style_sheet()
# 2. Set sheet’s location to the base URL of the associated Document for the current principal global object.
let associated_document = html_window_document(as_html_window((gc.Cell*)realm_global_object(realm)))
css_style_sheet_set_location(style_sheet, dom_document_base_url(associated_document))
# 3. Set sheet’s stylesheet base URL to the baseURL attribute value from options.
if let init = options:
if let base_url = init.base_url:
var sheet_location_url: web_url.Url? = none
if let location = css_style_sheet_location(style_sheet):
sheet_location_url = location
# AD-HOC: This isn't explicitly mentioned in the specification, but multiple modern browsers do this.
var url: web_url.Url? = none
if let location_url = sheet_location_url:
url = web_url.url_complete_url(&location_url, ak.string_bytes_as_string_view(&base_url))
else:
url = web_url.parser_basic_parse(ak.string_bytes_as_string_view(&base_url))
if url == none:
try idl_throw(.idl_dom_exception(idl_not_allowed_error_create(realm, ak.utf16_string_from_str("Constructed style sheets must have a valid base URL"))))
css_css_style_sheet_set_base_url(sheet, url)
# 4. Set sheet’s parent CSS style sheet to null.
css_style_sheet_set_parent_css_style_sheet(style_sheet, none)
# 5. Set sheet’s owner node to null.
css_style_sheet_set_owner_node(style_sheet, none)
# 6. Set sheet’s owner CSS rule to null.
css_css_style_sheet_set_owner_css_rule(sheet, none)
# 7. Set sheet’s title to the empty string.
css_style_sheet_set_title(style_sheet, ak.string_from_str(""))
# 8. Unset sheet’s alternate flag.
css_style_sheet_set_alternate(style_sheet, false)
# 9. Set sheet’s origin-clean flag.
css_style_sheet_set_origin_clean(style_sheet, true)
# 10. Set sheet’s constructed flag.
css_css_style_sheet_set_constructed(sheet, true)
# 11. Set sheet’s Constructor document to the associated Document for the current global object.
css_css_style_sheet_set_constructor_document(sheet, associated_document)
# 12. If the media attribute of options is a string, create a MediaList object from the string and assign it as sheet’s media.
# Otherwise, serialize a media query list from the attribute and then create a MediaList object from the resulting string and set it as sheet’s media.
if let init = options:
match init.media:
.string(media):
css_style_sheet_set_media(style_sheet, media)
.css_media_list(media_list):
style_sheet.m_media = media_list else trap("null MediaList")
# 13. If the disabled attribute of options is true, set sheet’s disabled flag.
if let init = options:
if init.disabled:
css_style_sheet_set_disabled(style_sheet, true)
# 14. Return sheet
return sheet
# mark: Construction ============================================================================
## The `m_rules->on_change` lambda of the constructor: `recalculate_rule_caches()`.
func css_css_style_sheet_on_rules_change(context: void*?):
let this = (CssCssStyleSheet*)(context else trap("no style sheet"))
css_css_style_sheet_recalculate_rule_caches(this)
## Ported from Libraries/LibWeb/CSS/CSSStyleSheet.cpp:106 Web::CSS::CSSStyleSheet::CSSStyleSheet.
pub func css_css_style_sheet_construct(this: CssCssStyleSheet*, realm: Realm*, rules: CssRuleList*, media: CssMediaList*, location: web_url.Url?):
css_style_sheet_construct(this.css_style_sheet(), realm, media)
this.m_rules = rules
if location != none:
css_style_sheet_set_location(this.css_style_sheet(), location)
for rule in ak.vector_span(&rules.m_rules):
css_rule_set_parent_style_sheet(rule, this)
css_css_style_sheet_recalculate_rule_caches(this)
rules.on_change = ak.Function0[unit](call = css_css_style_sheet_on_rules_change, context = this)
## Ported from Libraries/LibWeb/CSS/CSSStyleSheet.cpp:125 Web::CSS::CSSStyleSheet::initialize (override).
pub func css_css_style_sheet_initialize_impl(base: JsCell*, realm: Realm*):
web_set_prototype_for_interface(base, realm, BindInterfaceName.css_style_sheet)
js_cell_initialize_impl(base, realm)
## Ported from Libraries/LibWeb/CSS/CSSStyleSheet.cpp:131 Web::CSS::CSSStyleSheet::visit_edges (override).
pub func css_css_style_sheet_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
let this = (CssCssStyleSheet*)base
css_style_sheet_visit_edges_impl(base, visitor)
gc.cell_visitor_visit_t(visitor, this.m_rules)
gc.cell_visitor_visit_t(visitor, this.m_owner_css_rule)
gc.cell_visitor_visit_t(visitor, this.m_default_namespace_rule)
gc.cell_visitor_visit_t(visitor, this.m_constructor_document)
for entry in ak.hash_map_begin_const(&this.m_namespace_rules):
gc.cell_visitor_visit_t(visitor, entry.value)
gc.cell_visitor_visit_vector(visitor, &this.m_import_rules)
gc.cell_visitor_visit_hash_table_nullable(visitor, &this.m_owning_documents_or_shadow_roots)
if let cache = this.m_shared_single_constructed_sheet_style_cache:
css_style_cache_visit_edges(cache, visitor)
for subresource in ak.vector_span(&this.m_critical_subresources):
css_style_sheet_subresource_visit_edges(subresource, visitor)
# mark: Inserting and removing rules ============================================================
## Ported from Libraries/LibWeb/CSS/CSSStyleSheet.cpp:148 Web::CSS::CSSStyleSheet::insert_rule.
# https://www.w3.org/TR/cssom/#dom-cssstylesheet-insertrule
pub func css_css_style_sheet_insert_rule(this: CssCssStyleSheet*, rule: ak.StringView, index: u32) -> u32!:
let realm = bind_platform_object_realm(this.bind_platform_object())
# FIXME: 1. If the origin-clean flag is unset, throw a SecurityError exception.
# If the disallow modification flag is set, throw a NotAllowedError DOMException.
if css_css_style_sheet_disallow_modification(this):
try idl_throw(.idl_dom_exception(idl_not_allowed_error_create(realm, ak.utf16_string_from_str("Can't call insert_rule() on non-modifiable stylesheets."))))
# 3. Let parsed rule be the return value of invoking parse a rule with rule.
# 4. If parsed rule is a syntax error, return parsed rule.
let maybe_parsed_rule = parse_css_rule(css_css_style_sheet_make_parsing_params(this), rule)
if maybe_parsed_rule == none:
try idl_throw(.idl_dom_exception(idl_syntax_error_create(realm, ak.utf16_string_from_str("Unable to parse CSS rule."))))
let parsed_rule = maybe_parsed_rule else trap("unreachable")
# 5. If parsed rule is an @import rule, and the constructed flag is set, throw a SyntaxError DOMException.
if css_css_style_sheet_constructed(this) and css_rule_type(parsed_rule) == CssRuleType.import_:
try idl_throw(.idl_dom_exception(idl_syntax_error_create(realm, ak.utf16_string_from_str("Can't insert @import rules into a constructed stylesheet."))))
# 6. Return the result of invoking insert a CSS rule rule in the CSS rules at index.
let rules = this.m_rules else trap("null m_rules")
let result = try css_rule_list_insert_a_css_rule(rules, .css_rule(parsed_rule), index, CssRuleListNested.no, css_css_style_sheet_declared_namespaces(this))
# (!result.is_exception())
# NOTE: The spec doesn't say where to set the parent style sheet, so we'll do it here.
css_rule_set_parent_style_sheet(parsed_rule, this)
let owner_node = css_style_sheet_owner_node(this.css_style_sheet())
var owner_is_style_element = false
if let node = owner_node:
owner_is_style_element = dom_node_is_html_style_element(node.dom_node())
if not css_css_style_sheet_constructed(this) and owner_is_style_element and css_rule_type(parsed_rule) == CssRuleType.keyframes:
css_invalidate_owners_for_inserted_keyframes_rule(this, (CssKeyframesRule*)parsed_rule)
elif not css_css_style_sheet_constructed(this) and owner_is_style_element and css_rule_type(parsed_rule) == CssRuleType.style:
css_invalidate_owners_for_inserted_style_rule(this, as_css_style_rule(parsed_rule), DomStyleInvalidationReason.style_sheet_insert_rule)
else:
css_css_style_sheet_invalidate_owners(this, DomStyleInvalidationReason.style_sheet_insert_rule)
return result
## Ported from Libraries/LibWeb/CSS/CSSStyleSheet.cpp:186 Web::CSS::CSSStyleSheet::delete_rule.
# https://www.w3.org/TR/cssom/#dom-cssstylesheet-deleterule
pub func css_css_style_sheet_delete_rule(this: CssCssStyleSheet*, index: u32) -> !:
# FIXME: 1. If the origin-clean flag is unset, throw a SecurityError exception.
# 2. If the disallow modification flag is set, throw a NotAllowedError DOMException.
if css_css_style_sheet_disallow_modification(this):
try idl_throw(.idl_dom_exception(idl_not_allowed_error_create(bind_platform_object_realm(this.bind_platform_object()), ak.utf16_string_from_str("Can't call delete_rule() on non-modifiable stylesheets."))))
# 3. Remove a CSS rule in the CSS rules at index.
let previous_sheet_effects = css_determine_shadow_root_stylesheet_effects_css_css_style_sheet(this)
try css_rule_list_remove_a_css_rule(this.m_rules else trap("null m_rules"), index)
css_css_style_sheet_invalidate_owners(this, DomStyleInvalidationReason.style_sheet_delete_rule, &previous_sheet_effects)
## The captures of replace()'s "in parallel" lambda.
struct CssCssStyleSheetReplaceInParallel:
var realm: Realm*
var this: CssCssStyleSheet*
var text: ak.String
var promise: JsPromiseCapability*
## replace()'s "in parallel" steps.
func css_css_style_sheet_replace_in_parallel(context: void*?):
let captures = (CssCssStyleSheetReplaceInParallel*)(context else trap("no captures"))
let realm = captures.realm
let this = captures.this
var execution_context: HtmlTemporaryExecutionContext = ---
html_temporary_execution_context_construct_realm(&execution_context, realm, HtmlTemporaryExecutionContextCallbacksEnabled.yes)
defer html_temporary_execution_context_destruct(&execution_context)
let previous_sheet_effects = css_determine_shadow_root_stylesheet_effects_css_css_style_sheet(this)
# 1. Let rules be the result of running parse a stylesheet’s contents from text.
var parser = css_parser_create(css_css_style_sheet_make_parsing_params(this), ak.string_bytes_as_string_view(&captures.text))
let rules = css_parser_parse_as_stylesheet_contents(&parser)
# 2. If rules contains one or more @import rules, remove those rules from rules.
var rules_without_import: ak.Vector[CssRule*]
for rule in ak.vector_span_const(&rules):
if css_rule_type(rule) != CssRuleType.import_:
ak.vector_append_t(&rules_without_import, rule)
# NOTE: The spec doesn't say where to set the parent style sheet, so we'll do it here.
for rule in ak.vector_span(&rules_without_import):
css_rule_set_parent_style_sheet(rule, this)
# 3. Set sheet’s CSS rules to rules.
css_rule_list_set_rules(this.m_rules else trap("null m_rules"), rules_without_import)
css_css_style_sheet_invalidate_owners(this, DomStyleInvalidationReason.style_sheet_replace, &previous_sheet_effects)
# 4. Unset sheet’s disallow modification flag.
css_css_style_sheet_set_disallow_modification(this, false)
# 5. Resolve promise with sheet.
idl_resolve_promise(realm, captures.promise, bind_platform_object_wrapper(this.bind_platform_object()))
## Ported from Libraries/LibWeb/CSS/CSSStyleSheet.cpp:204 Web::CSS::CSSStyleSheet::replace.
# https://drafts.csswg.org/cssom/#dom-cssstylesheet-replace
pub func css_css_style_sheet_replace(this: CssCssStyleSheet*, text: ak.String) -> JsPromiseCapability*:
let realm = bind_platform_object_realm(this.bind_platform_object())
# 1. Let promise be a promise
let promise = idl_create_promise(realm)
# 2. If the constructed flag is not set, or the disallow modification flag is set, reject promise with a NotAllowedError DOMException and return promise.
if not css_css_style_sheet_constructed(this):
let error_ = idl_not_allowed_error_create(realm, ak.utf16_string_from_str("Can't call replace() on non-constructed stylesheets"))
idl_reject_promise(realm, promise, bind_platform_object_wrapper(error_.bind_platform_object()))
return promise
if css_css_style_sheet_disallow_modification(this):
let error_ = idl_not_allowed_error_create(realm, ak.utf16_string_from_str("Can't call replace() on non-modifiable stylesheets"))
idl_reject_promise(realm, promise, bind_platform_object_wrapper(error_.bind_platform_object()))
return promise
# 3. Set the disallow modification flag.
css_css_style_sheet_set_disallow_modification(this, true)
# 4. In parallel, do these steps:
let captures = new CssCssStyleSheetReplaceInParallel(realm = realm, this = this, text = text, promise = promise) else trap("out of memory")
platform_event_loop_plugin_deferred_invoke(platform_event_loop_plugin_the(), gc.create_function0(realm_heap(realm), ak.Function0[unit](call = css_css_style_sheet_replace_in_parallel, context = captures)))
return promise
## Ported from Libraries/LibWeb/CSS/CSSStyleSheet.cpp:259 Web::CSS::CSSStyleSheet::replace_sync.
# https://drafts.csswg.org/cssom/#dom-cssstylesheet-replacesync
pub func css_css_style_sheet_replace_sync(this: CssCssStyleSheet*, text: ak.StringView) -> !:
let realm = bind_platform_object_realm(this.bind_platform_object())
# 1. If the constructed flag is not set, or the disallow modification flag is set, throw a NotAllowedError DOMException.
if not css_css_style_sheet_constructed(this):
try idl_throw(.idl_dom_exception(idl_not_allowed_error_create(realm, ak.utf16_string_from_str("Can't call replaceSync() on non-constructed stylesheets"))))
if css_css_style_sheet_disallow_modification(this):
try idl_throw(.idl_dom_exception(idl_not_allowed_error_create(realm, ak.utf16_string_from_str("Can't call replaceSync() on non-modifiable stylesheets"))))
# 2. Let rules be the result of running parse a stylesheet’s contents from text.
let previous_sheet_effects = css_determine_shadow_root_stylesheet_effects_css_css_style_sheet(this)
var parser = css_parser_create(css_css_style_sheet_make_parsing_params(this), text)
let rules = css_parser_parse_as_stylesheet_contents(&parser)
# 3. If rules contains one or more @import rules, remove those rules from rules.
var rules_without_import: ak.Vector[CssRule*]
for rule in ak.vector_span_const(&rules):
if css_rule_type(rule) != CssRuleType.import_:
ak.vector_append_t(&rules_without_import, rule)
# NOTE: The spec doesn't say where to set the parent style sheet, so we'll do it here.
for rule in ak.vector_span(&rules_without_import):
css_rule_set_parent_style_sheet(rule, this)
# 4. Set sheet’s CSS rules to rules.
css_rule_list_set_rules(this.m_rules else trap("null m_rules"), rules_without_import)
css_css_style_sheet_invalidate_owners(this, DomStyleInvalidationReason.style_sheet_replace, &previous_sheet_effects)
## Ported from Libraries/LibWeb/CSS/CSSStyleSheet.cpp:291 Web::CSS::CSSStyleSheet::add_rule.
# https://drafts.csswg.org/cssom/#dom-cssstylesheet-addrule
pub func css_css_style_sheet_add_rule(this: CssCssStyleSheet*, selector: ak.String?, style: ak.String?, index: u32?) -> i32!:
# 1. Let rule be an empty string.
var rule = ak.string_builder_new()
# 2. Append selector to rule.
if let selector_text = selector:
ak.string_builder_append_string_view(&rule, ak.string_bytes_as_string_view(&selector_text))
# 3. Append " { " to rule.
ak.string_builder_append_u8(&rule, '{')
# 4. If block is not empty, append block, followed by a space, to rule.
if let block = style:
if not ak.string_is_empty(&block):
dump_appendff(&rule, "{} ", [css_arg_string(&block)])
# 5. Append "}" to rule.
ak.string_builder_append_u8(&rule, '}')
# 6. Let index be optionalIndex if provided, or the number of CSS rules in the stylesheet otherwise.
# 7. Call insertRule(), with rule and index as arguments.
let insert_index = index else (u32)css_rule_list_length(css_css_style_sheet_rules(this))
_ = try css_css_style_sheet_insert_rule(this, ak.string_builder_string_view(&rule), insert_index)
# 8. Return -1.
return -1
## Ported from Libraries/LibWeb/CSS/CSSStyleSheet.cpp:319 Web::CSS::CSSStyleSheet::remove_rule.
# https://www.w3.org/TR/cssom/#dom-cssstylesheet-removerule
pub func css_css_style_sheet_remove_rule(this: CssCssStyleSheet*, index: u32?) -> !:
# The removeRule(index) method must run the same steps as deleteRule().
try css_css_style_sheet_delete_rule(this, index else 0)