ps-blitz-script 0.3.0-beta.6

JavaScript execution for Blitz using the Boa engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
//! The `Element` prototype: attributes, DOM properties (`value`, `checked`, ...),
//! `style`, `innerHTML` and friends.

use blitz_dom::NodeId;
use blitz_dom::{LocalName, QualName};
use boa_engine::object::{JsObject, ObjectInitializer, builtins::JsProxyBuilder};
use boa_engine::property::{Attribute as PropAttribute, PropertyKey};
use boa_engine::value::JsValue;
use boa_engine::{Context, Finalize, JsData, JsNativeError, JsResult, Trace, js_string};

use super::{
    define_accessor, define_method, dom_ctx, js_str, node_wrapper, this_node_id, to_rust_string,
};
use crate::state::DomCtx;

/// Construct a `QualName` for an attribute (no namespace)
pub(crate) fn attr_name(local: &str) -> QualName {
    QualName::new(None, markup5ever::ns!(), LocalName::from(local))
}

pub(crate) fn init_element_proto(proto: &JsObject, context: &mut Context) {
    define_accessor(proto, "tagName", Some(tag_name), None, context);
    define_accessor(proto, "localName", Some(local_name), None, context);
    define_accessor(proto, "namespaceURI", Some(namespace_uri), None, context);
    define_accessor(proto, "id", Some(get_id), Some(set_id), context);
    define_accessor(proto, "src", Some(get_src), Some(set_src), context);
    define_accessor(
        proto,
        "className",
        Some(get_class_name),
        Some(set_class_name),
        context,
    );
    define_accessor(proto, "value", Some(get_value), Some(set_value), context);
    define_accessor(
        proto,
        "checked",
        Some(get_checked),
        Some(set_checked),
        context,
    );
    define_accessor(
        proto,
        "disabled",
        Some(get_disabled),
        Some(set_disabled),
        context,
    );
    define_accessor(
        proto,
        "placeholder",
        Some(get_placeholder),
        Some(set_placeholder),
        context,
    );
    define_accessor(proto, "type", Some(get_type), Some(set_type), context);
    define_accessor(
        proto,
        "autofocus",
        Some(get_autofocus),
        Some(set_autofocus),
        context,
    );
    define_accessor(proto, "style", Some(get_style), None, context);
    define_accessor(proto, "dataset", Some(get_dataset), None, context);
    define_accessor(proto, "classList", Some(get_class_list), None, context);
    define_accessor(
        proto,
        "innerHTML",
        Some(get_inner_html),
        Some(set_inner_html),
        context,
    );
    define_accessor(proto, "outerHTML", Some(get_outer_html), None, context);
    define_accessor(proto, "children", Some(children), None, context);
    define_accessor(proto, "content", Some(get_template_content), None, context);
    define_accessor(
        proto,
        "scrollLeft",
        Some(get_scroll_left),
        Some(set_scroll_left),
        context,
    );
    define_accessor(
        proto,
        "scrollTop",
        Some(get_scroll_top),
        Some(set_scroll_top),
        context,
    );
    define_accessor(proto, "scrollWidth", Some(get_scroll_width), None, context);
    define_accessor(
        proto,
        "scrollHeight",
        Some(get_scroll_height),
        None,
        context,
    );
    define_accessor(proto, "clientWidth", Some(get_client_width), None, context);
    define_accessor(
        proto,
        "clientHeight",
        Some(get_client_height),
        None,
        context,
    );
    define_accessor(proto, "offsetWidth", Some(get_offset_width), None, context);
    define_accessor(
        proto,
        "offsetHeight",
        Some(get_offset_height),
        None,
        context,
    );
    define_accessor(proto, "offsetLeft", Some(get_offset_left), None, context);
    define_accessor(proto, "offsetTop", Some(get_offset_top), None, context);

    define_method(proto, "getAttribute", 1, get_attribute, context);
    define_method(proto, "setAttribute", 2, set_attribute, context);
    define_method(proto, "removeAttribute", 1, remove_attribute, context);
    define_method(proto, "hasAttribute", 1, has_attribute, context);
    define_method(proto, "focus", 0, focus, context);
    define_method(proto, "blur", 0, blur, context);
    define_method(
        proto,
        "getBoundingClientRect",
        0,
        get_bounding_client_rect,
        context,
    );
    define_method(proto, "querySelector", 1, query_selector, context);
    define_method(proto, "querySelectorAll", 1, query_selector_all, context);
    define_method(proto, "matches", 1, matches_selector, context);
    define_method(proto, "closest", 1, closest, context);
    define_method(proto, "setPointerCapture", 1, set_pointer_capture, context);
    define_method(
        proto,
        "releasePointerCapture",
        1,
        release_pointer_capture,
        context,
    );
    define_method(proto, "hasPointerCapture", 1, has_pointer_capture, context);
}

