Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / html / tests_html_structure_2.lucb

#==============================================================================================
#
#   tests_html_structure_2 - region r26's elements and image data, pinned to the C++ code
#
#   DESCRIPTION:
#       Focused tests of what tests_html_structure's oracle cases do not reach: the classes the
#       ElementFactory makes and their mixin tables, a <style> element whose sheet applies in
#       the cascade (the key scenario), the list of available images and AnimatedDecodedImageData
#       under a test ImageCodecPlugin (frames, requests, collection), SharedResourceRequest's
#       callbacks and decode, and the small IDL surfaces of template, slot, dialog, summary,
#       link, img and title. Expected values follow the C++ (and the reference build where the
#       oracle prints them).
#
#==============================================================================================

# mark: Helpers =================================================================================

## A Text node holding `text`.
func test_structure_text(document: DomDocument*, text: str) -> DomNode*:
    return dom_document_create_text_node(document, ak.utf16_string_from_str(text)).dom_node()

## Whether a String holds `text`.
func test_structure_is(string: ak.String, text: str) -> bool:
    return ak.string_eq_string_view(&string, ak.sv(text))

# mark: The element classes =====================================================================

test "the ElementFactory makes r26's element classes, whose constructors move the mixin tables":
    let (vm, realm, document) = test_elements_setup()
    defer web_test_destroy_vm(vm)
    let allocator: memory.Allocator = vm_heap(vm)
    with allocator:
        let cases: TestElementsClassCase[34] = [
            TestElementsClassCase(name = "base", info = &html_base_element_class),
            TestElementsClassCase(name = "dl", info = &html_htmld_list_element_class),
            TestElementsClassCase(name = "details", info = &html_details_element_class),
            TestElementsClassCase(name = "dialog", info = &html_dialog_element_class),
            TestElementsClassCase(name = "dir", info = &html_directory_element_class),
            TestElementsClassCase(name = "img", info = &html_image_element_class),
            TestElementsClassCase(name = "li", info = &html_htmlli_element_class),
            TestElementsClassCase(name = "link", info = &html_link_element_class),
            TestElementsClassCase(name = "menu", info = &html_menu_element_class),
            TestElementsClassCase(name = "meta", info = &html_meta_element_class),
            TestElementsClassCase(name = "ol", info = &html_htmlo_list_element_class),
            TestElementsClassCase(name = "picture", info = &html_picture_element_class),
            TestElementsClassCase(name = "slot", info = &html_slot_element_class),
            TestElementsClassCase(name = "source", info = &html_source_element_class),
            TestElementsClassCase(name = "style", info = &html_style_element_class),
            TestElementsClassCase(name = "summary", info = &html_summary_element_class),
            TestElementsClassCase(name = "caption", info = &html_table_caption_element_class),
            TestElementsClassCase(name = "td", info = &html_table_cell_element_class),
            TestElementsClassCase(name = "th", info = &html_table_cell_element_class),
            TestElementsClassCase(name = "col", info = &html_table_col_element_class),
            TestElementsClassCase(name = "colgroup", info = &html_table_col_element_class),
            TestElementsClassCase(name = "table", info = &html_table_element_class),
            TestElementsClassCase(name = "tr", info = &html_table_row_element_class),
            TestElementsClassCase(name = "tbody", info = &html_table_section_element_class),
            TestElementsClassCase(name = "thead", info = &html_table_section_element_class),
            TestElementsClassCase(name = "tfoot", info = &html_table_section_element_class),
            TestElementsClassCase(name = "template", info = &html_template_element_class),
            TestElementsClassCase(name = "title", info = &html_title_element_class),
            TestElementsClassCase(name = "ul", info = &html_htmlu_list_element_class),
            # Names the factory gives other classes stay theirs (r27's and HTMLElement).
            TestElementsClassCase(name = "dt", info = &html_element_class),
            TestElementsClassCase(name = "dd", info = &html_element_class),
            TestElementsClassCase(name = "figure", info = &html_element_class),
            TestElementsClassCase(name = "div", info = &html_div_element_class),
            TestElementsClassCase(name = "span", info = &html_span_element_class),
        ]
        for test_case in &cases:
            let element = test_elements_create(document, test_case.name)
            assert(test_elements_class(element) == test_case.info, test_case.name)
            let html = (HtmlElement*)element
            assert(element.aria_mixin.vtable.class_info == test_case.info, test_case.name)
            assert(element.slottable_mixin.vtable.class_info == test_case.info, test_case.name)
            assert(element.animatable.vtable.class_info == test_case.info, test_case.name)
            assert(html.global_event_handlers.vtable.class_info == test_case.info, test_case.name)
            assert(html.form_associated_element.vtable.class_info == test_case.info, test_case.name)

        # The further mixin bases: StyleElementBase of <style>, Slot of <slot>, ImageProvider and
        # ViewportClient of <img>.
        let style = as_html_style_element(test_elements_create(document, "style"))
        assert(style.style_element_base.vtable == &html_style_element_style_element_base_vtable)
        assert(style.style_element_base.class_id == style.cell().class_id)
        assert(dom_style_element_base_as_element(&style.style_element_base) == style.dom_element())
        let slot = as_html_slot_element(test_elements_create(document, "slot"))
        assert(slot.slot.vtable == &html_slot_element_slot_vtable)
        assert(slot.slot.class_id == slot.cell().class_id)
        let image = as_html_image_element(test_elements_create(document, "img"))
        assert(image.image_provider.vtable == &html_image_element_image_provider_vtable)
        assert(image.image_provider.class_id == image.cell().class_id)
        assert(image.viewport_client.vtable == &html_image_element_viewport_client_vtable)
        assert(image.viewport_client.class_id == image.cell().class_id)
    _ = realm

