Commit graph

6146 commits

Author SHA1 Message Date
sideshowbarker
4af1b9357b LibWeb: Don't crash when evaluating XPath against a rootless document
Problem: Crash when evaluating an XPath expression against a document
that has no root element.

Cause: mirror_node()’s DOCUMENT_NODE branch unconditionally mirrored
document.document_element(). But a document may lack a root element —
in which case, document_element() returns null.

Fix: Return null from mirror_node() when the document has no root
element. (The caller already maps a null mirror result to a failed
evaluation, and raises an error in that case.)

Fixes https://github.com/LadybirdBrowser/ladybird/issues/10004
2026-06-23 08:59:01 +02:00
Timothy Flynn
a7ce007ff4 LibWeb: Define name and length properties on exported wasm functions
We were previously not setting any name or length properties on exported
functions. Some sites like https://squeel.frankmayer.dev/ rely on these
properties.

The name property is a bit strange. Exported wasm functions have a name
property which is its index in its module instance's function-address
list.

This patch is not enough for the squeel site to be fully functional; we
will need to implement navigator.locks.
2026-06-23 08:57:08 +02:00
Shannon Booth
ef6753a9f9 LibWeb+LibTextCodec: Wire decoder options through TextDecoder
Add explicit IgnoreBOM and ErrorMode options to LibTextCodec decoders,
and thread them through TextDecoder and TextDecoderStream.

This lets Web-facing decoder APIs preserve BOMs when requested and use
fatal error handling without post-processing decoded output.

NB: RemoveBOM was renamed to IgnoreBOM as "RemoveBOM" is the name
used by encoding_rs and was previously an implementation detail.
The new name matches what is used by the encoding standard as it
is now also used in LibWeb.
2026-06-23 07:25:11 +02:00
Shannon Booth
ef99632fa7 Tests/LibWeb: Add some encoding options related WPT tests 2026-06-23 07:25:11 +02:00
Shannon Booth
02320c9b58 LibWeb: Run text encoder/decoder stream algorithms in their realm
Temporarily enter the TextEncoderStream/TextDecoderStream realm while
running their transform and flush algorithms.

This ensures objects and exceptions created through those algorithms are
associated with the constructor realm, matching the encoding streams
realm WPT.

I find this behaviour _somewhat_ strange, and this is only very loosely
specified, but all browsers have aligned on this behviour, so we may
as well match it.
2026-06-23 07:25:11 +02:00
Andreas Kling
b6bef6b688 Libraries: Use UTF-16 for JS-visible runtime strings
Produce JS-visible string results as UTF-16 at their source, including
numeric formatting, BigInt and BigFraction formatting, URI encoding,
console formatting, parser errors, regular expression errors, Intl and
Temporal records, LibUnicode locale boundaries, and LibWeb bindings.

Handle fractional radix formatting through the UTF-16 builder view.
2026-06-22 19:51:25 +02:00
Shannon Booth
f890f289a7 LibWeb: Use resolved subgrid inline size for row contributions
Row subgrid contribution sizing reused the parent grid's available
width, so descendants in flexible columns could contribute an unwrapped
height and then wrap during layout.

Use the resolved subgrid item width when measuring row contributions.
2026-06-22 18:27:22 +02:00
Shannon Booth
870aaa8a1f LibWeb: Resolve subgrid inline sizing before row contributions
When collecting row-axis contributions from subgrid descendants,
resolve the subgrid column metrics first so intrinsic height measurement
uses the correct inline size. This prevents text from being measured as
if it had no usable width, which inflated auto row sizes.
2026-06-22 18:27:22 +02:00
sideshowbarker
b024e45c2c LibWeb: Saturate CSSPixels::abs() at the i32 minimum
Problem: CSSPixels::abs() invokes UB for the i32 minimum raw value.

Cause: abs() returned from_raw(::abs(m_value)) — and ::abs() of the i32
minimum isn’t representable as an int.