fn pointer_id_arg(args: &[JsValue], context: &mut Context) -> JsResult<u64> {
    let value = args
        .first()
        .unwrap_or(&JsValue::undefined())
        .to_number(context)?;
    if !value.is_finite() || value < 0.0 {
        return Err(JsNativeError::typ()
            .with_message("pointerId must be a non-negative finite number")
            .into());
    }
    Ok(value as u64)
}

fn set_pointer_capture(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let pointer_id = pointer_id_arg(args, context)?;
    ctx.state
        .borrow_mut()
        .pointer_capture
        .insert(pointer_id, node_id);
    Ok(JsValue::undefined())
}

fn release_pointer_capture(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let pointer_id = pointer_id_arg(args, context)?;
    let mut state = ctx.state.borrow_mut();
    if state.pointer_capture.get(&pointer_id) == Some(&node_id) {
        state.pointer_capture.remove(&pointer_id);
    }
    Ok(JsValue::undefined())
}

fn has_pointer_capture(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let pointer_id = pointer_id_arg(args, context)?;
    Ok(JsValue::from(
        ctx.state.borrow().pointer_capture.get(&pointer_id) == Some(&node_id),
    ))
}

// === Attribute helpers ===

fn read_attr(ctx: &DomCtx, node_id: NodeId, name: &str) -> Option<String> {
    let doc = ctx.doc.borrow();
    let node = doc.get_node(node_id)?;
    let element = node.element_data()?;
    element
        .attrs()
        .iter()
        .find(|attr| &*attr.name.local == name)
        .map(|attr| attr.value.clone())
}

fn write_attr(ctx: &DomCtx, node_id: NodeId, name: &str, value: &str) {
    // Timed here rather than at `setAttribute`, because that method is the
    // least used way in. The reflected properties (`value`, `className`, `id`)
    // and every classList mutation reach the DOM through this function and
    // through nothing else, and while they were uncounted a keystroke looked
    // like it touched no DOM at all while dirtying layout every time.
    let _t = crate::script_stats::Timed::new(ctx, "dom:attr=");
    let mut doc = ctx.mutate_doc();
    doc.mutate().set_attribute(node_id, attr_name(name), value);
}

fn clear_attr(ctx: &DomCtx, node_id: NodeId, name: &str) {
    let _t = crate::script_stats::Timed::new(ctx, "dom:attr-remove");
    let mut doc = ctx.mutate_doc();
    doc.mutate().clear_attribute(node_id, attr_name(name));
}

fn attr_getter(name: &str, this: &JsValue, context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    Ok(js_str(&read_attr(&ctx, node_id, name).unwrap_or_default()))
}

fn attr_setter(
    name: &str,
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let value = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?;
    write_attr(&ctx, node_id, name, &value);
    Ok(JsValue::undefined())
}

// === Basic element info ===

fn tag_name(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let doc = ctx.doc.borrow();
    let name = doc
        .get_node(node_id)
        .and_then(|node| node.element_data())
        .map(|element| element.name.local.to_uppercase())
        .unwrap_or_default();
    Ok(js_str(&name))
}

fn local_name(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let doc = ctx.doc.borrow();
    let name = doc
        .get_node(node_id)
        .and_then(|node| node.element_data())
        .map(|element| element.name.local.to_string())
        .unwrap_or_default();
    Ok(js_str(&name))
}

fn namespace_uri(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let doc = ctx.doc.borrow();
    let ns = doc
        .get_node(node_id)
        .and_then(|node| node.element_data())
        .map(|element| element.name.ns.to_string())
        .unwrap_or_default();
    Ok(js_str(&ns))
}

fn children(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let child_ids: Vec<NodeId> = {
        let doc = ctx.doc.borrow();
        doc.get_node(node_id)
            .map(|node| {
                node.children
                    .iter()
                    .copied()
                    .filter(|child_id| {
                        doc.get_node(*child_id)
                            .is_some_and(|child| child.is_element())
                    })
                    .collect()
            })
            .unwrap_or_default()
    };
    let wrappers: Vec<JsValue> = child_ids
        .into_iter()
        .map(|child_id| node_wrapper(&ctx, child_id, context).into())
        .collect();
    Ok(boa_engine::object::builtins::JsArray::from_iter(wrappers, context).into())
}

// === Attributes ===

fn get_attribute(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let name = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?
        .to_ascii_lowercase();
    match read_attr(&ctx, node_id, &name) {
        Some(value) => Ok(js_str(&value)),
        None => Ok(JsValue::null()),
    }
}

