Commit graph

1187 commits

Author SHA1 Message Date
Aliaksandr Kalenik
aa24da8a93 LibWeb: Only invalidate layout on SVG viewBox/preserveAspectRatio change
These attributes are consumed during layout in SVGFormattingContext to
compute the viewbox transform. They don't affect the layout tree
structure, so a layout-only invalidation is sufficient instead of a
full layout tree rebuild.
2026-02-09 19:49:10 +01:00
Aliaksandr Kalenik
ed0ce5c17f LibWeb: Unify three layout tree traversals into one in update_layout()
Merge the three consecutive for_each_in_inclusive_subtree traversals
into a single preorder walk. All three operations only depend on
ancestor state which is satisfied before descendants are visited in
preorder traversal.
2026-02-09 19:00:04 +01:00
Aliaksandr Kalenik
abecc746d7 LibWeb: Implement partial SVG relayout
Previously, any SVG geometry attribute change would mark the entire
document layout tree as dirty, triggering a full layout pass even though
only the SVG subtree was affected. This made SVG geometry animations
unnecessarily expensive.

Fix this by stopping `needs_layout_update` propagation at the SVGSVGBox
boundary and tracking dirty SVG roots separately on the Document. When
`update_layout()` finds that only SVG roots need relayout (and the
document layout root is clean), it runs SVGFormattingContext on each
dirty SVG root in a fresh LayoutState and commits the results directly,
bypassing the full document layout pass entirely.

This results in a substantial performance improvement on pages with
animated SVGs, such as https://www.cloudflare.com/,
https://www.duolingo.com/, and our GC graph explorer page.
2026-02-09 03:02:49 +01:00
Timothy Flynn
4a8ef68b90 LibWeb: Protect against null navigables in lineage chain more thoroughly
This extends the null navigable check added in commit
b118c99c27 to include all ancestor and
descendant list lookups. Fixes a crash in the following WPT test:

/cookies/schemeful-same-site/schemeful-navigation.tentative.html
2026-02-08 14:51:25 -05:00
Timothy Flynn
5cff8db44c LibWeb: Invoke Document::navigable() fewer times in a row
This is not necessarily a cheap accessor.
2026-02-08 14:51:25 -05:00
Aliaksandr Kalenik
2452680615 LibWeb: Remove Document.h include from DOMParser.h, DOMImplementation.h
...and WorkerEnvironmentSettingsObject.h

These headers only use Document via forward-declarable references and
smart pointers, so the full include is unnecessary.
2026-02-08 18:51:13 +01:00
Aliaksandr Kalenik
e76cf3e225 LibWeb: Remove Document.h include from Layout/Node.h
This reduces the recompilation cascade when Document.h is modified.
Add explicit includes to files that relied on the transitive dependency.
2026-02-08 18:51:13 +01:00
Aliaksandr Kalenik
c62996abd7 LibWeb: Avoid dynamic_cast in SlottableMixin::assigned_slot()
`SlottableMixin::assigned_slot()` was using `as<DOM::Node>(*this)` to
get a `Node` reference. Since `SlottableMixin` has no inheritance
relationship with `Node`, `as_if<>` can't use `static_cast` and falls
through to `dynamic_cast`, which is expensive. Replace this with a
virtual `slottable_as_node()` accessor overridden in `Element` and
`Text`.

This showed up as hot in profiles when loading the GC heap explorer
page.
2026-02-07 16:43:50 +01:00
Aliaksandr Kalenik
488123c75b LibWeb: Don't rebuild layout tree on SVG transform change
The SVG `transform` attribute is stored on the DOM element and read
directly during layout by
`SVGFormattingContext::layout_graphics_element()`. Since changing the
transform doesn't affect which DOM nodes produce layout boxes or how
they're structured, we only need to re-run layout on the existing tree
instead of rebuild it from scratch.
2026-02-07 15:47:17 +01:00
Jelle Raaijmakers
2a2f8ef90b LibWeb+UI: Support triple clicking and dragging paragraphs
When triple clicking on text, we should select the entire paragraph, or
entire line in <input>s and <textarea>s. If the mouse button is held
down and the user starts dragging, the selection expands with additional
paragraphs or lines.