# mark: <style> in the cascade ==================================================================

## What update_a_style_block does past its CSP check (step 6) for `style`: its sheet, created in
## the document's style sheet list from its child text content and media attribute.
func test_structure_create_style_block(style: HtmlStyleElement*):
    let element = style.dom_element()
    let style_sheet_list = dom_element_document_or_shadow_root_style_sheets(element)
    style.style_element_base.m_style_sheet_list = style_sheet_list
    let text_content = dom_node_text_content(element.dom_node()) else ak.utf16_string_new()
    let media = dom_element_attribute(element, html_attribute_names_media) else ak.string_new()
    let sheet = css_style_sheet_list_create_a_css_style_sheet(style_sheet_list, ak.utf16_string_base_to_utf8_but_should_be_ported_to_utf16(&text_content.utf16_string_base), ak.string_from_str("text/css"), element, media, ak.string_new(), CssStyleSheetListAlternate.no, CssStyleSheetListOriginClean.yes, none, none, none)
    style.style_element_base.m_associated_css_style_sheet = sheet

test "scenario: a <style> element's rules show up in the cascade (its insertion stops at the CSP check)":
    let world = test_style_computer_world()
    defer web_test_destroy_vm(world.vm)
    let allocator: memory.Allocator = vm_heap(world.vm)
    with allocator:
        test_style_computer_install_user_agent_sheets(world.realm)
        defer test_style_computer_release_user_agent_sheets()
        let document = world.document
        let style = as_html_style_element(test_elements_create(document, "style"))

        # Detached: changing its children updates the style block, which stops at "not connected".
        test_elements_append(style.dom_node(), test_structure_text(document, "#root { color: rgb(1, 2, 3) } #root span { margin-left: 7px }"))
        assert(dom_style_element_base_sheet(&style.style_element_base) == none)
        assert(not html_style_element_disabled(style))
        html_style_element_set_disabled(style, true)
        assert(not html_style_element_disabled(style))

        # Connected, update_a_style_block reaches "Should element's inline behavior be blocked by
        # Content Security Policy?" (ported by region r28), which reads the CSP list of the
        # document's global object: a Window's (the global of this test realm is not one; region
        # r28's tests_window_document runs a connected <style> in a Window's document).

        # So the element goes into <head> as a tree operation, and the block's sheet is made as
        # step 6 makes it.
        let html = dom_document_document_element(document) else trap("the document has a root")
        let head = tree_node_first_child(html.dom_node()) else trap("the document has a head")
        tree_node_append_child(head, style.dom_node())
        test_structure_create_style_block(style)
        let sheet = dom_style_element_base_sheet(&style.style_element_base) else trap("the style block has a sheet")
        assert(css_style_sheet_owner_node(sheet.css_style_sheet()) == style.dom_element())
        assert(css_style_sheet_list_length(dom_document_style_sheets(document)) == 1)

        # The cascade over the document: the sheet's rules apply.
        let root = world.root.dom_element()
        let span = test_elements_create(document, "span")
        tree_node_append_child(root.dom_node(), span.dom_node())
        test_style_computer_build_rule_cache(&document.m_style_scope)
        test_style_computer_cascade_subtree(world.style_computer, html)
        assert(test_structure_is(test_style_computer_value(root, ak.sv("color")), "rgb(1, 2, 3)"))
        assert(test_structure_is(test_style_computer_value(span, ak.sv("color")), "rgb(1, 2, 3)"))
        assert(test_structure_is(test_style_computer_value(span, ak.sv("margin-left")), "7px"))
        assert(test_structure_is(test_style_computer_value(html, ak.sv("color")), "canvastext"))

        # disabled reflects the sheet's disabled flag; the media attribute sets the sheet's media.
        assert(not html_style_element_disabled(style))
        html_style_element_set_disabled(style, true)
        assert(html_style_element_disabled(style))
        assert(css_style_sheet_disabled(sheet.css_style_sheet()))
        html_style_element_set_disabled(style, false)
        assert(not html_style_element_disabled(style))
        test_elements_set(style.dom_element(), html_attribute_names_media, "print")
        assert(test_structure_is(css_media_list_media_text(css_style_sheet_media(sheet.css_style_sheet())), "print"))

# mark: A test ImageCodecPlugin =================================================================

## A test ImageCodecPlugin: it records animation frame requests and stopped sessions, and decodes
## any bytes into a streamed animation of four 2x1 frames (session 21).
struct TestStructureCodec:
    var plugin: PlatformImageCodecPlugin
    var requests: i32
    var last_request_start: u32
    var last_request_count: u32
    var stopped: i32
    var last_stopped_session: i64

## The test plugin, in the C heap (installed while a test runs, through the heap's teardown;
## AnimatedDecodedImageData installs its frame-delivery callbacks in the first one only).
var test_structure_codec_storage: TestStructureCodec*?