fn set_attribute(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let name = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?
        .to_ascii_lowercase();
    let value = to_rust_string(args.get(1).unwrap_or(&JsValue::undefined()), context)?;
    write_attr(&ctx, node_id, &name, &value);
    Ok(JsValue::undefined())
}

fn remove_attribute(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let name = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?
        .to_ascii_lowercase();
    clear_attr(&ctx, node_id, &name);
    Ok(JsValue::undefined())
}

fn has_attribute(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let name = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?
        .to_ascii_lowercase();
    Ok(JsValue::from(read_attr(&ctx, node_id, &name).is_some()))
}

// === Reflected DOM properties ===

fn get_id(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let _ = args;
    attr_getter("id", this, context)
}
fn set_id(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    attr_setter("id", this, args, context)
}

/// `src`, reflected to the attribute.
///
/// Without this, `element.src = url` set a plain JavaScript property and the
/// DOM never heard about it, so nothing that reads the attribute — the script
/// runner, the image loader — could see what the page had asked for. Every
/// loader that builds a `<script>` and assigns `src` rather than calling
/// `setAttribute` was silently inert.
fn get_src(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let _ = args;
    attr_getter("src", this, context)
}
fn set_src(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    attr_setter("src", this, args, context)
}

fn get_class_name(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let _ = args;
    attr_getter("class", this, context)
}
fn set_class_name(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    attr_setter("class", this, args, context)
}

fn get_placeholder(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let _ = args;
    attr_getter("placeholder", this, context)
}
fn set_placeholder(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    attr_setter("placeholder", this, args, context)
}

fn get_type(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let _ = args;
    attr_getter("type", this, context)
}
fn set_type(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    attr_setter("type", this, args, context)
}

fn get_autofocus(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    Ok(JsValue::from(
        read_attr(&ctx, node_id, "autofocus").is_some(),
    ))
}
fn set_autofocus(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let value = args.first().map(JsValue::to_boolean).unwrap_or(false);
    if value {
        // The empty string, as a boolean attribute is written everywhere else.
        write_attr(&ctx, node_id, "autofocus", "");
    } else {
        clear_attr(&ctx, node_id, "autofocus");
    }
    Ok(JsValue::undefined())
}

fn get_value(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let value = {
        let doc = ctx.doc.borrow();
        doc.get_node(node_id)
            .and_then(|node| node.element_data())
            .map(|element| match element.text_input_data() {
                Some(input_data) => input_data.editor.text().to_string(),
                None => element
                    .attrs()
                    .iter()
                    .find(|attr| &*attr.name.local == "value")
                    .map(|attr| attr.value.clone())
                    .unwrap_or_default(),
            })
            .unwrap_or_default()
    };
    Ok(js_str(&value))
}

fn set_value(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    attr_setter("value", this, args, context)
}

fn get_checked(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let checked = {
        let doc = ctx.doc.borrow();
        doc.get_node(node_id)
            .and_then(|node| node.element_data())
            .map(|element| {
                element
                    .checkbox_input_checked()
                    .unwrap_or_else(|| element.attr(blitz_dom::local_name!("checked")).is_some())
            })
            .unwrap_or(false)
    };
    Ok(JsValue::from(checked))
}

fn set_checked(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let checked = args.first().map(JsValue::to_boolean).unwrap_or(false);
    // blitz-dom's checked handling parses the value as a boolean
    write_attr(
        &ctx,
        node_id,
        "checked",
        if checked { "true" } else { "false" },
    );
    Ok(JsValue::undefined())
}

fn get_disabled(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    Ok(JsValue::from(
        read_attr(&ctx, node_id, "disabled").is_some(),
    ))
}

fn set_disabled(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let disabled = args.first().map(JsValue::to_boolean).unwrap_or(false);
    if disabled {
        write_attr(&ctx, node_id, "disabled", "");
    } else {
        clear_attr(&ctx, node_id, "disabled");
    }
    Ok(JsValue::undefined())
}

// === dataset ===

#[derive(Trace, Finalize, JsData)]
struct DatasetRef {
    #[unsafe_ignore_trace]
    node_id: NodeId,
}

fn dataset_ref(args: &[JsValue]) -> JsResult<NodeId> {
    args.first()
        .and_then(JsValue::as_object)
        .and_then(|target| target.downcast_ref::<DatasetRef>().map(|data| data.node_id))
        .ok_or_else(|| {
            JsNativeError::typ()
                .with_message("dataset proxy target is invalid")
                .into()
        })
}