This expands on the work of Kai Wildberger (PR #7681) but was adjusted
for the work that happened previously to support double click + drag
moves and includes triple click support for our Qt UI.

Co-authored-by: Kai Wildberger <kiawildberger@gmail.com>
2026-02-06 14:18:10 +00:00
Andreas Kling
5b26777904 LibWeb: Don't WEB_SET_PROTOTYPE_FOR_INTERFACE for ShadowRealm global
We weren't doing this before either, but through a slightly sneaky
mechanism: we had overridden Cell::initialize() in
ShadowRealmGlobalScope as a no-op.

Instead of that, do the same thing Window and Worker globals do and
make all of the globals that inherit UniversalGlobalScopeMixin opt
out of WEB_SET_PROTOTYPE_FOR_INTERFACE in EventTarget::initialize().
2026-02-06 13:50:54 +01:00
Andreas Kling
d45bda7b79 LibWeb: Mark Node::inserted() and Node::removed_from() as MUST_UPCALL
Node::inserted() sets needs_style_update, and Node::removed_from()
clears the layout node and paintable pointers. Forgetting to call
either base implementation from a derived class would be a bug.
2026-02-06 13:50:54 +01:00
Andreas Kling
8d2081d3ff LibWeb: Mark Element::attribute_changed() as MUST_UPCALL
The base implementation handles critical bookkeeping like element
ID/name registration and slot assignment. Forgetting to call it
from a derived class would be a correctness bug.
2026-02-06 13:50:54 +01:00
Jelle Raaijmakers
7714471aae LibWeb: Recompute style for ::selection pseudo element 2026-02-06 10:47:50 +00:00
Callum Law
665feb57ae LibWeb: Use computed values in Element::is_potentially_scrollable
`Layout::NodeWithStyle::computed_values()` actually holds used values
which may not be the same as computed values e.g. if they have been
modified by `Document::propagate_overflow_to_viewport()`
2026-02-05 16:45:34 +01:00
Callum Law
226b1ee46b LibWeb: Support percentage units for Animations::TimeValue
Non functional change for now since we don't yet have any progress-based
timelines which support percentage based time values
2026-02-05 16:45:34 +01:00
Timothy Flynn
0482b6bb57 LibWeb+LibWebView+WebContent: Implement versioning for document cookies
This patch introduces a cookie cache in the WebContent process to reduce
blocking IPC calls when JS accesses document.cookie. The UI process now
maintains a cookie version counter per-domain in shared memory. When JS
reads document.cookie, we check whether we have a valid cached cookie by
comparing the current shared version to the last used version. If they
match, the cached cookie is returned without IPC.

This optimization is based on Chromium's shared versioning, in which it
was observed that 87% of document.cookie accesses were redundant. See:
https://blog.chromium.org/2024/06/introducing-shared-memory-versioning-to.html

Note that this cache only supports document.cookie, not HTTP Cookie
headers. HTTP cookies are attached to requests with varying URLs and
paths. The cookies that match the document URL might not match the
request URL, which we wouldn't know from WebContent. So attaching the
cached document cookie would be incorrect.

On https://twinings.co.uk, we see approximately 600 document.cookie
requests while the page loads. This patch reduces the time spent in
the document.cookie getter from ~45ms to 2-3ms.
2026-02-05 07:28:07 -05:00
Sam Atkins
78fcc7ed72 LibWeb/DOM: Add FIXME for flat tree descendant check 2026-02-05 11:21:08 +01:00
Sam Atkins
2994a7532d LibWeb: Make shadow_including_first_ancestor_of_type() use the flat tree
Every user of this actually wants an ancestor in the flat tree - taking
things like `<slot>` into account. So rename it and adjust its behavior
to use that.
2026-02-05 11:21:08 +01:00
Sam Atkins
bd753eafb6 LibWeb/DOM: Walk flat tree in Element::check_visibility() 2026-02-05 11:21:08 +01:00
Sam Atkins
ce13ab733d LibWeb/DOM: Walk the flat tree to propagate layout tree updates
This fixes an issue where we wouldn't propagate the layout update from a
slotted node to its slot.
2026-02-05 11:21:08 +01:00
Sam Atkins
bccf388110 LibWeb/DOM: Implement "flat tree parent" getter for DOM Node
Various parts of the spec ask us to walk the flat tree. In most cases
that's the same as getting its parent or shadow host, but `<slot>` in
particular breaks this rule, as a slotted element's flat tree parent is
the slot.
2026-02-05 11:21:08 +01:00
Tim Ledbetter
c44b30f0f1 LibWeb: Exclude UA internal shadow root elements in elementFromPoint()
When `elementFromPoint()` or `elementsFromPoint()` returns an element
that is inside a UA internal shadow root, we now return the shadow host
for that element.
2026-02-02 20:17:03 +00:00
Andreas Kling
5f434a442a LibWeb: Use targeted style invalidation when adding a new stylesheet
Instead of doing a full document style invalidation when a stylesheet is
dynamically added, we now analyze the new sheet's selectors to determine
which elements could potentially be affected, and only invalidate those.

This works by building an InvalidationSet from the rightmost compound
selector (the "subject") of each rule in the new stylesheet, extracting
class, ID, tag name, attribute, and pseudo-class features. We then walk
the DOM tree and only mark elements matching those features as needing a
style update.

If any selector has a rightmost compound that is purely universal (no
identifying features), or uses a pseudo-class not supported by the
invalidation set matching logic, we fall back to full invalidation.
2026-02-02 21:08:30 +01:00
Tim Ledbetter
73fcbb0666 LibWeb: Add a flag for UA internal shadow roots 2026-02-02 12:28:05 +00:00
Adam Colvin
ef3991f1ed LibWeb: Implement Document.hasFocus() per specification
Previously, Document::has_focus() always returned true, which was
incorrect. This caused documents without a browsing context (such as
those created via document.implementation.createHTMLDocument()) to
incorrectly report that they had focus.

The implementation now follows the spec:
1. Return false if the document has no navigable
2. Return false if the top-level traversable doesn't have system focus
3. Walk the focus chain from the top-level document to verify this
   document is actually focused

This fixes a WPT test: "The hasFocus() method must return false if the
Document has no browsing context"
2026-01-31 15:13:54 +01:00
Tim Ledbetter
ea855d2baf LibWeb: Clear assigned slot for slottables that become unassigned 2026-01-31 11:44:20 +01:00
Tim Ledbetter
18b8ba1fd3 LibWeb: Avoid subtree iteration when assigning slottables
This change introduces SlotRegistry to track slot elements per shadow
root. This allows us to iterate slots directly when assigning
slottables for a tree instead of walking an entire subtree.
2026-01-31 11:44:20 +01:00
Tim Ledbetter
2017347a77 LibWeb: Store slot name as a FlyString
This speeds up slot name lookups.
2026-01-31 11:44:20 +01:00
Andreas Kling
d89f3fc5e6 LibGC+ClangPlugins: Forbid non-trivial destructors in Cell subclasses
Add a clang plugin check that flags GC::Cell subclasses (and their
base classes within the Cell hierarchy) that have destructors with
non-trivial bodies. Such logic should use Cell::finalize() instead.

Add GC_ALLOW_CELL_DESTRUCTOR annotation macro for opting out in
exceptional cases (currently only JS::Object).

This prevents us from accidentally adding code in destructors that
runs after something we're pointing to may have been destroyed.
(This could become a problem when the garbage collector sweeps
objects in an unfortunate order.)

This new check uncovered a handful of bugs which are then also fixed
in this commit. :^)
2026-01-30 20:57:42 +01:00
Jelle Raaijmakers
e05503dbcb LibWeb: Send InputEvent with right .inputType on insert and delete
Applies to `<input>` and `<textarea>`. Editing commands in
`contenteditable` already sent the right events and input types.