## The test plugin.
func test_structure_codec() -> TestStructureCodec*:
    return test_structure_codec_storage else trap("the test plugin is installed")

## The test plugin's decode_image: resolves at once with a streamed animation's first two frames.
func test_structure_codec_decode_image(this: PlatformImageCodecPlugin*, bytes: const u8[], on_resolved: ak.Function1[PlatformDecodedImage*, unit], on_rejected: ak.Function1[ak.AkError*, unit]) -> CorePromise[PlatformDecodedImage, ak.AkError]*:
    var image = PlatformDecodedImage(color_space = test_structure_color_space())
    image.is_animated = true
    image.frame_count = 4
    image.session_id = 21
    for i in 0..<2:
        let bitmap = gfx.bitmap_create_int_size(gfx.BitmapFormat.bgra8888, gfx.IntSize(m_width = 2, m_height = 1)) else trap("a bitmap")
        ak.vector_append_t(&image.frames, PlatformFrame(bitmap = bitmap, duration = 40))
    for i: u32 in 0..<4:
        ak.vector_append_t(&image.all_durations, 40 + 10 * i)
    ak.function1_call(&on_resolved, &image)
    return new CorePromise[PlatformDecodedImage, ak.AkError]() else trap("out of memory")

## The test plugin's request_animation_frames.
func test_structure_codec_request_animation_frames(this: PlatformImageCodecPlugin*, session_id: i64, start_frame_index: u32, count: u32):
    test_structure_codec().requests += 1
    test_structure_codec().last_request_start = start_frame_index
    test_structure_codec().last_request_count = count

## The test plugin's stop_animation_decode.
func test_structure_codec_stop_animation_decode(this: PlatformImageCodecPlugin*, session_id: i64):
    test_structure_codec().stopped += 1
    test_structure_codec().last_stopped_session = session_id

## The test plugin's vtable.
let test_structure_codec_vtable: PlatformImageCodecPluginVTable = PlatformImageCodecPluginVTable(class_info = &platform_image_codec_plugin_class, decode_image = test_structure_codec_decode_image, request_animation_frames = test_structure_codec_request_animation_frames, stop_animation_decode = test_structure_codec_stop_animation_decode)

## Installs the test plugin with its counters reset (its frame-delivery callbacks, installed once by
## AnimatedDecodedImageData, stay).
func test_structure_codec_install():
    if test_structure_codec_storage == none:
        with memory.heap:
            test_structure_codec_storage = new TestStructureCodec(plugin = PlatformImageCodecPlugin(vtable = &test_structure_codec_vtable)) else trap("out of memory")
    test_structure_codec().requests = 0
    test_structure_codec().stopped = 0
    test_structure_codec().last_stopped_session = 0
    platform_s_the = none
    platform_image_codec_plugin_install(&test_structure_codec().plugin)

## Removes the test plugin.
func test_structure_codec_remove():
    platform_s_the = none

## `count` 2x1 bitmaps.
func test_structure_bitmaps(count: usize) -> ak.Vector[gfx.Bitmap*]:
    var bitmaps: ak.Vector[gfx.Bitmap*]
    for i in 0..<count:
        ak.vector_append_t(&bitmaps, gfx.bitmap_create_int_size(gfx.BitmapFormat.bgra8888, gfx.IntSize(m_width = 2, m_height = 1)) else trap("a bitmap"))
    return bitmaps

## The frame durations 10, 20, … for `count` frames.
func test_structure_durations(count: u32) -> ak.Vector[u32]:
    var durations: ak.Vector[u32]
    for i: u32 in 0..<count:
        ak.vector_append_t(&durations, (i + 1) * 10)
    return durations

## A default ColorSpace.
func test_structure_color_space() -> gfx.ColorSpace:
    var color_space: gfx.ColorSpace = ---
    gfx.color_space_construct(&color_space)
    return color_space

## Whether the session registry maps `session_id` to `data`.
func test_structure_registered(session_id: i64, data: HtmlAnimatedDecodedImageData*?) -> bool:
    let entry = ak.hash_map_get_k(html_animated_decoded_image_data_session_registry(), session_id) else return data == none
    return *entry == data

# mark: AnimatedDecodedImageData ================================================================