fn dataset_key(value: &JsValue, context: &mut Context) -> JsResult<Option<String>> {
    Ok(match value.to_property_key(context)? {
        PropertyKey::String(key) => Some(key.to_std_string_lossy()),
        PropertyKey::Index(key) => Some(key.get().to_string()),
        PropertyKey::Symbol(_) => None,
    })
}

fn dataset_attr_name(key: &str) -> String {
    let mut name = String::with_capacity(key.len() + 5);
    name.push_str("data-");
    for ch in key.chars() {
        if ch.is_ascii_uppercase() {
            name.push('-');
            name.push(ch.to_ascii_lowercase());
        } else {
            name.push(ch);
        }
    }
    name
}

fn dataset_property_name(attr: &str) -> Option<String> {
    let suffix = attr.strip_prefix("data-")?;
    let mut key = String::with_capacity(suffix.len());
    let mut chars = suffix.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch == '-' && chars.peek().is_some_and(char::is_ascii_lowercase) {
            key.push(chars.next().expect("peeked character").to_ascii_uppercase());
        } else {
            key.push(ch);
        }
    }
    Some(key)
}

fn dataset_get(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let Some(key) = dataset_key(args.get(1).unwrap_or(&JsValue::undefined()), context)? else {
        return Ok(JsValue::undefined());
    };
    let ctx = dom_ctx(context)?;
    let node_id = dataset_ref(args)?;
    Ok(read_attr(&ctx, node_id, &dataset_attr_name(&key))
        .map_or_else(JsValue::undefined, |value| js_str(&value)))
}

fn dataset_set(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let Some(key) = dataset_key(args.get(1).unwrap_or(&JsValue::undefined()), context)? else {
        return Ok(JsValue::from(false));
    };
    let value = to_rust_string(args.get(2).unwrap_or(&JsValue::undefined()), context)?;
    let ctx = dom_ctx(context)?;
    let node_id = dataset_ref(args)?;
    write_attr(&ctx, node_id, &dataset_attr_name(&key), &value);
    Ok(JsValue::from(true))
}

fn dataset_delete(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let Some(key) = dataset_key(args.get(1).unwrap_or(&JsValue::undefined()), context)? else {
        return Ok(JsValue::from(true));
    };
    let ctx = dom_ctx(context)?;
    let node_id = dataset_ref(args)?;
    clear_attr(&ctx, node_id, &dataset_attr_name(&key));
    Ok(JsValue::from(true))
}

fn dataset_has(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let Some(key) = dataset_key(args.get(1).unwrap_or(&JsValue::undefined()), context)? else {
        return Ok(JsValue::from(false));
    };
    let ctx = dom_ctx(context)?;
    let node_id = dataset_ref(args)?;
    Ok(JsValue::from(
        read_attr(&ctx, node_id, &dataset_attr_name(&key)).is_some(),
    ))
}

fn dataset_own_keys(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = dataset_ref(args)?;
    let keys: Vec<JsValue> = {
        let doc = ctx.doc.borrow();
        doc.get_node(node_id)
            .and_then(|node| node.element_data())
            .map(|element| {
                element
                    .attrs()
                    .iter()
                    .filter_map(|attr| dataset_property_name(&attr.name.local))
                    .map(|key| js_str(&key))
                    .collect()
            })
            .unwrap_or_default()
    };
    Ok(boa_engine::object::builtins::JsArray::from_iter(keys, context).into())
}

fn dataset_descriptor(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let Some(key) = dataset_key(args.get(1).unwrap_or(&JsValue::undefined()), context)? else {
        return Ok(JsValue::undefined());
    };
    let ctx = dom_ctx(context)?;
    let node_id = dataset_ref(args)?;
    let Some(value) = read_attr(&ctx, node_id, &dataset_attr_name(&key)) else {
        return Ok(JsValue::undefined());
    };
    Ok(ObjectInitializer::new(context)
        .property(js_string!("value"), js_str(&value), PropAttribute::all())
        .property(js_string!("writable"), true, PropAttribute::all())
        .property(js_string!("enumerable"), true, PropAttribute::all())
        .property(js_string!("configurable"), true, PropAttribute::all())
        .build()
        .into())
}

fn get_dataset(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    if let Some(dataset) = ctx.state.borrow().dataset_wrappers.get(&node_id) {
        return Ok(dataset.clone().into());
    }

    let target = JsObject::from_proto_and_data(
        Some(context.intrinsics().constructors().object().prototype()),
        DatasetRef { node_id },
    );
    let dataset: JsObject = JsProxyBuilder::new(target)
        .get(dataset_get)
        .set(dataset_set)
        .delete_property(dataset_delete)
        .has(dataset_has)
        .own_keys(dataset_own_keys)
        .get_own_property_descriptor(dataset_descriptor)
        .build(context)?
        .into();
    ctx.state
        .borrow_mut()
        .dataset_wrappers
        .insert(node_id, dataset.clone());
    Ok(dataset.into())
}