Fixes #7668
2026-01-29 15:08:06 +01:00
Aliaksandr Kalenik
1f6ee6c63a LibWeb: Add internals.dumpStackingContextTree() for testing
This new API allows tests to inspect the stacking context tree structure
which is useful for verifying that stacking context invalidation and
rebuilding work correctly.
2026-01-28 18:05:41 +01:00
Aliaksandr Kalenik
0fcd8c0bfa LibWeb: Fix pseudo-element scroll offset leaking to generating element
In Element::set_scroll_offset(), when setting a pseudo-element's
scroll offset, the code was also incorrectly setting the generating
element's own m_scroll_offset. Added an else branch so only the
pseudo-element's offset is set.

Also adds a ref test for scrollable pseudo-elements to prevent
regression. The test scrolls a ::before pseudo-element via wheel
event and verifies the content scrolls correctly.
2026-01-27 20:32:12 +01:00
Andreas Kling
6b9797f480 LibWeb: Scope pseudo-class invalidation to common ancestor
When a pseudo-class state changed, we always walked the entire
document (or shadow root) tree to find affected elements, even
though only the subtree rooted at the old/new common ancestor
can be affected.

Narrow the tree walk to start from old_new_common_ancestor
instead of the root. To ensure ancestor-dependent selectors are
still correctly evaluated, we seed the style computer's ancestor
filter by walking up from the common ancestor to the root before
the invalidation walk.