test "AnimatedDecodedImageData: its answers, the buffer pool, frame requests and delivery":
    test_structure_codec_install()
    defer test_structure_codec_remove()
    let (vm, realm, document) = test_elements_setup()
    defer web_test_destroy_vm(vm)
    let allocator: memory.Allocator = vm_heap(vm)
    with allocator:
        # Ten frames of 4x2 pixels, looping twice, with the first two decoded.
        let data = html_animated_decoded_image_data_create(realm, 7, 10, 2, gfx.IntSize(m_width = 4, m_height = 2), test_structure_color_space(), test_structure_durations(10), test_structure_bitmaps(2))
        let base = data.html_decoded_image_data()
        assert(test_structure_registered(7, data))
        assert(html_animated_decoded_image_data_session_id(data) == 7)
        assert(html_decoded_image_data_frame_count(base) == 10 and html_decoded_image_data_loop_count(base) == 2)
        assert(html_decoded_image_data_is_animated(base))
        assert(html_decoded_image_data_frame_duration(base, 1) == 20 and html_decoded_image_data_frame_duration(base, 9) == 100)
        assert(html_decoded_image_data_frame_duration(base, 10) == 0)
        assert((html_decoded_image_data_intrinsic_width(base) else trap("a width")) == gfx.CssPixels.from_int(4))
        assert((html_decoded_image_data_intrinsic_height(base) else trap("a height")) == gfx.CssPixels.from_int(2))
        let ratio = html_decoded_image_data_intrinsic_aspect_ratio(base) else trap("a ratio")
        assert(ratio.m_numerator == gfx.CssPixels.from_int(4) and ratio.m_denominator == gfx.CssPixels.from_int(2))
        let rect = html_decoded_image_data_frame_rect(base, 3) else trap("a frame rect")
        assert(rect.m_size.m_width == 4 and rect.m_size.m_height == 2 and rect.m_location.m_x == 0)

        # The initial frames are in the pool; the first is the last displayed.
        let frame0 = html_decoded_image_data_bitmap(base, 0, gfx.IntSize()) else trap("frame 0")
        let frame1 = html_decoded_image_data_bitmap(base, 1, gfx.IntSize()) else trap("frame 1")
        assert(frame0 != frame1)
        assert(data.m_highest_requested_frame == 2)
        # A frame not in the pool answers the last displayed one, as does one past the end.
        assert(html_decoded_image_data_bitmap(base, 5, gfx.IntSize()) == frame1)
        assert(html_decoded_image_data_bitmap(base, 10, gfx.IntSize()) == frame1)

        # Advancing to frame 1 finds nothing ahead and requests four frames from 2.
        assert(html_decoded_image_data_notify_frame_advanced(base, 1) == 1)
        assert(test_structure_codec().requests == 1 and test_structure_codec().last_request_start == 2 and test_structure_codec().last_request_count == 4)
        assert(data.m_request_in_flight and data.m_highest_requested_frame == 6)
        # Another caller of the same tick does not advance it; nor does a request go out while
        # one is in flight.
        assert(html_decoded_image_data_notify_frame_advanced(base, 1) == 1)
        assert(html_decoded_image_data_notify_frame_advanced(base, 2) == 2)
        assert(test_structure_codec().requests == 1)

        # The decoder delivers frames 2..5 through the plugin's callback.
        var frames = test_structure_bitmaps(4)
        ak.function2_call(&test_structure_codec().plugin.on_animation_frames_decoded, 7, frames)
        assert(not data.m_request_in_flight)
        for i: usize in 2..<6:
            assert(html_animated_decoded_image_data_find_slot(data, (u32)i) != none)
        let frame3 = html_decoded_image_data_bitmap(base, 3, gfx.IntSize()) else trap("frame 3")
        assert(frame3 != frame1 and html_decoded_image_data_bitmap(base, 7, gfx.IntSize()) == frame3)

        # Frame 3: frames 4 and 5 are ahead (fewer than four): request from 6.
        assert(html_decoded_image_data_notify_frame_advanced(base, 3) == 3)
        assert(test_structure_codec().requests == 2 and test_structure_codec().last_request_start == 6)
        # A failed decode clears the request in flight.
        ak.function1_call(&test_structure_codec().plugin.on_animation_decode_failed, 7)
        assert(not data.m_request_in_flight)
        # Frames for another session go nowhere.
        ak.function2_call(&test_structure_codec().plugin.on_animation_frames_decoded, 8, test_structure_bitmaps(1))
        assert(html_animated_decoded_image_data_find_slot(data, 6) == none)
    _ = document

## Makes an AnimatedDecodedImageData for session `session_id` that only the document's list of
## available images holds, and answers a weak pointer to it.
noinline func test_structure_add_available_image(realm: Realm*, document: DomDocument*, key: HtmlListOfAvailableImagesKey, session_id: i64) -> gc.Weak[HtmlAnimatedDecodedImageData]:
    let data = html_animated_decoded_image_data_create(realm, session_id, 3, 0, gfx.IntSize(m_width = 1, m_height = 1), test_structure_color_space(), test_structure_durations(3), test_structure_bitmaps(1))
    html_list_of_available_images_add(dom_document_list_of_available_images(document), key, data.html_decoded_image_data(), true)
    return gc.make_weak[HtmlAnimatedDecodedImageData](data)

## An AnimatedDecodedImageData for session `session_id` that nothing holds, as a weak pointer.
noinline func test_structure_unheld_image(realm: Realm*, session_id: i64) -> gc.Weak[HtmlAnimatedDecodedImageData]:
    let data = html_animated_decoded_image_data_create(realm, session_id, 2, 0, gfx.IntSize(m_width = 1, m_height = 1), test_structure_color_space(), test_structure_durations(2), test_structure_bitmaps(1))
    return gc.make_weak[HtmlAnimatedDecodedImageData](data)

## Whether the list's entry for `key` holds the image data of `weak`, registered for its session
## (a separate frame: the pointers it reads do not stay on the test's stack).
noinline func test_structure_entry_holds(list: HtmlListOfAvailableImages*, key: HtmlListOfAvailableImagesKey, weak: const gc.Weak[HtmlAnimatedDecodedImageData]*) -> bool:
    let entry = html_list_of_available_images_get(list, key) else return false
    let data = gc.weak_ptr(weak) else return false
    return entry.ignore_higher_layer_caching and entry.image_data == data.html_decoded_image_data() and test_structure_registered(html_animated_decoded_image_data_session_id(data), data)