Fix: Compute the magnitude with saturating_sub(0, raw_value()) for
negative inputs — so the i32 minimum saturates to the maximum.
2026-06-22 17:00:14 +02:00
Andreas Kling
595ae25e74 LibJS: Use Utf16StringBuilder for JS string construction
Port straightforward JS string construction sites to Utf16StringBuilder.
Make ASCII appends explicit with append_ascii(), and leave byte-output,
formatted-output, and printer plumbing on StringBuilder where that API
still matches the caller.

Add a small checked JS string length product helper. Use it for
String.prototype.repeat() before constructing the repeated result. Keep
the maximum string length policy in LibJS while allowing the UTF-16
builder to remain purpose-built and infallible. Cover overflow from the
final repeated code-unit length in the repeat tests.
2026-06-22 16:10:40 +02:00
Tim Ledbetter
a87f7b9561 LibWeb: Account for visual viewport when scrolling a target into view
This ensures the correct portion of the screen is scrolled into view
when the window is pinch-zoomed.
2026-06-22 14:47:17 +02:00
sideshowbarker
2e86169246 Tests: Serialize Worker-echo messages to eliminate an ordering race
Problem: The Worker-echo.html test flakes under load in CI on the
Sanitizer runners, printing its messages out of order.

Cause: The test asserts a fixed order for messages arriving over two
separate ports: “loaded” over the Worker’s own port, and the channel
messages over the transferred MessagePort. Those two race, with no
cross-port ordering guarantee. So the printed order is nondeterministic.

Fix: Sequence each message explicitly with an awaited helper — the same
approach used for SharedWorker-reuse in #9669 — so the printed order is
deterministic. port2 is left unstarted until after “loaded”.
2026-06-22 14:46:00 +02:00
Tim Ledbetter
0ec95a606f LibWeb: Use computed display value for ::first-letter layout wrappers
Previously, `::first-letter` elements were always wrapped in an inline
box, meaning these elements were not correctly blockified when floated.
2026-06-22 09:43:07 +02:00
Tim Ledbetter
2f84f89874 LibWeb: Drop non-typesetting properties from pseudo element allowlist 2026-06-22 09:43:07 +02:00
Tim Ledbetter
9b06a79b81 LibWeb: Add missing properties to pseudo element allow list 2026-06-22 09:43:07 +02:00
sideshowbarker
9402a6e4e1 LibWeb: Saturate CSSPixels unary negation at the i32 minimum
Problem: UBSan crash when computing layout for an element with a giant
negative inset.

Cause: CSSPixels::operator-() returned from_raw(-raw_value()), and
negating the i32 minimum overflows int.

Fix: Negate with saturating_sub(0, raw_value()) — matching the
saturating arithmetic already used by the other CSSPixels operators.

Fixes https://github.com/LadybirdBrowser/ladybird/issues/9997
2026-06-21 15:44:07 +02:00
sideshowbarker
86f75e1e35 LibWeb: Saturate list-item ordinal numbering at the i32 bounds
Problem: Crash when loading an ordered list whose numbering reaches the
i32 limit; e.g. <ol start="2147483647"> with two or more items.

Cause: Element::ordinal_value() kept its numbering in a Checked<i32>
and stepped it once per list item. When the numbering already sits at
the i32 maximum (or minimum, for a reversed list whose value attribute
pins it there), the increment overflowed the Checked value.

Fix: Keep the numbering in a plain i32 instead, and step it with
AK::saturating_add and AK::saturating_sub — so it clamps at the i32
bounds, rather than overflowing.

Fixes https://github.com/LadybirdBrowser/ladybird/issues/10003
2026-06-21 14:48:23 +02:00
sideshowbarker
9ffd3e48c3 LibWeb: Don’t crash on a detached publicExponent in generateKey
Problem: Crash when generating an RSA key — or serializing one —
whose publicExponent is a typed array whose backing ArrayBuffer has
been detached; for example, by calling transfer() on it.

Cause: Two places with big_integer_from_api_big_integer() reading the
bytes of the backing ArrayBuffer directly. But reading the bytes of a
detached buffer aborts.

Fix: Read the bytes with WebIDL get_buffer_source_copy() — which yields
an empty copy for a detached, or OOB resizable, buffer. The empty array
is already mapped to zero — so generation rejects the zero exponent with
an error, rather than crashing.