// === classList ===

fn class_tokens(ctx: &DomCtx, node_id: NodeId) -> Vec<String> {
    read_attr(ctx, node_id, "class")
        .unwrap_or_default()
        .split_ascii_whitespace()
        .map(str::to_owned)
        .collect()
}

fn write_class_tokens(ctx: &DomCtx, node_id: NodeId, tokens: &[String]) {
    write_attr(ctx, node_id, "class", &tokens.join(" "));
}

fn class_token(value: &JsValue, context: &mut Context) -> JsResult<String> {
    let token = to_rust_string(value, context)?;
    if token.is_empty() || token.chars().any(|ch| ch.is_ascii_whitespace()) {
        return Err(JsNativeError::syntax()
            .with_message("classList token must be non-empty and contain no ASCII whitespace")
            .into());
    }
    Ok(token)
}

fn class_list_length(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    Ok(JsValue::from(
        class_tokens(&ctx, this_node_id(this)?).len() as u32
    ))
}

fn class_list_value(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    Ok(js_str(
        &read_attr(&ctx, this_node_id(this)?, "class").unwrap_or_default(),
    ))
}

fn set_class_list_value(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let value = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?;
    write_attr(&ctx, this_node_id(this)?, "class", &value);
    Ok(JsValue::undefined())
}

fn class_list_item(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let index = args
        .first()
        .unwrap_or(&JsValue::undefined())
        .to_u32(context)? as usize;
    let ctx = dom_ctx(context)?;
    Ok(class_tokens(&ctx, this_node_id(this)?)
        .get(index)
        .map_or_else(JsValue::null, |token| js_str(token)))
}

fn class_list_contains(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let token = class_token(args.first().unwrap_or(&JsValue::undefined()), context)?;
    let ctx = dom_ctx(context)?;
    Ok(JsValue::from(
        class_tokens(&ctx, this_node_id(this)?).contains(&token),
    ))
}

fn class_list_add(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let tokens_to_add = args
        .iter()
        .map(|value| class_token(value, context))
        .collect::<JsResult<Vec<_>>>()?;
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let mut tokens = class_tokens(&ctx, node_id);
    for token in tokens_to_add {
        if !tokens.contains(&token) {
            tokens.push(token);
        }
    }
    write_class_tokens(&ctx, node_id, &tokens);
    Ok(JsValue::undefined())
}

fn class_list_remove(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let tokens_to_remove = args
        .iter()
        .map(|value| class_token(value, context))
        .collect::<JsResult<Vec<_>>>()?;
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let mut tokens = class_tokens(&ctx, node_id);
    tokens.retain(|token| !tokens_to_remove.contains(token));
    write_class_tokens(&ctx, node_id, &tokens);
    Ok(JsValue::undefined())
}

fn class_list_toggle(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let token = class_token(args.first().unwrap_or(&JsValue::undefined()), context)?;
    let force = args.get(1).map(JsValue::to_boolean);
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let mut tokens = class_tokens(&ctx, node_id);
    let present = tokens.contains(&token);
    let retain = force.unwrap_or(!present);
    if retain && !present {
        tokens.push(token);
    } else if !retain && present {
        tokens.retain(|item| item != &token);
    }
    write_class_tokens(&ctx, node_id, &tokens);
    Ok(JsValue::from(retain))
}

fn class_list_replace(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let old = class_token(args.first().unwrap_or(&JsValue::undefined()), context)?;
    let new = class_token(args.get(1).unwrap_or(&JsValue::undefined()), context)?;
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let mut tokens = class_tokens(&ctx, node_id);
    let Some(index) = tokens.iter().position(|token| token == &old) else {
        return Ok(JsValue::from(false));
    };
    if old != new {
        tokens[index] = new;
        let mut seen = std::collections::HashSet::new();
        tokens.retain(|token| seen.insert(token.clone()));
    }
    write_class_tokens(&ctx, node_id, &tokens);
    Ok(JsValue::from(true))
}

fn class_list_to_string(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    class_list_value(this, args, context)
}