test "the list of available images: keys, entries, and the image data it keeps alive":
    test_structure_codec_install()
    defer test_structure_codec_remove()
    web_test_clobber_stack()
    run_structure_available_images()

noinline func run_structure_available_images():
    let (vm, realm, document) = test_elements_setup()
    defer web_test_destroy_vm(vm)
    vm_keep_alive(vm, document)
    let allocator: memory.Allocator = vm_heap(vm)
    with allocator:
        let list = dom_document_list_of_available_images(document)
        let url = web_url.parser_basic_parse(ak.sv("https://example.com/")) else trap("a URL")
        let key = HtmlListOfAvailableImagesKey(url = ak.string_from_str("https://example.com/a.png"), mode = HtmlCorsSettingAttribute.no_cors, origin = web_url.url_origin(&url), cached_hash = none)
        let other_mode = HtmlListOfAvailableImagesKey(url = key.url, mode = HtmlCorsSettingAttribute.anonymous, origin = key.origin, cached_hash = none)
        let no_origin = HtmlListOfAvailableImagesKey(url = key.url, mode = key.mode, origin = none, cached_hash = none)
        assert(html_list_of_available_images_key_eq(&key, key))
        assert(not html_list_of_available_images_key_eq(&key, other_mode) and not html_list_of_available_images_key_eq(&key, no_origin))
        assert(not html_list_of_available_images_key_eq(&no_origin, key))
        assert(html_list_of_available_images_get(list, key) == none)

        let weak = test_structure_add_available_image(realm, document, key, 31)
        assert(test_structure_entry_holds(list, key, &weak))
        assert(html_list_of_available_images_get(list, other_mode) == none)
        assert(html_list_of_available_images_get(list, no_origin) == none)

        # The list keeps the data alive through collections.
        test_html_forms_collect(vm)
        assert(web_test_alive(&weak))
        assert(test_structure_entry_holds(list, key, &weak))
        assert(test_structure_codec().stopped == 0)

        # Image data nothing holds is collected, whether it was removed from the list or never
        # in it: its finalizer leaves the registry and stops the decode.
        html_list_of_available_images_remove(list, key)
        assert(html_list_of_available_images_get(list, key) == none)
        let unheld = test_structure_unheld_image(realm, 32)
        test_html_forms_collect(vm)
        assert(not web_test_alive(&weak))
        assert(not web_test_alive(&unheld))
        assert(test_structure_registered(31, none))
        assert(test_structure_registered(32, none))
        assert(test_structure_codec().stopped == 2)

# mark: ImageRequest and SharedResourceRequest ==================================================

## Counts of the callbacks of a SharedResourceRequest.
var test_structure_finished: i32
var test_structure_failed: i32

## An on_finish callback.
func test_structure_on_finish(context: void*?):
    test_structure_finished += 1

## An on_fail callback.
func test_structure_on_fail(context: void*?):
    test_structure_failed += 1

## The on_finish and on_fail callbacks.
func test_structure_callbacks() -> (ak.Function0[unit], ak.Function0[unit]):
    return (ak.Function0[unit](call = test_structure_on_finish, context = none), ak.Function0[unit](call = test_structure_on_fail, context = none))

test "ImageRequest's initial state and SharedResourceRequest's callbacks and streamed decode":
    test_structure_codec_install()
    defer test_structure_codec_remove()
    let (vm, realm, document) = test_elements_setup()
    defer web_test_destroy_vm(vm)
    let allocator: memory.Allocator = vm_heap(vm)
    with allocator:
        test_structure_finished = 0
        test_structure_failed = 0
        let page = dom_document_page(document)
        let request = html_image_request_create(realm, page)
        assert(html_image_request_state(request) == HtmlImageRequestState.unavailable)
        assert(not html_image_request_is_available(request) and not html_image_request_is_fetching(request))
        assert(test_structure_is(html_image_request_current_url(request), ""))
        assert(html_image_request_current_pixel_density(request) == 1.0)
        assert(html_image_request_preferred_density_corrected_dimensions(request) == none)
        # An unparsable current URL gets no shared resource request.
        html_image_request_set_current_url(request, realm, ak.string_from_str("not a url"))
        assert(test_structure_is(html_image_request_current_url(request), "not a url"))
        assert(html_image_request_shared_resource_request(request) == none)
        html_image_request_set_state(request, HtmlImageRequestState.completely_available)
        assert(html_image_request_is_available(request))

        # A shared resource request (get_or_create needs the settings object's responsible
        # document, a Window's: made directly, as get_or_create makes it).
        let url = web_url.parser_basic_parse(ak.sv("https://example.com/b.gif")) else trap("a URL")
        let shared = realm_create_html_shared_resource_request(realm, page, url, document)
        assert(html_shared_resource_request_needs_fetching(shared) and not html_shared_resource_request_is_fetching(shared))
        let (on_finish, on_fail) = test_structure_callbacks()
        html_shared_resource_request_add_callbacks(shared, on_finish, on_fail)
        assert(test_structure_finished == 0 and ak.vector_size(&shared.m_callbacks) == 1)

        # A fetched GIF goes to the ImageCodecPlugin; its streamed animation becomes an
        # AnimatedDecodedImageData and the callbacks run once.
        var bytes: ak.ByteBuffer
        html_shared_resource_request_handle_successful_fetch(shared, url, ak.sv("image/gif"), bytes)
        assert(test_structure_finished == 1 and test_structure_failed == 0)
        assert(ak.vector_size(&shared.m_callbacks) == 0)
        assert(shared.m_state == HtmlSharedResourceRequestState.finished)
        let data = as_html_animated_decoded_image_data(html_shared_resource_request_image_data(shared) else trap("image data"))
        assert(html_animated_decoded_image_data_session_id(data) == 21)
        assert(html_decoded_image_data_frame_count(data.html_decoded_image_data()) == 4)
        assert(html_decoded_image_data_frame_duration(data.html_decoded_image_data(), 3) == 70)
        assert(data.m_size.m_width == 2 and data.m_size.m_height == 1)
        assert(html_animated_decoded_image_data_find_slot(data, 1) != none and html_animated_decoded_image_data_find_slot(data, 2) == none)

        # Callbacks added after the end run at once: on_finish once finished, on_fail once failed.
        html_shared_resource_request_add_callbacks(shared, on_finish, on_fail)
        assert(test_structure_finished == 2)
        html_shared_resource_request_handle_failed_fetch(shared)
        assert(shared.m_state == HtmlSharedResourceRequestState.failed and test_structure_failed == 0)
        html_shared_resource_request_add_callbacks(shared, on_finish, on_fail)
        assert(test_structure_failed == 1 and test_structure_finished == 2)

