Skip to content

Commit e2f1832

Browse files
committed
Fixes for improving Acid3
1 parent 0dcdff5 commit e2f1832

11 files changed

Lines changed: 219 additions & 8 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1+
# 1.2.3
2+
3+
Released on tbd.
4+
5+
- Fixed `undefined` for an argument of an enumeration (e.g. the `how` of `compareBoundaryPoints`) throwing an error scripts could not catch
6+
- Fixed event handler attributes of forms and selects (e.g. `form.onsubmit`) not being set
7+
- Fixed a frame not finding the functions and variables of a script of another window, e.g. `parent.notify()`
8+
- Added the constants of the interfaces, e.g. `Node.ELEMENT_NODE`, `Range.START_TO_END` or `NodeFilter.SHOW_ELEMENT`
9+
110
# 1.2.2
211

312
Released on Sunday, November 15 2026.

‎src/AngleSharp.Js.Docs/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@anglesharp/js",
3-
"version": "1.2.2",
3+
"version": "1.2.3",
44
"preview": true,
55
"description": "The doclet for the AngleSharp.Js documentation.",
66
"keywords": [
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
namespace AngleSharp.Js.Tests
2+
{
3+
using AngleSharp.Dom;
4+
using AngleSharp.Html.Dom;
5+
using NUnit.Framework;
6+
using System.Threading.Tasks;
7+
8+
/// <summary>
9+
/// Behavior the Acid3 test (acid3.acidtests.org) relies on.
10+
/// </summary>
11+
[TestFixture]
12+
public class Acid3Tests
13+
{
14+
[Test]
15+
public async Task ConstantsAreOnTheInterfacesAndTheirInstances()
16+
{
17+
var result = await "[Node.ELEMENT_NODE, document.DOCUMENT_FRAGMENT_NODE, document.documentElement.TEXT_NODE, Range.START_TO_END, document.createRange().END_TO_START, Event.CAPTURING_PHASE, NodeFilter.SHOW_ELEMENT].join()".EvalScriptAsync();
18+
Assert.AreEqual("1,11,3,1,3,1,1", result);
19+
}
20+
21+
[Test]
22+
public async Task ConstantsCannotBeChanged()
23+
{
24+
var result = await "(function () { Node.ELEMENT_NODE = 5; document.ELEMENT_NODE = 6; return [Node.ELEMENT_NODE, document.ELEMENT_NODE].join(); })()".EvalScriptAsync();
25+
Assert.AreEqual("1,1", result);
26+
}
27+
28+
[Test]
29+
public async Task UndefinedForAnEnumerationArgumentIsZero()
30+
{
31+
var result = await "(function () { var r = document.createRange(); return r.compareBoundaryPoints(r.NO_SUCH_CONSTANT, r.cloneRange()); })()".EvalScriptAsync();
32+
Assert.AreEqual("0", result);
33+
}
34+
35+
[Test]
36+
public async Task EventHandlerOfAFormIsNotANamedProperty()
37+
{
38+
var result = await "(function () { var f = document.createElement('form'); var n = 0; f.onsubmit = function () { n++; }; f.appendChild(document.createElement('input')); document.documentElement.appendChild(f); f.dispatchEvent(new Event('submit')); return [n, typeof f.onsubmit, f.length, f[0].tagName].join(); })()".EvalScriptAsync();
39+
Assert.AreEqual("1,function,1,INPUT", result);
40+
}
41+
42+
[Test]
43+
public async Task FrameCallsAFunctionOfItsParent()
44+
{
45+
var config = Configuration.Default.WithJs().WithEventLoop();
46+
var document = await BrowsingContext.New(config).OpenAsync(m => m.Content(@"<body><script>
47+
function notify(value) { document.title = value; }
48+
var f = document.createElement('iframe');
49+
document.body.appendChild(f);
50+
var d = f.contentDocument;
51+
d.open();
52+
d.write('<script>parent.notify(typeof parent.notify + \' from frame\')<\/script>');
53+
d.close();
54+
</script></body>"));
55+
await document.WhenStable();
56+
var frame = (IHtmlInlineFrameElement)document.QuerySelector("iframe");
57+
await frame.ContentDocument.WhenStable();
58+
59+
Assert.AreEqual("function from frame", document.Title);
60+
}
61+
}
62+
}
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
namespace AngleSharp.Js.Cache
2+
{
3+
using AngleSharp.Attributes;
4+
using System;
5+
using System.Collections.Concurrent;
6+
using System.Collections.Generic;
7+
using System.Linq;
8+
using System.Reflection;
9+
10+
/// <summary>
11+
/// The WebIDL constants of the interfaces (e.g. Node.ELEMENT_NODE), which the libraries
12+
/// declare as the fields of an enum named like the interface owning them.
13+
/// </summary>
14+
static class ConstantCache
15+
{
16+
private static readonly ConcurrentDictionary<Assembly, IReadOnlyDictionary<String, KeyValuePair<String, Double>[]>> _constants = new();
17+
18+
// Enums whose name doesn't say the interface owning their constants (AngleSharp 1.10 names
19+
// the document for those of a node, which all nodes have).
20+
private static readonly Dictionary<String, String> _owners = new(StringComparer.Ordinal)
21+
{
22+
{ "AngleSharp.Dom.NodeType", "Node" },
23+
{ "AngleSharp.Dom.DocumentPositions", "Node" },
24+
{ "AngleSharp.Dom.DomError", "DOMException" },
25+
};
26+
27+
public static IEnumerable<KeyValuePair<String, Double>> GetConstants(this IEnumerable<Assembly> libs, String name)
28+
{
29+
if (name is null)
30+
{
31+
return [];
32+
}
33+
34+
return libs
35+
.Select(m => _constants.GetOrAdd(m, Collect))
36+
.SelectMany(m => m.TryGetValue(name, out var constants) ? constants : []);
37+
}
38+
39+
private static IReadOnlyDictionary<String, KeyValuePair<String, Double>[]> Collect(Assembly assembly)
40+
{
41+
var result = new Dictionary<String, List<KeyValuePair<String, Double>>>(StringComparer.Ordinal);
42+
43+
foreach (var type in GetTypes(assembly))
44+
{
45+
var info = type.GetTypeInfo();
46+
47+
if (!info.IsEnum || info.GetCustomAttribute<DomLiteralsAttribute>() != null)
48+
{
49+
continue;
50+
}
51+
52+
var owner = _owners.TryGetValue(type.FullName ?? String.Empty, out var known) ? known :
53+
info.GetCustomAttributes<DomNameAttribute>().FirstOrDefault()?.OfficialName;
54+
55+
if (owner is null)
56+
{
57+
continue;
58+
}
59+
60+
foreach (var field in info.DeclaredFields.Where(m => m.IsLiteral))
61+
{
62+
var constant = field.GetCustomAttributes<DomNameAttribute>().FirstOrDefault()?.OfficialName;
63+
64+
if (constant is not null && IsConstantName(constant))
65+
{
66+
if (!result.TryGetValue(owner, out var list))
67+
{
68+
result[owner] = list = [];
69+
}
70+
71+
if (!list.Any(m => m.Key == constant))
72+
{
73+
list.Add(new KeyValuePair<String, Double>(constant, Convert.ToDouble(field.GetRawConstantValue())));
74+
}
75+
}
76+
}
77+
}
78+
79+
return result.ToDictionary(m => m.Key, m => m.Value.ToArray(), StringComparer.Ordinal);
80+
}
81+
82+
// constants are all upper case (the members of a string enumeration are not)
83+
private static Boolean IsConstantName(String name) =>
84+
name.Length > 0 && Char.IsUpper(name[0]) && name.All(c => Char.IsUpper(c) || Char.IsDigit(c) || c == '_');
85+
86+
private static IEnumerable<Type> GetTypes(Assembly assembly)
87+
{
88+
try
89+
{
90+
return assembly.ExportedTypes;
91+
}
92+
catch (Exception)
93+
{
94+
return [];
95+
}
96+
}
97+
}
98+
}

‎src/AngleSharp.Js/Cache/DomShapeCache.cs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,15 @@ public DomShape Build(Engine engine)
182182
}
183183
}
184184

185+
// The constants are on the prototype as well, so that a node knows them (node.ELEMENT_NODE).
186+
foreach (var constant in _libs.Assemblies.GetConstants(_name))
187+
{
188+
if (!_members.ContainsKey(constant.Key) && !String.Equals(constant.Key, ConstructorName, StringComparison.Ordinal))
189+
{
190+
builder.Constant(constant.Key, JsNumber.Create(constant.Value), true);
191+
}
192+
}
193+
185194
if (constructor != null)
186195
{
187196
// The attributes an eagerly written constructor had, and still resolved on first

‎src/AngleSharp.Js/EngineInstance.cs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -859,7 +859,9 @@ private ObjectInstance CreateInstance(Object obj)
859859

860860
private ObjectInstance CreateInstance(Object obj, Type type)
861861
{
862-
var collection = type.GetIndexedCollection();
862+
// A node indexed like a collection (a form, a select) is a node still: only the node's
863+
// proxy holds its event handler attributes (form.onsubmit), and it asks the indexers too.
864+
var collection = obj is INode ? null : type.GetIndexedCollection();
863865

864866
if (collection != null)
865867
{

‎src/AngleSharp.Js/Extensions/JsValueExtensions.cs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -373,8 +373,13 @@ public static Object As(this JsValue value, Type targetType, EngineInstance engi
373373
}
374374
}
375375

376+
// a WebIDL integer (e.g. the "how" of compareBoundaryPoints): undefined or NaN is 0
376377
var underlyingType = Enum.GetUnderlyingType(targetType);
377-
var raw = Convert.ChangeType(TypeConverter.ToNumber(value), underlyingType);
378+
var integer = TypeConverter.ToNumber(value);
379+
var raw = underlyingType == typeof(Int32) ? TypeConverter.ToInt32(value) :
380+
underlyingType == typeof(UInt32) ? TypeConverter.ToUint32(value) :
381+
underlyingType == typeof(UInt16) ? TypeConverter.ToUint16(value) :
382+
Convert.ChangeType(ToNumeric(integer, Type.GetTypeCode(underlyingType)), underlyingType);
378383
return Enum.ToObject(targetType, raw);
379384
}
380385
else if (Nullable.GetUnderlyingType(targetType) is Type nullableType)

‎src/AngleSharp.Js/JsScriptingService.cs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,14 @@ public Object EvaluateScript(IDocument document, String source, String type, Str
213213

214214
#region Helpers
215215

216+
/// <summary>
217+
/// Gets the engine of the given window, if its document ran scripts already.
218+
/// </summary>
219+
internal static EngineInstance TryGetInstance(IWindow window) =>
220+
window?.Document?.Context?.GetService<JsScriptingService>() is { } service && service._contexts.TryGetValue(window, out var instance)
221+
? instance
222+
: null;
223+
216224
internal EngineInstance GetOrCreateInstance(IDocument document)
217225
{
218226
var objectContext = document.DefaultView;

‎src/AngleSharp.Js/Proxies/DomConstructorInstance.cs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ namespace AngleSharp.Js
1010
using Jint.Runtime.Descriptors;
1111
using Jint.Runtime.Interop;
1212
using System;
13+
using System.Collections.Generic;
1314
using System.Reflection;
1415

1516
sealed class DomConstructorInstance : Constructor
@@ -40,6 +41,18 @@ public DomConstructorInstance(EngineInstance engine, ConstructorDefinition defin
4041
SetOwnProperty("prototype", new PropertyDescriptor(_objectPrototype, false, false, false));
4142

4243
AddStaticMembers(definition.Type.GetStaticMembers());
44+
AddConstants(engine.Libs.GetConstants(definition.Name));
45+
}
46+
47+
private void AddConstants(IEnumerable<KeyValuePair<String, Double>> constants)
48+
{
49+
foreach (var constant in constants)
50+
{
51+
if (GetOwnProperty(constant.Key) == PropertyDescriptor.Undefined)
52+
{
53+
SetOwnProperty(constant.Key, new PropertyDescriptor(JsNumber.Create(constant.Value), false, true, false));
54+
}
55+
}
4356
}
4457

4558
private void AddStaticMembers(StaticMember[] members)

‎src/AngleSharp.Js/Proxies/DomNodeInstance.cs‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -246,11 +246,16 @@ protected override OwnPropertyProbe ProbeOwnProperty(JsValue property)
246246
/// </remarks>
247247
private PropertyDescriptor GetGlobalProperty(JsValue property)
248248
{
249-
if (_value is IWindow)
249+
if (_value is IWindow window)
250250
{
251-
var global = _instance.Jint.Global;
252-
253-
if (!ReferenceEquals(global, this))
251+
// Another window (of the same origin, the others are wrapped) has its globals in the
252+
// engine of its own document: a frame calling parent.notify() finds the function
253+
// the parent declared.
254+
var global = ReferenceEquals(_instance.Window?.Value, window)
255+
? _instance.Jint.Global
256+
: AngleSharp.Scripting.JsScriptingService.TryGetInstance(window)?.Jint.Global;
257+
258+
if (global != null && !ReferenceEquals(global, this))
254259
{
255260
return global.GetOwnProperty(property);
256261
}

0 commit comments

Comments
 (0)