Fixes https://github.com/LadybirdBrowser/ladybird/issues/9991
2026-06-21 14:04:01 +02:00
Callum Law
9183c2a029 LibWeb: Bail on unresolved percentages in resolve_value
Previously we assumed that if the calculation had been simplified to a
single `NumericCalculationNode` that we could resolve it - this isn't
the case if we have a percentage that should be resolved to a different
type.

Fixes #10209
2026-06-21 08:18:50 +01:00
Tim Ledbetter
360bfd66f6 LibWeb: Apply the font-variant-emoji property to font selection 2026-06-20 23:51:46 +02:00
Andreas Kling
2bf1f41805 LibWeb: Make computed properties immutable
Move CSS animation values into a mutable overlay on computed properties
and make base computed style data immutable after construction. Base
style mutation now goes through a builder that is consumed on publish,
so installed styles no longer expose mutation APIs.

Build new base style data for inherited style updates instead of cloning
and mutating installed computed properties. Element-specific computed
style adjustments now run before publication, while animation and
transition updates continue to mutate only the animated overlay.
2026-06-20 23:43:17 +02:00
Shannon Booth
7b0dd6ab30 LibTextCodec: Use encoding_rs for legacy codecs
Replace the generated C++ legacy codec implementations with a
small Rust wrapper around encoding_rs.

This keeps the existing LibTextCodec API while moving label lookup,
legacy decode/encode, validation, and streaming decoder state to Rust.
The generated index data and generator are no longer needed.

It also fixes several TextDecoder EOF cases due to a more correct
implementation. encoding_rs finalizes decoders according to the
Encoding Standard, so incomplete UTF-8/Big5 tails and malformed
UTF-16 surrogate tails produce the required single replacement at
end-of-queue instead of being dropped, buffered, or double-counted
by our old hand-written decoders.
2026-06-20 21:56:43 +02:00
Shannon Booth
250842d36a LibURL: Use encoding_rs for form URL encoding
Replace the Rust URL form-encoding callback bridge into C++ TextCodec
with a direct encoding_rs encoder.

This keeps percent-encode-after-encoding entirely in Rust and removes
liburl_rust's dependency on LibTextCodec.

It also happens to fix ISO-2022-JP URL encoding of literal U+FFFD.

The LibTextCodec reverse lookup treats generated 0xFFFD table holes as
real JIS0208 mappings, so literal U+FFFD skipped the encoder-error
path. encoding_rs treats U+FFFD as unmappable, so URL encoding emits
the required numeric character reference.
2026-06-20 21:56:43 +02:00
Shannon Booth
3a0f857cc1 Tests: Import some encoding related WPT tests 2026-06-20 21:56:43 +02:00
Andreas Kling
6eba8860f7 LibWeb: Add a lazy fast reject filter for :has()
Build a per-anchor Bloom-style filter for :has() argument matching
after an anchor sees a second check for the same traversal scope. The
filter stores salted tag, id, class, and attribute-name hashes from the
child or descendant scope and rejects arguments whose required
identifiers are absent.

This avoids repeatedly walking the same subtree for unrelated :has()
arguments while preserving the single-check case. More complex
direct-child arguments use the descendant scope so hashes from later
descendant compounds cannot cause false rejections.

Keep the filter conservative for quirks-mode class selectors and for
sibling-combinator relative selectors during invalidation metadata
collection. Text tests cover cache-primed misses for both cases.
2026-06-19 14:52:48 +02:00
Callum Law
fdca036ff3 LibWeb: Implement CSS progress() math function
`no-clamp` tests are added in-tree since there aren't any in WPT yet.
2026-06-19 09:33:06 +01:00
Tim Ledbetter
a9261b9daf test-web: Don't include skipped tests in --dry-run output 2026-06-19 09:47:55 +02:00
Luke Wilde
8dc8835b64 LibWeb+LibWebView+WebContent: Allow muted media to autoplay by default
The autoplay setting was binary and its default blocked all media,
including muted video, leaving sites that rely on muted autoplay
visibly broken. Replace it with a tri-state user-agent autoplay
policy (allow audio and video, block audio, or block audio and video)
defaulting to allowing only inaudible media to autoplay.