# mark: template, slot, dialog, summary =========================================================

test "template: its contents live in the inert template document and are cloned with it":
    let (vm, realm, document) = test_elements_setup()
    defer web_test_destroy_vm(vm)
    let allocator: memory.Allocator = vm_heap(vm)
    with allocator:
        let template_ = as_html_template_element(test_elements_create(document, "template"))
        let content = html_template_element_content_for_bindings(template_)
        assert(dom_document_fragment_host(content) == template_.dom_element())
        let contents_document = dom_node_document(content.dom_node())
        assert(contents_document != document)
        assert(dom_document_appropriate_template_contents_owner_document(document) == contents_document)
        test_elements_append(content.dom_node(), test_elements_create(contents_document, "p").dom_node())
        test_elements_append(content.dom_node(), test_structure_text(contents_document, "x"))

        # Cloning with the subtree clones the contents into the copy's contents.
        let copy = as_html_template_element(as_dom_element(dom_node_clone_node(template_.dom_node(), none, true) else trap("clone")))
        let copy_content = html_template_element_content(copy)
        assert(copy_content != content)
        assert(tree_node_child_count(copy_content.dom_node()) == 2)
        assert(dom_node_document(copy_content.dom_node()) == contents_document)
        # Without the subtree, the copy's contents are empty.
        let shallow = as_html_template_element(as_dom_element(dom_node_clone_node(template_.dom_node(), none, false) else trap("clone")))
        assert(tree_node_child_count(html_template_element_content(shallow).dom_node()) == 0)
    _ = realm

test "slot: manual assignment outside a shadow tree, and its assigned nodes":
    let (vm, realm, document) = test_elements_setup()
    defer web_test_destroy_vm(vm)
    let allocator: memory.Allocator = vm_heap(vm)
    with allocator:
        let slot = as_html_slot_element(test_elements_create(document, "slot"))
        let other = as_html_slot_element(test_elements_create(document, "slot"))
        let span = test_elements_create(document, "span")
        let text = dom_document_create_text_node(document, ak.utf16_string_from_str("t"))
        var nodes: ak.Vector[HtmlSlotElementSlottableHandle]
        ak.vector_append_t(&nodes, HtmlSlotElementSlottableHandle.dom_element(span))
        ak.vector_append_t(&nodes, HtmlSlotElementSlottableHandle.dom_text(text))
        html_slot_element_assign(slot, nodes)
        assert(html_slot_element_manually_assigned_nodes(slot).length == 2)
        assert(dom_slottable_mixin_manual_slot_assignment(&span.slottable_mixin) == slot.html_slot_element())

        # Not in a shadow tree: nothing is assigned, flattened or not.
        let assigned_nodes = html_slot_element_assigned_nodes(slot, HtmlAssignedNodesOptions(flatten = false))
        let flattened_elements = html_slot_element_assigned_elements(slot, HtmlAssignedNodesOptions(flatten = true))
        assert(ak.vector_size(&assigned_nodes) == 0 and ak.vector_size(&flattened_elements) == 0)

        # Assigning the span to another slot points the span at it. (Step 3.1 should remove the
        # span from the first slot's manually assigned nodes; C++ removes it from this slot's, so
        # the first slot still lists it.)
        var moved: ak.Vector[HtmlSlotElementSlottableHandle]
        ak.vector_append_t(&moved, HtmlSlotElementSlottableHandle.dom_element(span))
        html_slot_element_assign(other, moved)
        assert(html_slot_element_manually_assigned_nodes(slot).length == 2)
        assert(html_slot_element_manually_assigned_nodes(other).length == 1)
        assert(dom_slottable_mixin_manual_slot_assignment(&span.slottable_mixin) == other.html_slot_element())
    _ = realm

