web-api-cat 0.7.5

Bindings between boa-cat (JS engine) and the DOM (html-cat tree) plus fetch (net-cat). v0.7.5 extends the v0.7.4 event system with spec-compliant event flow: `dispatchEvent` decorates the supplied event with `target` / `currentTarget` / `defaultPrevented` plus `preventDefault()` / `stopPropagation()` / `stopImmediatePropagation()` methods. Listeners interact with the dispatch as they would in a real browser without needing a `new Event()` constructor. `dispatchEvent` returns `false` when any listener called `preventDefault`. Seventh sub-crate of a Servo-replacement webview runtime targeting Tauri.
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
//! `EventTarget` mixin (v0.7.4): `addEventListener(type, callback)`,
//! `removeEventListener(type, callback)`, `dispatchEvent(event)`.
//!
//! Per-element state lives under a hidden `__listeners__` Object
//! shaped as `{ <type>: { 0: cb, 1: cb, ..., length: n }, ... }`
//! -- one type-keyed entry per event type, each holding an
//! array-shaped Object of callbacks in registration order.  We
//! create the slot lazily on first `addEventListener` call so
//! elements that never listen carry no extra heap weight.
//!
//! `dispatchEvent(event)` walks the bubble chain via the v0.6.8
//! `__parent__` backref (no separate event-flow infrastructure
//! needed): the target's own listeners fire first, then each
//! ancestor's in order up to the document root or the first
//! null-parent.  `boa_cat::expression::call_function` (made `pub`
//! in boa-cat 0.7.1) dispatches each callback with `this = level`
//! and `args = [event]`.  Listener throws are intentionally
//! swallowed at the dispatch boundary -- per the DOM spec, a
//! listener's exception is reported to the console but does NOT
//! abort the remaining listeners or the bubble chain.
//!
//! v0 limitations:
//!
//! - No capture phase (bubble only).  `addEventListener(_, _,
//!   true)` ignores the capture flag.
//! - No `Event` constructor; scripts pass plain `{ type: 'foo' }`
//!   objects.  v0.7.5 augments the supplied event with
//!   `target` / `currentTarget` / `defaultPrevented` /
//!   `preventDefault` / `stopPropagation` /
//!   `stopImmediatePropagation`, so scripts written against the
//!   spec's Event API work without needing the constructor.  A
//!   future chunk can add `new Event(type)` once the engine grows
//!   `NewExpression` dispatch on `NativeFn` constructors.
//! - No `once` / `passive` / `signal` listener options.

use std::collections::BTreeMap;

use boa_cat::Value;
use boa_cat::fuel::Fuel;
use boa_cat::heap::Heap;
use boa_cat::outcome::{EvalResult, Outcome};
use boa_cat::value::{Object, ObjectId};

/// Hidden property key under which an element's listener map
/// lives once it has any registered listeners.
pub const LISTENERS_KEY: &str = "__listeners__";

/// `EventTarget.addEventListener(type, callback)` (v0.7.4): append
/// `callback` to the listener queue for `type` on `this`.  Lazy:
/// creates the `__listeners__` Object and the per-type array on
/// first use.  Duplicate `(type, callback)` pairs ARE inserted
/// (matches the spec only when the second arg differs by
/// reference; we keep all dupes for simplicity).  Third
/// `options` / `useCapture` arg is currently ignored.
///
/// # Errors
///
/// Never returns `Err`; bad inputs no-op.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn add_event_listener_impl(
    args: Vec<Value>,
    this: Value,
    heap: Heap,
    fuel: Fuel,
) -> EvalResult {
    let event_type = string_arg(&args, 0);
    let callback = args.get(1).cloned().unwrap_or(Value::Undefined);
    let new_heap = append_listener(&this, &event_type, callback, heap);
    Ok((Outcome::Normal(Value::Undefined), new_heap, fuel))
}