This reduces the work from O(total elements) to
O(subtree elements) + O(tree depth), which is a large improvement
on pages where pseudo-class changes (hover, focus, active, target)
occur deep in the DOM.

This was extremely hot (10%+) when hovering mailboxes on GMail.
2026-01-27 10:58:47 +01:00
Shannon Booth
354cca350a LibWeb/HTML: Invalidate :checked style on <input> type attribute change
The :checked (and :unchecked) psuedo classes depend on both the
checked state of input elements as well as what the type of that
input element is.
2026-01-27 09:45:40 +01:00
Andreas Kling
3b90eb1d49 LibWeb: Recompute child style when parent's display changes
When a parent element's display property changes (e.g., to flex or
grid), children may need to be blockified or un-blockified.
Previously, children only received a recompute_inherited_style() call
which doesn't run the blockification logic.

This patch adds a parent_display_changed flag to the recursive style
update that forces children to get a full style recompute when their
parent's display change triggers a layout tree rebuild.
2026-01-26 12:40:36 +01:00
Andreas Kling
5fc276872a LibWeb: Add style invalidation for :open pseudo-class
Add proper style invalidation when the `open` attribute changes on
HTMLDetailsElement and HTMLDialogElement. The :open pseudo-class can
affect sibling selectors (e.g., `dialog:open + sibling`), so we need
full subtree + sibling invalidation.
2026-01-26 12:40:36 +01:00
Andreas Kling
37bdcc3488 LibWeb: Support MIME type sniffing for streaming HTTP responses
Previously, when loading a document, we would try to sniff the MIME
type by reading from the response body's source. However, for streaming
HTTP responses, the body source is Empty (the data comes through the
stream instead), so we had no bytes to sniff.

This caused pages like hypr.land (which sends no Content-Type header)
to be misidentified as plain text instead of HTML, since the MIME
sniffing algorithm would receive zero bytes and fall back to the
default type.

The fix captures the first bytes of the response body during fetch,
storing them on the Body object. These bytes are the "resource header"
defined by the MIME Sniffing spec - up to 1445 bytes, which is enough
to identify any MIME type the spec can detect.

Since bytes may arrive asynchronously during streaming, we use a
callback mechanism: if bytes aren't ready yet when load_document()
needs them, it registers a callback that fires once enough bytes have
been captured (or the stream ends).

The flow is:
1. FetchedDataReceiver receives network bytes, buffers them
2. When Body is created, buffered bytes are flushed to Body's sniff
   buffer, and subsequent bytes are appended as they arrive
3. Before calling load_document(), Navigable waits for sniff bytes
4. load_document() passes the bytes to MimeSniff::Resource::sniff()
2026-01-24 15:21:26 +01:00
Aliaksandr Kalenik
3e54291813 LibWeb: Move VisualViewport transform to AccumulatedVisualContext tree
Move the visual viewport (pinch-to-zoom) transform from a reserved slot
in DisplayList to the AccumulatedVisualContext tree as a root transform
node. Fixed position elements now correctly inherit from this context.

This requires rebuilding the context tree and display list on each zoom
change, but this overhead will be eliminated by future partial context
tree rebuilds.
2026-01-23 18:56:24 +01:00
Colleirose
bf7fd80140 LibCrypto+AK: Merge LibCrypto/SecureRandom into AK/Random
AK/Random is already the same as SecureRandom. See PR for more details.

ProcessPrng is used on Windows for compatibility w/ sandboxing measures
See e.g. https://crbug.com/40277768
2026-01-23 15:53:27 +01:00
Aliaksandr Kalenik
44bfb32d47 LibWeb: Move AccumulatedVisualContext update in paint properties update
Integrate the AccumulatedVisualContext tree update into
update_paint_and_hit_testing_properties_if_needed() to consolidate
paint tree preparation into a single function.
2026-01-22 10:43:20 +01:00
Luke Wilde
babfd70ca7 LibGC: Enforce that a Cell type must declare the allocator to use
This ensures that we are explicitly declaring the allocator to use when
allocating a cell(-inheriting) type, instead of silently falling back
to size-based allocation.