test "dialog: returnValue, modality and commands of a closed dialog; summary for its parent details":
    let (vm, realm, document) = test_elements_setup()
    defer web_test_destroy_vm(vm)
    let allocator: memory.Allocator = vm_heap(vm)
    with allocator:
        let dialog = as_html_dialog_element(test_elements_create(document, "dialog"))
        assert(test_structure_is(html_dialog_element_return_value(dialog), ""))
        html_dialog_element_set_return_value(dialog, ak.string_from_str("ok"))
        assert(test_structure_is(html_dialog_element_return_value(dialog), "ok"))
        assert(not html_dialog_element_is_modal(dialog))
        # Closing a dialog without an open attribute does nothing (the return value stays).
        html_dialog_element_close(dialog, ak.string_from_str("other"))
        html_dialog_element_request_close(dialog, ak.string_from_str("other"))
        assert(test_structure_is(html_dialog_element_return_value(dialog), "ok"))
        for command in ["close", "request-close", "show-modal"]:
            var string = ak.string_from_str(command)
            assert(html_element_is_valid_command(dialog.html_element(), &string), command)
        for command in ["show", "toggle-popover", "--custom", "Close"]:
            var string = ak.string_from_str(command)
            assert(not html_element_is_valid_command(dialog.html_element(), &string), command)

        # The first summary child of a details is its summary; others, and a summary elsewhere, are not.
        let details = test_elements_create(document, "details")
        let first = as_html_summary_element(test_elements_create(document, "summary"))
        let second = as_html_summary_element(test_elements_create(document, "summary"))
        let alone = as_html_summary_element(test_elements_create(document, "summary"))
        test_elements_append(details.dom_node(), test_elements_create(document, "p").dom_node())
        test_elements_append(details.dom_node(), first.dom_node())
        test_elements_append(details.dom_node(), second.dom_node())
        assert(html_summary_element_is_summary_for_its_parent_details(first))
        assert(not html_summary_element_is_summary_for_its_parent_details(second))
        assert(not html_summary_element_is_summary_for_its_parent_details(alone))
        let div = test_elements_create(document, "div")
        test_elements_append(div.dom_node(), alone.dom_node())
        assert(not html_summary_element_is_summary_for_its_parent_details(alone))
        assert(dom_event_target_is_focusable(first.dom_event_target()))
    _ = realm

# mark: link, img, title ========================================================================

test "link: rel keywords, relList, type and media of a detached link":
    let (vm, realm, document) = test_elements_setup()
    defer web_test_destroy_vm(vm)
    let allocator: memory.Allocator = vm_heap(vm)
    with allocator:
        let link = as_html_link_element(test_elements_create(document, "link"))
        assert(link.m_relationship == 0)
        test_elements_set(link.dom_element(), html_attribute_names_rel, "StyleSheet  alternate\ticon x")
        assert(link.m_relationship == html_link_element_relationship_stylesheet | html_link_element_relationship_alternate | html_link_element_relationship_icon)
        let rel_list = html_link_element_rel_list(link)
        assert(html_link_element_rel_list(link) == rel_list)
        assert(dom_token_list_length(rel_list) == 4)
        assert(dom_token_list_contains(rel_list, ak.string_from_str("StyleSheet")))
        test_elements_set(link.dom_element(), html_attribute_names_rel, "preload dns-prefetch preconnect")
        assert(link.m_relationship == html_link_element_relationship_preload | html_link_element_relationship_dns_prefetch | html_link_element_relationship_preconnect)
        assert(dom_token_list_length(rel_list) == 3)
        assert(test_structure_is(html_link_element_rel(link), "preload dns-prefetch preconnect"))

        # type is kept lowercased; media reflects its attribute.
        test_elements_set(link.dom_element(), html_attribute_names_type, "Text/CSS")
        assert(test_structure_is(link.m_mime_type else trap("a MIME type"), "text/css"))
        html_link_element_set_media(link, ak.string_from_str("screen"))
        assert(test_structure_is(html_link_element_media(link), "screen"))
        assert(html_link_element_sheet(link) == none and not html_link_element_has_loaded_icon(link))
    _ = realm

test "img: complete, currentSrc, crossorigin and auto sizes before any fetch":
    let (vm, realm, document) = test_elements_setup()
    defer web_test_destroy_vm(vm)
    let allocator: memory.Allocator = vm_heap(vm)
    with allocator:
        let image = as_html_image_element(test_elements_create(document, "img"))
        assert(html_image_element_complete(image))
        assert(test_structure_is(html_image_element_current_src(image), ""))
        assert(html_image_request_state(html_image_element_current_request(image)) == HtmlImageRequestState.unavailable)
        assert(not html_image_element_uses_srcset_or_picture(image))

        # The crossorigin attribute's state.
        assert(image.m_cors_setting == HtmlCorsSettingAttribute.no_cors)
        test_elements_set(image.dom_element(), html_attribute_names_crossorigin, "")
        assert(image.m_cors_setting == HtmlCorsSettingAttribute.anonymous)
        test_elements_set(image.dom_element(), html_attribute_names_crossorigin, "USE-credentials")
        assert(image.m_cors_setting == HtmlCorsSettingAttribute.use_credentials)
        dom_element_remove_attribute(image.dom_element(), html_attribute_names_crossorigin)
        assert(image.m_cors_setting == HtmlCorsSettingAttribute.no_cors)

        # An empty src is complete; a src waits (the document is not fully active) and is not.
        test_elements_set(image.dom_element(), html_attribute_names_src, "")
        assert(html_image_element_complete(image))
        test_elements_set(image.dom_element(), html_attribute_names_src, "a.png")
        assert(not html_image_element_complete(image))
        test_elements_set(image.dom_element(), html_attribute_names_srcset, "b.png 2x")
        assert(html_image_element_uses_srcset_or_picture(image))
        assert(test_structure_is(html_image_element_current_src(image), ""))

        # Auto sizes need loading=lazy and sizes "auto" or "auto,…".
        test_elements_set(image.dom_element(), html_attribute_names_sizes, "AUTO, 100px")
        assert(not html_image_element_allows_auto_sizes(image))
        test_elements_set(image.dom_element(), html_attribute_names_loading, "lazy")
        assert(html_image_element_allows_auto_sizes(image))
        test_elements_set(image.dom_element(), html_attribute_names_sizes, "100px, auto")
        assert(not html_image_element_allows_auto_sizes(image))
        assert(test_structure_is(html_image_element_alt(image), ""))
        test_elements_set(image.dom_element(), html_attribute_names_alt, "a cat")
        assert(test_structure_is(html_image_element_alt(image), "a cat"))
    _ = realm