/// `EventTarget.removeEventListener(type, callback)` (v0.7.4):
/// drop every queue entry whose Value equals `callback` (via
/// `Value::PartialEq` -- `Value::Function(id)` equality is by
/// `FunctionId`; `Value::Native(fn_ptr)` equality is by function
/// pointer).  No-op when no matching entry exists.
///
/// # Errors
///
/// Never returns `Err`; bad inputs no-op.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn remove_event_listener_impl(
    args: Vec<Value>,
    this: Value,
    heap: Heap,
    fuel: Fuel,
) -> EvalResult {
    let event_type = string_arg(&args, 0);
    let callback = args.get(1).cloned().unwrap_or(Value::Undefined);
    let new_heap = drop_listener(&this, &event_type, &callback, heap);
    Ok((Outcome::Normal(Value::Undefined), new_heap, fuel))
}

/// `EventTarget.dispatchEvent(event)` (v0.7.4, extended v0.7.5):
/// walk the bubble chain (target then ancestors via
/// `__parent__`) and invoke every listener registered for
/// `event.type` at each level.  v0.7.5 decorates the supplied
/// event with `target` / `currentTarget` / `defaultPrevented`
/// (initially `false`) and `preventDefault` /
/// `stopPropagation` / `stopImmediatePropagation` methods so
/// listeners can interact with the dispatch in spec-compliant
/// shape.  `currentTarget` updates per bubble level;
/// `stopPropagation` halts the bubble after the current level
/// finishes; `stopImmediatePropagation` halts both remaining
/// listeners at the current level AND the bubble; `preventDefault`
/// sets `defaultPrevented = true` and makes this fn return
/// `false`.  Listener throws are swallowed per DOM dispatch
/// semantics (report-and-continue).
///
/// # Errors
///
/// Returns `Err` only when an underlying `call_function`
/// invocation hits a non-throw engine error (e.g. fuel
/// exhaustion).
#[allow(clippy::needless_pass_by_value)]
pub fn dispatch_event_impl(args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let event = args.first().cloned().unwrap_or(Value::Undefined);
    let Some(target_id) = object_id_of(&this) else {
        return Ok((Outcome::Normal(Value::Boolean(true)), heap, fuel));
    };
    let (decorated, heap) = decorate_event(&event, target_id, heap);
    let event_type = read_event_type(&decorated, &heap);
    let chain = build_bubble_chain(&this, &heap);
    let (heap, fuel) = chain.iter().try_fold(
        (heap, fuel),
        |(heap, fuel), level| -> Result<_, boa_cat::Error> {
            if read_bool_flag(&decorated, PROPAGATION_STOPPED_KEY, &heap)
                || read_bool_flag(&decorated, IMMEDIATE_STOPPED_KEY, &heap)
            {
                Ok((heap, fuel))
            } else {
                let heap = if let Some(id) = object_id_of(level) {
                    set_current_target(&decorated, id, heap)
                } else {
                    heap
                };
                invoke_level_listeners(level, &decorated, &event_type, heap, fuel)
            }
        },
    )?;
    let default_prevented = read_bool_flag(&decorated, DEFAULT_PREVENTED_KEY, &heap);
    Ok((
        Outcome::Normal(Value::Boolean(!default_prevented)),
        heap,
        fuel,
    ))
}

/// Property key under which the `event.defaultPrevented` flag
/// lives once dispatchEvent has decorated the event.
pub const DEFAULT_PREVENTED_KEY: &str = "defaultPrevented";

const PROPAGATION_STOPPED_KEY: &str = "__propagation_stopped__";
const IMMEDIATE_STOPPED_KEY: &str = "__immediate_propagation_stopped__";

/// v0.7.5 `event.preventDefault()` impl: set
/// `this.defaultPrevented = true`.  No-op if `this` isn't an
/// Object.  Idempotent.
///
/// # Errors
///
/// Never returns `Err`.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn prevent_default_impl(_args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let new_heap = set_bool_flag(&this, DEFAULT_PREVENTED_KEY, heap);
    Ok((Outcome::Normal(Value::Undefined), new_heap, fuel))
}