fn get_class_list(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    if let Some(class_list) = ctx.state.borrow().class_list_wrappers.get(&node_id) {
        return Ok(class_list.clone().into());
    }

    let class_list = JsObject::from_proto_and_data(
        Some(context.intrinsics().constructors().object().prototype()),
        super::NodeRef { node_id },
    );
    define_accessor(
        &class_list,
        "length",
        Some(class_list_length),
        None,
        context,
    );
    define_accessor(
        &class_list,
        "value",
        Some(class_list_value),
        Some(set_class_list_value),
        context,
    );
    define_method(&class_list, "item", 1, class_list_item, context);
    define_method(&class_list, "contains", 1, class_list_contains, context);
    define_method(&class_list, "add", 1, class_list_add, context);
    define_method(&class_list, "remove", 1, class_list_remove, context);
    define_method(&class_list, "toggle", 1, class_list_toggle, context);
    define_method(&class_list, "replace", 2, class_list_replace, context);
    define_method(&class_list, "toString", 0, class_list_to_string, context);
    ctx.state
        .borrow_mut()
        .class_list_wrappers
        .insert(node_id, class_list.clone());
    Ok(class_list.into())
}

// === Style ===

fn get_style(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let proto = ctx.state.borrow().protos().style.clone();
    super::style::make_style_object(proto, node_id, context)
}

// === innerHTML / outerHTML ===

fn get_template_content(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let is_template = ctx
        .doc
        .borrow()
        .get_node(node_id)
        .and_then(|node| node.element_data())
        .is_some_and(|element| element.name.local == markup5ever::local_name!("template"));

    // Blitz currently stores parsed template children on the template node
    // itself. Expose that node as the content container until blitz-dom grows a
    // distinct DocumentFragment node type.
    Ok(if is_template {
        this.clone()
    } else {
        JsValue::undefined()
    })
}

fn get_inner_html(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let doc = ctx.doc.borrow();
    let mut html = String::new();
    if let Some(node) = doc.get_node(node_id) {
        for child_id in &node.children {
            if let Some(child) = doc.get_node(*child_id) {
                child.write_outer_html(&mut html);
            }
        }
    }
    Ok(js_str(&html))
}

fn set_inner_html(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let html = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?;

    let mut doc = ctx.mutate_doc();
    let mut mutr = doc.mutate();
    // Detach (rather than drop) any existing children so that JS wrappers
    // referencing them remain valid.
    for child_id in mutr.child_ids(node_id) {
        mutr.remove_node(child_id);
    }
    mutr.set_inner_html(node_id, &html);
    Ok(JsValue::undefined())
}

fn get_outer_html(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let doc = ctx.doc.borrow();
    let html = doc
        .get_node(node_id)
        .map(|node| node.outer_html())
        .unwrap_or_default();
    Ok(js_str(&html))
}

// === Focus ===

fn focus(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    ctx.mutate_doc().set_focus_to(node_id);
    Ok(JsValue::undefined())
}

fn blur(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let _ = this_node_id(this)?;
    ctx.mutate_doc().clear_focus();
    Ok(JsValue::undefined())
}

// === Geometry ===

fn get_scroll_left(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let value = ctx
        .doc
        .borrow()
        .get_node(node_id)
        .map(|node| match node.primary_styles() {
            Some(styles) => styles.effective_zoom.unzoom(node.scroll_offset().x as f32) as f64,
            None => node.scroll_offset().x,
        })
        .unwrap_or(0.0);
    Ok(JsValue::from(value))
}

fn set_scroll_left(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    set_scroll_axis(this, args, context, true)
}

fn get_scroll_top(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    // Geometry is only meaningful after layout has caught up with the
    // mutations script already made. See DomCtx::flush_layout.
    ctx.flush_layout();
    let node_id = this_node_id(this)?;
    let value = ctx
        .doc
        .borrow()
        .get_node(node_id)
        .map(|node| match node.primary_styles() {
            Some(styles) => styles.effective_zoom.unzoom(node.scroll_offset().y as f32) as f64,
            None => node.scroll_offset().y,
        })
        .unwrap_or(0.0);
    Ok(JsValue::from(value))
}

fn set_scroll_top(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    set_scroll_axis(this, args, context, false)
}

fn set_scroll_axis(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
    horizontal: bool,
) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    // Flush before clamping. Assigning scrollTop clamps against the element's
    // scrollable height, and after an insertion that height is stale, so the
    // assignment lands short and the viewport jumps to the wrong place. This
    // is the read-modify-write that scroll restoration depends on.
    ctx.flush_layout();
    let node_id = this_node_id(this)?;
    let requested = args
        .first()
        .unwrap_or(&JsValue::undefined())
        .to_number(context)?;
    let target_css = if requested.is_finite() {
        requested.max(0.0)
    } else {
        0.0
    };
    // Not `mutate_doc`: scrolling moves an offset, it does not move layout, and
    // re-dirtying here would throw away the flush this function just paid for
    // and force a full resolve on the next geometry read of every scroll.
    let mut doc = ctx.doc.borrow_mut();
    let target = doc
        .get_node(node_id)
        .and_then(|node| node.primary_styles())
        .map(|styles| f64::from(styles.effective_zoom.zoom(target_css as f32)))
        .unwrap_or(target_css);
    let current = doc
        .get_node(node_id)
        .map(|node| {
            if horizontal {
                node.scroll_offset().x
            } else {
                node.scroll_offset().y
            }
        })
        .unwrap_or(0.0);
    let (delta_x, delta_y) = if horizontal {
        (current - target, 0.0)
    } else {
        (0.0, current - target)
    };
    if doc.scroll_by(Some(node_id), delta_x, delta_y, &mut |_| {}) {
        doc.shell_provider.request_redraw();
    }
    Ok(JsValue::undefined())
}