Since this is done in allocate_cell, this will only be detected for
types that are actively being allocated. However, since that means
they're _not_ being allocated, that means it's safe to not declare
an allocator to use for those. For example, the base TypedArray<T>,
which is never directly allocated and only the defined specializations
are ever allocated.
2026-01-20 12:00:11 +01:00
Tim Ledbetter
0035690977 LibWeb: Return body from activeElement() when nothing is focused
This matches the behavior of other browsers.
2026-01-19 13:08:30 +01:00
Jelle Raaijmakers
f2f8f3ae57 LibWeb: Propagate <body>'s image-rendering to root element
Whenever we propagated a <body>'s background image to the root element,
we ignored any `image-rendering` property present.
2026-01-19 12:05:08 +01:00
Aliaksandr Kalenik
23a74ddc2a LibWeb: Use AccumulatedVisualContext in Element::get_client_rects()
The previous implementation had a bug: it composed all ancestor
transforms but applied them around only the innermost element's
transform origin. The correct behavior is to apply each transform
around its own origin.

AccumulatedVisualContext already tracks all visual transformations
(transforms, scroll offsets, perspective) correctly for hit testing.
This change adds a new transform_rect_to_viewport() method that performs
the forward transformation (element coordinates to viewport
coordinates), which is the inverse direction of
transform_point_for_hit_test().

This fixes getBoundingClientRect() returning incorrect coordinates for
elements inside transformed ancestors with non-default
transform-origins.
2026-01-19 08:53:30 +01:00
Aliaksandr Kalenik
0ab35eee12 LibWeb: Fix spurious relayout triggers in font list comparison
Previously, compute_required_invalidation() compared font lists using
cached_computed_font_list(), which returns the lazily-cached value.
Since newly computed styles haven't had their font list computed yet,
this compared a non-null cached value (old style) against null (new
style), causing unnecessary relayout even when fonts hadn't changed.

Fix by using computed_font_list() to ensure both styles have their
font lists computed before comparison.
2026-01-19 04:01:37 +01:00
Adam Colvin
3a6d82245b LibWeb: Implement Screen.isExtended attribute
- Add WindowManagement to PolicyControlledFeature enum
- Add screen_count() virtual method to PageClient
- Store all screen rects in WebContent::PageClient, derive both
  screen_rect() and screen_count() from stored data
- Implement screen_count() overrides in SVGPageClient and PageHost
- Replace FIXME stub in Screen.cpp with spec-compliant implementation
2026-01-16 20:34:58 +01:00
Aliaksandr Kalenik
bb4e29be5c LibWeb: Remove ClipFrame
Remove the now-obsolete ClipFrame infrastructure:
- Delete ClipFrame.h and ClipFrame.cpp
- Remove assign_clip_frames() from ViewportPaintable
- Remove enclosing_clip_frame and own_clip_frame from PaintableBox
- Remove m_clip_state HashMap from ViewportPaintable

Clip handling is now fully managed through AccumulatedVisualContext
nodes with ClipData.
2026-01-15 19:50:53 +01:00
Aliaksandr Kalenik
a87b5c722d LibWeb: Add AccumulatedVisualContext debugging infrastructure 2026-01-15 19:50:53 +01:00
Aliaksandr Kalenik
04c3ad669b LibWeb: Rebuild AccumulatedVisualContext on transform changes
Ensure AccumulatedVisualContext stays synchronized when CSS transform
properties change.

AccumulatedVisualContext copies transform and perspective matrices from
the paintable tree at assignment time. When CSS properties that affect
these matrices change (transform, rotate, scale, translate, perspective,
transform-origin, perspective-origin), we must rebuild the
AccumulatedVisualContext tree to reflect the new values.

This adds a rebuild_accumulated_visual_contexts flag to style
invalidation that triggers a full rebuild during the next paint.

Note: The current invalidation strategy is inefficient - it rebuilds
the entire tree even for single-element transform changes. This could
be improved by patching the AccumulatedVisualContext node in-place with
updated matrices, but only when the transform doesn't transition
from/to none (which would change the tree structure). This optimization
is left for future work.
2026-01-15 19:50:53 +01:00