/// v0.7.5 `event.stopPropagation()` impl: set the hidden
/// propagation-stopped flag so the bubble walk halts after the
/// current level finishes.  Remaining listeners at the current
/// level still fire (see `stopImmediatePropagation` for the
/// stricter variant).
///
/// # Errors
///
/// Never returns `Err`.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn stop_propagation_impl(_args: Vec<Value>, this: Value, heap: Heap, fuel: Fuel) -> EvalResult {
    let new_heap = set_bool_flag(&this, PROPAGATION_STOPPED_KEY, heap);
    Ok((Outcome::Normal(Value::Undefined), new_heap, fuel))
}

/// v0.7.5 `event.stopImmediatePropagation()` impl: set both the
/// propagation-stopped flag AND the immediate-stopped flag so
/// remaining listeners at the current level are skipped in
/// addition to the bubble halt.
///
/// # Errors
///
/// Never returns `Err`.
#[allow(clippy::needless_pass_by_value, clippy::unnecessary_wraps)]
pub fn stop_immediate_propagation_impl(
    _args: Vec<Value>,
    this: Value,
    heap: Heap,
    fuel: Fuel,
) -> EvalResult {
    let heap = set_bool_flag(&this, PROPAGATION_STOPPED_KEY, heap);
    let heap = set_bool_flag(&this, IMMEDIATE_STOPPED_KEY, heap);
    Ok((Outcome::Normal(Value::Undefined), heap, fuel))
}

fn decorate_event(event: &Value, target_id: ObjectId, heap: Heap) -> (Value, Heap) {
    let user_props: BTreeMap<String, Value> = object_id_of(event)
        .and_then(|id| heap.object(id))
        .map(|obj| {
            obj.properties()
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect()
        })
        .unwrap_or_default();
    let decoration = [
        ("target".to_owned(), Value::Object(target_id)),
        ("currentTarget".to_owned(), Value::Object(target_id)),
        (DEFAULT_PREVENTED_KEY.to_owned(), Value::Boolean(false)),
        (PROPAGATION_STOPPED_KEY.to_owned(), Value::Boolean(false)),
        (IMMEDIATE_STOPPED_KEY.to_owned(), Value::Boolean(false)),
        (
            "preventDefault".to_owned(),
            Value::Native(prevent_default_impl),
        ),
        (
            "stopPropagation".to_owned(),
            Value::Native(stop_propagation_impl),
        ),
        (
            "stopImmediatePropagation".to_owned(),
            Value::Native(stop_immediate_propagation_impl),
        ),
    ];
    let combined: BTreeMap<String, Value> = user_props.into_iter().chain(decoration).collect();
    let (id, heap) = heap.alloc_object(Object::from_properties(combined));
    (Value::Object(id), heap)
}

fn set_current_target(event: &Value, level_id: ObjectId, heap: Heap) -> Heap {
    let Some(event_id) = object_id_of(event) else {
        return heap;
    };
    let Some(obj) = heap.object(event_id).cloned() else {
        return heap;
    };
    let updated = obj.with("currentTarget".to_owned(), Value::Object(level_id));
    heap.store_object(event_id, updated).unwrap_or_else(|h| h)
}

fn set_bool_flag(this: &Value, key: &str, heap: Heap) -> Heap {
    let Some(id) = object_id_of(this) else {
        return heap;
    };
    let Some(obj) = heap.object(id).cloned() else {
        return heap;
    };
    let updated = obj.with(key.to_owned(), Value::Boolean(true));
    heap.store_object(id, updated).unwrap_or_else(|h| h)
}

fn read_bool_flag(value: &Value, key: &str, heap: &Heap) -> bool {
    object_id_of(value)
        .and_then(|id| heap.object(id))
        .and_then(|obj| obj.get(key))
        .and_then(|v| match v {
            Value::Boolean(b) => Some(*b),
            Value::Undefined
            | Value::Null
            | Value::Number(_)
            | Value::String(_)
            | Value::Object(_)
            | Value::Function(_)
            | Value::Native(_)
            | Value::Promise(_) => None,
        })
        .unwrap_or(false)
}