/// Read one of the box-metric properties, in the units the DOM promises.
///
/// `scrollWidth`, `scrollHeight`, `clientWidth` and `clientHeight` are defined
/// in *unzoomed* CSS pixels, while layout stores the zoomed result. Returning
/// the zoomed number quietly breaks the commonest autosizing idiom there is:
///
///   el.style.height = "auto";
///   el.style.height = `${el.scrollHeight}px`;
///
/// The measurement comes back zoomed, is written into a declaration that Stylo
/// zooms again, and the element grows by the zoom factor on every pass. Under
/// the composer's 1.08 UI scale that is 8% per keystroke: the prompt box drifts
/// away from its own text and pushes the controls down until it hits its
/// max-height. `getBoundingClientRect` is the deliberate exception, and stays
/// zoomed — it reports viewport coordinates, not CSS box metrics.
fn box_metric(
    this: &JsValue,
    context: &mut Context,
    measure: impl Fn(&blitz_dom::Node) -> f32,
) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    // Geometry is only meaningful after layout has caught up with the
    // mutations script already made. See DomCtx::flush_layout.
    ctx.flush_layout();
    let node_id = this_node_id(this)?;
    let doc = ctx.doc.borrow();
    let value = doc
        .get_node(node_id)
        .map(|node| {
            let measured = measure(node);
            match node.primary_styles() {
                Some(styles) => styles.effective_zoom.unzoom(measured),
                None => measured,
            }
        })
        .unwrap_or(0.0);
    Ok(JsValue::from(f64::from(value)))
}

fn get_scroll_width(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    box_metric(this, context, |node| {
        node.final_layout().size.width + node.final_layout().scroll_width()
    })
}

fn get_scroll_height(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    // A text input answers from its own editor, without flushing layout.
    //
    // This one read dominated typing. An autosizing composer measures
    // `scrollHeight` on every keystroke, every geometry read flushes so the
    // answer accounts for pending mutations, and that flush is a full
    // `doc.resolve`: measured at 19.16ms of a 21.55ms keystroke, 89% of the
    // cost of typing a character.
    //
    // It buys nothing here. The height of a text input is the height its parley
    // editor laid out, and `TextInputData::set_text` re-applies the wrap width
    // and refreshes that layout as the text changes, so it is already current.
    // Resolving the document cannot change the answer; it only pays for it.
    //
    // The editor's height alone, not `max(box, editor)`. The spec's floor of
    // the padding box is a ratchet here: an autosizing field writes this number
    // back into its own height, so a measurement that can never report less
    // than the current box means it can never shrink again. Deleting text left
    // the box at its high-water mark.
    //
    // The width the editor wrapped at can go stale, since a window resize
    // changes it, but a resize lays out on its own and re-syncs the editor, so
    // that lasts until the next frame rather than indefinitely.
    // `layout_width` being set is the check that it has been laid out at a real
    // width at least once.
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    {
        let doc = ctx.doc.borrow();
        if let Some(node) = doc.get_node(node_id) {
            let measured = node
                .data
                .downcast_element()
                .and_then(|el| el.text_input_data())
                .filter(|input| input.layout_width.is_some())
                .and_then(|input| input.content_height());
            if let Some(measured) = measured {
                let value = match node.primary_styles() {
                    Some(styles) => styles.effective_zoom.unzoom(measured),
                    None => measured,
                };
                return Ok(JsValue::from(f64::from(value)));
            }
        }
    }

    box_metric(this, context, |node| {
        node.final_layout().size.height + node.final_layout().scroll_height()
    })
}

fn get_client_width(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    box_metric(this, context, |node| node.final_layout().size.width)
}

fn get_client_height(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    box_metric(this, context, |node| node.final_layout().size.height)
}