test "title: text is the child text content; setting it replaces the children":
    let (vm, realm, document) = test_elements_setup()
    defer web_test_destroy_vm(vm)
    let allocator: memory.Allocator = vm_heap(vm)
    with allocator:
        let title = as_html_title_element(test_elements_create(document, "title"))
        test_elements_append(title.dom_node(), test_structure_text(document, "a "))
        let b = test_elements_create(document, "b")
        test_elements_append(b.dom_node(), test_structure_text(document, "hidden"))
        test_elements_append(title.dom_node(), b.dom_node())
        test_elements_append(title.dom_node(), test_structure_text(document, "c"))
        assert(test_elements_utf16_is(html_title_element_text(title), "a c"))
        html_title_element_set_text(title, ak.utf16_string_from_str("new"))
        assert(test_elements_utf16_is(html_title_element_text(title), "new"))
        assert(tree_node_child_count(title.dom_node()) == 1)
        html_title_element_set_text(title, ak.utf16_string_from_str(""))
        assert(tree_node_child_count(title.dom_node()) == 0)
    _ = realm

# mark: Collection ==============================================================================

## A tree of r26 elements under the document: a template with contents, a link with its relList,
## slots with a manual assignment, a dialog and an img. Answers a weak pointer to the template's contents.
noinline func test_structure_make_tree(document: DomDocument*) -> gc.Weak[DomDocumentFragment]:
    let root = test_elements_create(document, "div")
    tree_node_append_child(document.dom_node(), root.dom_node())
    let template_ = as_html_template_element(test_elements_create(document, "template"))
    let content = html_template_element_content(template_)
    test_elements_append(content.dom_node(), test_elements_create(dom_node_document(content.dom_node()), "p").dom_node())
    test_elements_append(root.dom_node(), template_.dom_node())
    let link = as_html_link_element(test_elements_create(document, "link"))
    test_elements_set(link.dom_element(), html_attribute_names_rel, "icon")
    _ = html_link_element_rel_list(link)
    test_elements_append(root.dom_node(), link.dom_node())
    let slot = as_html_slot_element(test_elements_create(document, "slot"))
    let span = test_elements_create(document, "span")
    var nodes: ak.Vector[HtmlSlotElementSlottableHandle]
    ak.vector_append_t(&nodes, HtmlSlotElementSlottableHandle.dom_element(span))
    html_slot_element_assign(slot, nodes)
    test_elements_append(root.dom_node(), slot.dom_node())
    test_elements_append(root.dom_node(), test_elements_create(document, "dialog").dom_node())
    # An img's visit_edges reaches ImageProvider::image_provider_visit_edges (region r43).
    test_elements_append(root.dom_node(), test_elements_create(document, "img").dom_node())
    return gc.make_weak[DomDocumentFragment](content)

test "GC with r26 elements alive: their edges keep template contents and manual assignments":
    web_test_clobber_stack()
    run_structure_collections()

noinline func run_structure_collections():
    let (vm, realm, document) = test_elements_setup()
    defer web_test_destroy_vm(vm)
    vm_keep_alive(vm, document)
    let allocator: memory.Allocator = vm_heap(vm)
    with allocator:
        let weak_content = test_structure_make_tree(document)
        test_html_forms_collect(vm)
        assert(web_test_alive(&weak_content))
        let root = document.dom_node().tree_node.m_first_child else trap("the tree")
        let template_ = as_html_template_element(as_dom_element(tree_node_first_child(root) else trap("the template")))
        assert(tree_node_child_count(html_template_element_content(template_).dom_node()) == 1)
        let slot = as_html_slot_element(as_dom_element(tree_node_first_child_of_type(root, &html_slot_element_class) else trap("the slot")))
        # The manually assigned span lives only through the slot's edges.
        let assigned = html_slot_element_manually_assigned_nodes(slot)
        assert(assigned.length == 1)
        let span = dom_slottable_node(assigned[0])
        assert(test_elements_class(as_dom_element(span)) == &html_span_element_class)
        assert(tree_node_first_child_of_type(root, &html_image_element_class) != none)
    _ = realm