This is enforced through the media element's "allowed to play" check,
so unmuting a muted autoplay or calling `play()` cannot slip audio
past the policy; audible playback is permitted once the document has
been activated by the user. The policy lives in a dedicated
AutoplaySettings consulted from HTMLMediaElement instead of the
Permissions Policy "allowed to use feature" check it was previously
conflated with.
2026-06-19 09:41:32 +02:00
Andreas Kling
8e473cb703 LibWeb: Bucket pseudo :is() rules by originating element
Split pseudo-element rules whose originating compound contains :is() or
:where() across the cheap buckets from their selector-list alternatives
when the rule would otherwise land in the pseudo-element other bucket.

Use per-collection generation stamps to suppress duplicate candidates
when more than one alternative bucket applies to the same originating
element. Add text coverage for class, attribute, and complex combinator
arguments reaching generated pseudo-element style.
2026-06-19 09:36:53 +02:00
Jelle Raaijmakers
d819152b4e LibGfx+LibWeb: Preserve text color for selections
Selecting text without custom ::selection styling changed the
foreground color of the selected content. This was especially visible
for links, where the text changed color but the underline did not.

The default selection style supplied both a selection background and a
foreground color from the palette or HighlightText system color. That
made ordinary selections behave as if the page had explicitly styled
::selection color.

Only provide a default selection background, so selected content keeps
its own foreground color unless CSS overrides it. Remove the now-unused
SelectionText palette role.
2026-06-18 22:43:26 +02:00
Tim Ledbetter
91d3d135eb LibWeb: Paint emoji glyph text-shadows in the shadow color 2026-06-18 22:42:29 +02:00
Andreas Kling
86e0e281a0 LibWeb: Avoid unnecessary pseudo-element style recomputation
Track the synthetic pseudo-elements that matched while computing an
originating element's normal style. Store the transient match set as a
bitfield, then copy those bits into ComputedProperties. Use them during
style invalidation to skip pseudo style recomputation when neither the
old nor new originating style matched pseudo rules and no pseudo style
already exists.

This shaves roughly 500 ms off loading the Ladybird GitHub repository.

Materialize synthetic pseudo styles on demand for CSSOM reads so
getComputedStyle(element, "::before") still computes skipped styles when
script asks for them. Add coverage for a universal pseudo selector, and
update style invalidation counter expectations for the reduced work.
2026-06-18 19:50:34 +02:00
Tim Ledbetter
340ef361d8 LibWeb: Support anchor() in calc() trees
Previously, `anchor()`  was only resolved when it appeared bare in an
inset property. We now allow it to appear anywhere inside a `calc()`
tree.
2026-06-18 17:36:56 +01:00
Tim Ledbetter
b62a099e91 LibWeb: Serialize a non-math function at the root of a calc() tree
Previously, math function serialization assumed the calculation tree
root was a numeric value or a calc-operator node, and otherwise emitted
the root's name followed by its comma-separated children.
A non-math function node such as `sibling-index()` or `anchor()` has no
children, so a `calc()` whose entire contents was such a function
serialized to an empty "calc()". We now serialize the function directly
instead.
2026-06-18 17:36:56 +01:00
Andreas Kling
849d528220 LibWeb: Build style invalidation data lazily
Split StyleCache's rule matching data from its invalidation metadata.
Allow callers to build either payload independently. Style invalidation
queries no longer force a full rule cache rebuild, and rule matching
no longer builds invalidation metadata as a side effect.

Previously, callers often treated an absent rule cache as proof that no
style invalidation metadata existed. That made some invalidation paths
do nothing until something else had populated the rule cache first.
Build invalidation data before reading it instead, so these paths use
the metadata whenever stylesheet rules require it.

Rebaseline style invalidation counter expectations for the new lazy
build points. Flush setup style work in the structural :has() feature
filter test before measuring each mutation, so the recomputation
counters describe the mutation itself instead of leftover setup work.
2026-06-18 15:45:12 +02:00
Jelle Raaijmakers
d8a55dad1c LibWeb: Target :active and :open invalidation
Changing :active or :open used the broad style invalidation path, so
large subtrees were recomputed even when only the target element and
selector-matched relatives could be affected.