/// `offsetWidth` / `offsetHeight`: the border box, which is what every control
/// that measures itself wants.
///
/// Absent until now, and absent is worse than wrong here. Reading a missing
/// property yields `undefined`, and `undefined` in arithmetic is `NaN` rather
/// than a throw, so the failure travels silently into whatever the value was
/// for. The app's slider library computes
/// `thumb.offsetWidth / 2 + (track.offsetHeight - thumb.offsetHeight) / 2` to
/// find where the thumb's centre can travel; that was `NaN`, so the usable
/// track length was `NaN` and every drag snapped to `NaN`. The result is a
/// slider that renders and simply ignores the pointer, which is exactly how it
/// was reported.
///
/// `final_layout().size` is the border box, so no padding or border arithmetic
/// is needed. Both are unzoomed by `box_metric` for the same reason the client
/// and scroll metrics are.
fn get_offset_width(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    box_metric(this, context, |node| node.final_layout().size.width)
}

fn get_offset_height(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    box_metric(this, context, |node| node.final_layout().size.height)
}

/// `offsetLeft` / `offsetTop`: the border box's position within the offset
/// parent's padding edge. blitz-dom already computes this for the CSSOM; it
/// was simply never handed to script.
fn get_offset_left(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    box_metric(this, context, |node| node.offset_top_left().x)
}

fn get_offset_top(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    box_metric(this, context, |node| node.offset_top_left().y)
}

fn get_bounding_client_rect(
    this: &JsValue,
    _: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    // Geometry is only meaningful after layout has caught up with the
    // mutations script already made. See DomCtx::flush_layout.
    ctx.flush_layout();
    let node_id = this_node_id(this)?;
    let rect = ctx.doc.borrow().get_client_bounding_rect(node_id);
    let (x, y, width, height) = match rect {
        Some(rect) => (rect.x, rect.y, rect.width, rect.height),
        None => (0.0, 0.0, 0.0, 0.0),
    };
    let object = ObjectInitializer::new(context)
        .property(js_string!("x"), x, PropAttribute::all())
        .property(js_string!("y"), y, PropAttribute::all())
        .property(js_string!("width"), width, PropAttribute::all())
        .property(js_string!("height"), height, PropAttribute::all())
        .property(js_string!("left"), x, PropAttribute::all())
        .property(js_string!("top"), y, PropAttribute::all())
        .property(js_string!("right"), x + width, PropAttribute::all())
        .property(js_string!("bottom"), y + height, PropAttribute::all())
        .build();
    Ok(object.into())
}

// === Scoped selector queries ===

fn is_descendant_of(doc: &blitz_dom::BaseDocument, node_id: NodeId, ancestor_id: NodeId) -> bool {
    let mut current = doc.get_node(node_id).and_then(|node| node.parent);
    while let Some(id) = current {
        if id == ancestor_id {
            return true;
        }
        current = doc.get_node(id).and_then(|node| node.parent);
    }
    false
}

fn query_selector(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let selector = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?;

    let result = {
        let doc = ctx.doc.borrow();
        doc.query_selector_all(&selector).ok().and_then(|matches| {
            matches
                .into_iter()
                .find(|match_id| is_descendant_of(&doc, *match_id, node_id))
        })
    };
    Ok(super::node_or_null(&ctx, result, context))
}

fn query_selector_all(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let selector = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?;

    let matches: Vec<NodeId> = {
        let doc = ctx.doc.borrow();
        doc.query_selector_all(&selector)
            .map(|matches| {
                matches
                    .into_iter()
                    .filter(|match_id| is_descendant_of(&doc, *match_id, node_id))
                    .collect()
            })
            .unwrap_or_default()
    };
    let wrappers: Vec<JsValue> = matches
        .into_iter()
        .map(|match_id| node_wrapper(&ctx, match_id, context).into())
        .collect();
    Ok(boa_engine::object::builtins::JsArray::from_iter(wrappers, context).into())
}

fn matches_selector(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let selector = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?;
    let is_match = ctx
        .doc
        .borrow()
        .query_selector_all(&selector)
        .is_ok_and(|matches| matches.contains(&node_id));
    Ok(JsValue::from(is_match))
}

fn closest(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let ctx = dom_ctx(context)?;
    let node_id = this_node_id(this)?;
    let selector = to_rust_string(args.first().unwrap_or(&JsValue::undefined()), context)?;
    let result = {
        let doc = ctx.doc.borrow();
        let matches = doc.query_selector_all(&selector).unwrap_or_default();
        let mut current = Some(node_id);
        let mut result = None;
        while let Some(id) = current {
            if matches.contains(&id) {
                result = Some(id);
                break;
            }
            current = doc.get_node(id).and_then(|node| node.parent);
        }
        result
    };
    Ok(super::node_or_null(&ctx, result, context))
}