fn append_listener(this: &Value, event_type: &str, callback: Value, heap: Heap) -> Heap {
    let Some(element_id) = object_id_of(this) else {
        return heap;
    };
    let Some(element) = heap.object(element_id).cloned() else {
        return heap;
    };
    let (listeners_id, heap) = resolve_or_create_listeners_map(element_id, &element, heap);
    let Some(listeners) = heap.object(listeners_id).cloned() else {
        return heap;
    };
    let (array_id, heap) = resolve_or_create_type_array(listeners_id, &listeners, event_type, heap);
    let Some(array) = heap.object(array_id).cloned() else {
        return heap;
    };
    let length = array_length(&array);
    let updated = array
        .with(format!("{length}"), callback)
        .with("length".to_owned(), Value::Number(f64::from(length + 1)));
    heap.store_object(array_id, updated).unwrap_or_else(|h| h)
}

fn drop_listener(this: &Value, event_type: &str, callback: &Value, heap: Heap) -> Heap {
    let Some(element_id) = object_id_of(this) else {
        return heap;
    };
    let Some(element) = heap.object(element_id) else {
        return heap;
    };
    let Some(listeners_id) = element.get(LISTENERS_KEY).and_then(object_id_from_value) else {
        return heap;
    };
    let Some(listeners) = heap.object(listeners_id) else {
        return heap;
    };
    let Some(array_id) = listeners.get(event_type).and_then(object_id_from_value) else {
        return heap;
    };
    let Some(array) = heap.object(array_id).cloned() else {
        return heap;
    };
    let length = array_length(&array);
    let remaining: Vec<Value> = (0..length)
        .filter_map(|i| array.get(&format!("{i}")).cloned())
        .filter(|v| v != callback)
        .collect();
    let new_length = u32::try_from(remaining.len()).unwrap_or(u32::MAX);
    let pairs: BTreeMap<String, Value> = remaining
        .into_iter()
        .enumerate()
        .map(|(i, v)| (format!("{i}"), v))
        .chain(std::iter::once((
            "length".to_owned(),
            Value::Number(f64::from(new_length)),
        )))
        .collect();
    heap.store_object(array_id, Object::from_properties(pairs))
        .unwrap_or_else(|h| h)
}

fn invoke_level_listeners(
    level: &Value,
    event: &Value,
    event_type: &str,
    heap: Heap,
    fuel: Fuel,
) -> Result<(Heap, Fuel), boa_cat::Error> {
    let listeners = collect_listeners(level, event_type, &heap);
    listeners
        .into_iter()
        .try_fold((heap, fuel), |(heap, fuel), callback| {
            if read_bool_flag(event, IMMEDIATE_STOPPED_KEY, &heap) {
                Ok((heap, fuel))
            } else {
                let (_outcome, heap, fuel) = boa_cat::expression::call_function(
                    &callback,
                    level,
                    vec![event.clone()],
                    heap,
                    fuel,
                )?;
                Ok((heap, fuel))
            }
        })
}

fn collect_listeners(level: &Value, event_type: &str, heap: &Heap) -> Vec<Value> {
    let Some(element_id) = object_id_of(level) else {
        return Vec::new();
    };
    let Some(element) = heap.object(element_id) else {
        return Vec::new();
    };
    let Some(listeners_id) = element.get(LISTENERS_KEY).and_then(object_id_from_value) else {
        return Vec::new();
    };
    let Some(listeners) = heap.object(listeners_id) else {
        return Vec::new();
    };
    let Some(array_id) = listeners.get(event_type).and_then(object_id_from_value) else {
        return Vec::new();
    };
    let Some(array) = heap.object(array_id) else {
        return Vec::new();
    };
    let length = array_length(array);
    (0..length)
        .filter_map(|i| array.get(&format!("{i}")).cloned())
        .collect()
}