Reuse the :has() feature collector to keep conservative fallback for
observable :has() cases, then use pseudo-class property invalidation
for the common targeted path.
2026-06-18 13:42:51 +02:00
sideshowbarker
4bbc5e0950 LibWeb: Fix crash from SVG resource boxes outliving removed element
Problem: Crash when removing a <mask>, <clipPath>, or <pattern> element
that’s referenced via url(#id), and then GC’ing it.

Cause: <mask>, <clipPath>, and <pattern> are laid out as resource boxes
attached to the referencing element's layout subtree, rather than their
own. So those survive cleanup of their DOM ancestor. Once a removed
<mask>/<clipPath>/<pattern> is collected, its resource box’s weak DOM
node pointer is null. And dereferencing that trips an assert — both
while painting and while tearing down the layout tree.

Fix: When a <mask>, <clipPath>, or <pattern> is removed, request a full
layout-tree update while the element’s still alive. That drops the stale
resource boxes (whose url(#id) references no longer resolve) before the
node gets collected.

Fixes https://github.com/LadybirdBrowser/ladybird/issues/10127
2026-06-18 13:35:32 +02:00
Andreas Kling
4daec8f6e0 LibWeb: Use Event storage for MouseEvent relatedTarget
Store MouseEvent's relatedTarget in the inherited Event field instead of
keeping a second slot on MouseEvent.

Event dispatch retargets and updates the inherited field while building
the event path. The second slot left JS listeners observing stale or
null relatedTarget values during mouse and pointer boundary events.

Add coverage for boundary events between sibling elements.
2026-06-18 12:40:37 +02:00
Callum Law
64f866cae2 LibWeb: Support number/percentage interpolation for scale
Previously we didn't support interpolating component values of `scale`
from a number to a percentage (or vice versa). This also caused
interpolation from `none` to a percentage value to fail since the
fallback value is number based.

This makes the transition run when hovering buttons on
https://chrede88.github.io/L1nkr/ rather than being discrete.
2026-06-18 12:26:22 +02:00
Callum Law
2c6aa4d272 LibWeb: Apply null transform properties on style recomputation
When applying style in `Layout::Node::apply_style` we previously ignored
null `rotate`, `translate`, and `scale` values which left the old values
in place in the case of nonnull -> null changes.

Fixes #10125
2026-06-18 12:26:22 +02:00
Sam Atkins
147d4595c6 LibWebView: Restore RFC cookie storage behavior
In 11b053b154 I accidentally changed the
behaviour of CookieJar::set_cookie() to not match what the RFC
requires, particularly when dealing with too-long paths. This commit
restores the original behaviour, now that the validation required by
DevTools happens elsewhere, before set_cookie() is called.
2026-06-18 11:37:36 +02:00
sideshowbarker
9f7a328d9b LibWeb: Reject canvas toDataURL()/toBlob() when not origin-clean
Problem: Drawing a cross-origin image onto a 2D canvas clears its
origin-clean flag, but toDataURL() and toBlob() ignored that flag and
serialized the bitmap regardless. So, a page could read back the
cross-origin pixels it shouldn't (per spec) be allowed to access.

Cause: The origin-clean checks in to_data_url() and to_blob() were left
as FIXMEs. Only getImageData() enforced the flag.

Fix: Throw a SecurityError exception from both serialization entry
points when the canvas isn't origin-clean — matching getImageData() and
the spec. The same check also implements the previously-stubbed
origin-clean step in the WebDriver canvas-encoding algorithm.

Fixes: https://github.com/LadybirdBrowser/ladybird/issues/10009
2026-06-18 10:52:42 +02:00
Jelle Raaijmakers
d642f7d85a LibWeb: Do not dump number of children for StackingContexts
The number of children a SC has is not that useful in dumps, when all
its children are dumped anyway.
2026-06-18 10:50:08 +02:00
Callum Law
8ebdaeab69 LibWeb: Transfer animation ownership to AnimatedBitmapDecodedImageData
Previously animation ownership was a messy split between
`AnimatedBitmapDecodedImageData` and the consumers (i.e.
`ImageStyleValueResource`, `HTMLImageElement`, and `SVGImageElement`)
with `AnimatedBitmapDecodedImageData` owning the frames and a current
frame index, and the consumers owning the rest of the state (e.g. loop
count, timers to drive the animation forward, their own current index).

This had a couple of main issues:
 - While `AnimatedDecodedImageData` partially synchronized animations by
   dropping unexpected advancement notifications, this didn't apply to
   other animation state which meant, for instance, that a later started
   consumer could drive the animation of an earlier one past the max
   loop count (albeit without invalidating the earlier consumer).
 - Multiple consumers didn't share frame timings, meaning animations
   could be up to a full frame out of sync visually.
 - Animations were paused depending on whether there were any consumers,
   this is different to the behavior in other browsers (where they
   continue regardless of whether there are any consumers).
 - It was an overgeneralization of how animations need to work - only
   `AnimatedBitmapDecodedImageData` works with an indexed frame model,
   with animated SVGs (although not yet implemented) relying on their
   internal event loop to be driven forward.

Given the above the new approach implemented in this commit is:
 - The API for `DecodedImageData` is animation system agnostic, only
   exposing `default_frame`, `current_frame`, and `restart_animation`
   methods not reliant on providing a specific frame index.
 - `AnimatedBitmapDecodedImageData` owns its own timer, loop count,
   etc. The animation starts when the first consumer registers and ends
   when the document is hidden or becomes inactive (or completes in the
   case of finite animations).
 - Consumers are invalidated by `AnimatedBitmapDecodedImageData` when
   required.

Tests have been added for:
 - Animations being paused when the document becomes inactive and
   restarted when it becomes active again.
 - Frame timings being synchronized across consumers.
 - Restarts triggered by `HTMLImageElement` applying to all consumers.
 - Processing ending once a non-infinite animation plays to completion.

The tests to ensure animations are cancelled when consumers are removed
(e.g. `animated-background-image-timer-stops-when-hidden.html`) have
been updated to assert the inverse since animation state is now per
resource not per consumer.
2026-06-18 10:44:25 +02:00
Callum Law
2335941e43 LibWeb: Register ImageObservers for all mask-images
As of 114c8a7 we paint all mask layers, not just the first, so we should
likewise observe all `mask-image` values, not just the first.
2026-06-18 10:44:25 +02:00
Callum Law
11ab66c752 LibWeb: Notify ImageStyleValue::Clients on animation
Previously image animations driven by `ImageStyleValueResource`
invalidated clients using `on_animate`, this was only implemented by the
`background` presentational attribute of `HTMLBodyElement`.

It now uses `notify_clients_did_update` which is implemented by all
clients.
2026-06-18 10:44:25 +02:00
Callum Law
d98c5d1b03 LibWeb: Inline image scaling mode computation
This allows us to remove the `frame_rect` accessor.

This also fixes a bug where we computed the scaling mode based on the
clipping rect rather than the draw rect for `ImagePaintable`
2026-06-18 10:44:25 +02:00
Callum Law
d3c0cfdc71 LibWeb: Respect SVG intrinsic sizing during object fitting
Previously we used the `frame_rect` size, this is the same as the
intrinsic size for bitmap images but is `OptionalNone` for SVG which
caused us to always fall back to the `image_rect` and thus not apply
any scaling for SVGs regardless of whether they had intrinsic sizing.
2026-06-18 10:44:25 +02:00
Aliaksandr Kalenik
23885e7b4d LibWeb+WebContent+WebWorker: Drop display list player type selection
WebContent no longer chooses between CPU and GPU display list players,
and the remaining callers always use Skia raster playback. Remove the
PageClient virtual and now-single-value enum, then play SVG image and
cursor display lists directly.
2026-06-18 10:25:44 +02:00
Jelle Raaijmakers
9ed75e4f50 LibWeb/CSS: Retain length precision in PercentageOr<T>
Instead of operating within the (saturating) CSSPixels constraints,
calculate the expected value using a floating point calculation first
and then create the CSSPixels value.
2026-06-18 09:59:41 +02:00