fn build_bubble_chain(target: &Value, heap: &Heap) -> Vec<Value> {
    std::iter::successors(Some(target.clone()), |current| read_parent(current, heap)).collect()
}

fn read_parent(value: &Value, heap: &Heap) -> Option<Value> {
    let id = object_id_of(value)?;
    let obj = heap.object(id)?;
    obj.get("__parent__").and_then(|v| match v {
        Value::Object(_) => Some(v.clone()),
        Value::Undefined
        | Value::Null
        | Value::Boolean(_)
        | Value::Number(_)
        | Value::String(_)
        | Value::Function(_)
        | Value::Native(_)
        | Value::Promise(_) => None,
    })
}

fn resolve_or_create_listeners_map(
    element_id: ObjectId,
    element: &Object,
    heap: Heap,
) -> (ObjectId, Heap) {
    if let Some(id) = element.get(LISTENERS_KEY).and_then(object_id_from_value) {
        (id, heap)
    } else {
        let (id, heap) = heap.alloc_object(Object::from_properties(BTreeMap::new()));
        let updated = element
            .clone()
            .with(LISTENERS_KEY.to_owned(), Value::Object(id));
        let heap = heap.store_object(element_id, updated).unwrap_or_else(|h| h);
        (id, heap)
    }
}

fn resolve_or_create_type_array(
    listeners_id: ObjectId,
    listeners: &Object,
    event_type: &str,
    heap: Heap,
) -> (ObjectId, Heap) {
    if let Some(id) = listeners.get(event_type).and_then(object_id_from_value) {
        (id, heap)
    } else {
        let empty = Object::from_properties(
            std::iter::once(("length".to_owned(), Value::Number(0.0))).collect(),
        );
        let (id, heap) = heap.alloc_object(empty);
        let updated = listeners
            .clone()
            .with(event_type.to_owned(), Value::Object(id));
        let heap = heap
            .store_object(listeners_id, updated)
            .unwrap_or_else(|h| h);
        (id, heap)
    }
}

fn read_event_type(event: &Value, heap: &Heap) -> String {
    object_id_of(event)
        .and_then(|id| heap.object(id))
        .and_then(|obj| obj.get("type").cloned())
        .and_then(|v| match v {
            Value::String(s) => Some(s),
            Value::Undefined
            | Value::Null
            | Value::Boolean(_)
            | Value::Number(_)
            | Value::Object(_)
            | Value::Function(_)
            | Value::Native(_)
            | Value::Promise(_) => None,
        })
        .unwrap_or_default()
}

fn array_length(array: &Object) -> u32 {
    match array.get("length") {
        Some(Value::Number(n)) if n.is_finite() && *n >= 0.0 => {
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            let length = *n as u32;
            length
        }
        Some(_) | None => 0,
    }
}

fn object_id_of(value: &Value) -> Option<ObjectId> {
    object_id_from_value(value)
}

fn object_id_from_value(value: &Value) -> Option<ObjectId> {
    match value {
        Value::Object(id) => Some(*id),
        Value::Undefined
        | Value::Null
        | Value::Boolean(_)
        | Value::Number(_)
        | Value::String(_)
        | Value::Function(_)
        | Value::Native(_)
        | Value::Promise(_) => None,
    }
}

fn string_arg(args: &[Value], idx: usize) -> String {
    match args.get(idx) {
        Some(Value::String(s)) => s.clone(),
        Some(Value::Number(n)) => format!("{n}"),
        Some(Value::Boolean(b)) => format!("{b}"),
        Some(Value::Null) => "null".to_owned(),
        Some(Value::Undefined) | None => String::new(),
        Some(Value::Object(_) | Value::Function(_) | Value::Native(_) | Value::Promise(_)) => {
            "[object]".to_owned()
        }
    }
}