Files
Browser/engine/src/script_boa.rs
T
Carlo Baratto 6a14853d0d Promise vere e await: la coda dei microtask viene svuotata
Il difetto: Boa le Promise le ha, ma nessuno chiamava run_jobs(), quindi ogni
.then restava in coda per sempre e la pagina non si aggiornava — senza un solo
errore da leggere.

- fetch restituisce una Promise costruita dal motore (new Promise + resolve/reject
  tenuti nella richiesta), non più un oggetto con un then finto
- text() e json() restituiscono Promise anche loro, come nel browser: senza,
  "await r.text()" riceveva la stringa e chi si aspettava una Promise si rompeva
- run_jobs() dopo ogni ingresso di JavaScript: script, eventi, timer, consegna
  delle risposte di fetch
- il guscio desktop serve le fetch anche nel percorso senza finestra: con
  --aspetta l'attesa non serviva a niente e la pagina restava sulla scritta iniziale
- 7 test nuovi (tests/promise.rs): then, await, fetch+text, fetch+json, catch,
  Promise.all, Promise accesa dentro un gestore di clic
- aggiornato il test che si aspettava r.text() sincrona: codificava la vecchia
  semplificazione, non il comportamento giusto

Verifica end-to-end su HTTP vero: una pagina con await fetch e await r.json()
mostra "ricevuto: Mosaic (200)". Wikipedia, che usa async/await ovunque, si carica
senza panic.
2026-11-13 09:01:35 +01:00

2255 lines
86 KiB
Rust

//! Esecuzione degli `<script>` inline con Boa (milestone M2.5 e M2.5b).
//!
//! Ambito: script inline eseguiti in ordine **prima** dello stile e del layout, e
//! un sottoinsieme di DOM API che resta usabile dopo, sugli eventi:
//!
//! - `document.getElementById`
//! - `textContent`, `innerHTML` in lettura e scrittura
//! - `setAttribute`, `getAttribute`, `removeAttribute`, `className`
//! - `element.style`, sia `style.color = 'red'` sia `style.setProperty(...)`
//! - `classList.add/remove/toggle/contains`
//! - `addEventListener('click', ...)`, con l'evento consegnato dal motore
//!
//! Fuori ambito, dichiarato: altri tipi di evento (`input`, `submit`, `keydown`),
//! cattura e `stopPropagation`, `createElement`/`appendChild`, timer, `fetch`.
//! Una funzione assente restituisce `null` o non fa nulla; gli errori degli script
//! tornano al chiamante, non restano nascosti.
//!
//! Il documento non è esposto all'interprete: gli script vedono uno snapshot
//! (indice del nodo, testo corrente, attributi) e le scritture vengono accodate e
//! applicate al DOM dal motore. Così non si condivide memoria con Boa.
use std::cell::RefCell;
use std::collections::HashMap;
use boa_engine::{js_string, Context, JsResult, JsValue, NativeFunction, Source};
use crate::dom::{Document, Node, NodeKind};
/// Scrittura richiesta da uno script, applicata al DOM dal motore.
#[derive(Debug, Clone)]
enum Op {
Testo(usize, String),
Attributo(usize, String, String),
TogliAttributo(usize, String),
Stile(usize, String, String),
Classe(usize, String, bool),
/// nodo nuovo creato da script: `usize` è l'indice sintetico
NuovoElemento(usize, String),
NuovoTesto(usize, String),
/// (padre, figlio), con indici sintetici o reali
Append(usize, usize),
RemoveChild(usize, usize),
/// inserimento prima di un riferimento (-1 = in fondo)
InsertBefore(usize, usize, i64),
/// il nodo si stacca dal padre
TogliSe(usize),
/// scrittura del valore di un campo dal codice
Valore(usize, String),
/// `innerHTML = ...`: il testo va analizzato come HTML
Html(usize, String),
/// `insertAdjacentHTML(dove, html)`
HtmlAccanto(usize, String, String),
}
#[derive(Default)]
struct Stato {
/// identificatore → nodo
id: HashMap<String, usize>,
/// testo corrente per nodo
testi: HashMap<usize, String>,
/// attributi per nodo (nomi in minuscolo)
attributi: HashMap<usize, HashMap<String, String>>,
/// testo dell'attributo `style`
stili_inline: HashMap<usize, String>,
/// testo dell'attributo `class`
classi: HashMap<usize, String>,
/// nome del tag per nodo
tag: HashMap<usize, String>,
/// padre di ogni nodo
padre: HashMap<usize, usize>,
/// figli di ogni nodo, in ordine
figli: HashMap<usize, Vec<usize>>,
/// messaggi di `console.log`
log: Vec<String>,
/// scritture richieste dagli script, applicate alla fine
ops: Vec<Op>,
/// tag dei nodi creati da script, per indice sintetico
nuovi: Vec<String>,
/// nodo `<body>`, se c'è
corpo: Option<usize>,
}
thread_local! {
static STATO: RefCell<Stato> = RefCell::new(Stato::default());
/// valori correnti dei campi, per nodo: li fornisce il guscio prima di
/// consegnare un evento, così lo script può leggere cosa è stato digitato
static VALORI: RefCell<std::collections::HashMap<usize, String>> =
RefCell::new(std::collections::HashMap::new());
/// orologio del guscio, in millisecondi: il motore non legge mai l'ora vera
static OROLOGIO: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// valori che gli script hanno scritto nei campi (`campo.value = ...`)
static SCRITTI: RefCell<Vec<(usize, String)>> = const { RefCell::new(Vec::new()) };
}
/// Preludio: oggetti elemento stabili (stessa identità a ogni `getElementById`),
/// registro degli ascoltatori e consegna degli eventi.
const PRELUDIO: &str = r#"
var __elementi = {};
var __ascoltatori = [];
/* vero se un gestore ha chiamato preventDefault: il motore lo legge per sapere
se deve fare l'azione predefinita (per ora: l'invio del formulario) */
var __preventuto = false;
/* vero se un gestore ha fermato la propagazione */
var __ferma = false;
/* Timer: la coda vive qui, ma il tempo lo fornisce il motore (che a sua volta lo
riceve dal guscio). Così il motore non legge mai l'orologio e i test possono
usare un tempo finto, restando riproducibili. */
var __timers = [];
var __prossimo_timer = 1;
function __timer_aggiungi(fn, ms, ripeti) {
if (typeof fn !== 'function') { return 0; }
var attesa = Number(ms);
if (!isFinite(attesa) || attesa < 0) { attesa = 0; }
var id = __prossimo_timer++;
__timers.push({
id: id,
fn: fn,
quando: __adesso() + attesa,
ogni: ripeti ? Math.max(1, attesa) : 0,
ripeti: !!ripeti
});
return id;
}
function __timer_togli(id) {
for (var i = 0; i < __timers.length; i++) {
if (__timers[i].id === Number(id)) { __timers.splice(i, 1); return; }
}
}
function setTimeout(fn, ms) { return __timer_aggiungi(fn, ms, false); }
function setInterval(fn, ms) { return __timer_aggiungi(fn, ms, true); }
function clearTimeout(id) { __timer_togli(id); }
function clearInterval(id) { __timer_togli(id); }
/* Esegue i timer scaduti entro `adesso`, al massimo `limite` per non restare
prigionieri di un ciclo infinito scritto male. */
function __timer_pompa(adesso, limite) {
var eseguiti = 0;
for (var giro = 0; giro < limite; giro++) {
var scelto = -1;
var minore = null;
for (var i = 0; i < __timers.length; i++) {
var t = __timers[i];
if (t.quando <= adesso && (minore === null || t.quando < minore)) {
minore = t.quando;
scelto = i;
}
}
if (scelto < 0) { break; }
var timer = __timers[scelto];
if (timer.ripeti) {
timer.quando = Math.max(timer.quando + timer.ogni, adesso + 1);
} else {
__timers.splice(scelto, 1);
}
try { timer.fn(); } catch (e) { __log('errore in un timer: ' + e); }
eseguiti++;
}
return eseguiti;
}
/* Prima scadenza futura, in millisecondi; -1 se non c'è nulla in coda. */
function __timer_prossimo() {
var minimo = -1;
for (var i = 0; i < __timers.length; i++) {
if (minimo < 0 || __timers[i].quando < minimo) { minimo = __timers[i].quando; }
}
return minimo;
}
/* fetch: la richiesta si accoda, la esegue il guscio (che sa fare rete) e la
risposta torna qui con __risposta(). È una Promise vera, costruita dal
costruttore del motore: `then`, `catch`, `await` e `Promise.all` funzionano,
purché la coda dei microtask venga svuotata dopo ogni evento — lo fa la parte
Rust con `run_jobs`. `text()` e `json()` restituiscono Promise anche loro, come
nel browser: senza, `await r.text()` darebbe la stringa e non una Promise. */
var __richieste = [];
var __prossima_richiesta = 1;
function fetch(url, opzioni) {
var id = __prossima_richiesta++;
var opz = opzioni || {};
var richiesta = {
id: id,
url: String(url),
metodo: opz.method ? String(opz.method).toUpperCase() : 'GET',
corpo: (opz.body === undefined || opz.body === null) ? null : String(opz.body)
};
__richieste.push(richiesta);
return new Promise(function (resolve, reject) {
richiesta.resolve = resolve;
richiesta.reject = reject;
});
}
function __richieste_pendenti() {
var out = [];
for (var i = 0; i < __richieste.length; i++) {
var r = __richieste[i];
out.push({ id: r.id, url: r.url, metodo: r.metodo, corpo: r.corpo });
}
return JSON.stringify(out);
}
function __risposta(id, stato, corpo) {
var i = -1;
for (var k = 0; k < __richieste.length; k++) {
if (__richieste[k].id === Number(id)) { i = k; break; }
}
if (i < 0) { return 0; }
var r = __richieste[i];
__richieste.splice(i, 1);
if (stato < 0) {
if (r.reject) { r.reject(new Error('richiesta fallita')); }
return 1;
}
var risposta = {
ok: stato >= 200 && stato < 300,
status: stato,
url: r.url,
headers: { get: function () { return null; }, has: function () { return false; } },
text: function () { return Promise.resolve(corpo); },
json: function () {
return Promise.resolve(corpo).then(function (t) { return JSON.parse(t); });
}
};
if (r.resolve) { r.resolve(risposta); }
return 1;
}
var console = {
log: function () {
var pezzi = [];
for (var i = 0; i < arguments.length; i++) { pezzi.push(String(arguments[i])); }
__log(pezzi.join(' '));
}
};
function __elenco(testo) {
if (!testo) { return []; }
var parti = testo.split(',');
var out = [];
for (var i = 0; i < parti.length; i++) {
if (parti[i] !== '') { out.push(Number(parti[i])); }
}
return out;
}
function __wrap(n) {
if (__elementi[n]) { return __elementi[n]; }
var stile = new Proxy({}, {
get: function (_, p) { return __stile_leggi(n, String(p)); },
set: function (_, p, v) { __stile(n, String(p), String(v)); return true; }
});
var classi = {
add: function (c) { __classe(n, String(c), true); },
remove: function (c) { __classe(n, String(c), false); },
contains: function (c) { return __classe_ha(n, String(c)); },
toggle: function (c) {
if (__classe_ha(n, String(c))) { __classe(n, String(c), false); return false; }
__classe(n, String(c), true);
return true;
}
};
var el = {
nodeIndex: n,
get parentNode() {
var p = __padre(n);
return p < 0 ? null : __wrap(p);
},
get children() {
var indici = __elenco(__figli(n));
var out = [];
for (var i = 0; i < indici.length; i++) { out.push(__wrap(indici[i])); }
return out;
},
get firstChild() {
var indici = __elenco(__figli(n));
return indici.length === 0 ? null : __wrap(indici[0]);
},
get nextSibling() {
var f = __fratello(n);
return f < 0 ? null : __wrap(f);
},
get textContent() { return __leggi(n); },
set textContent(v) { __scrivi(n, String(v)); },
get innerHTML() { return __leggi(n); },
set innerHTML(v) { __html(n, String(v)); },
get value() { return __valore(n); },
set value(v) { __imposta_valore(n, String(v)); },
setAttribute: function (k, v) { __attributo(n, String(k), String(v)); },
getAttribute: function (k) {
var v = __attr_leggi(n, String(k));
return v === null ? null : v;
},
removeAttribute: function (k) { __attr_togli(n, String(k)); },
hasAttribute: function (k) { return __attr_leggi(n, String(k)) !== null; },
addEventListener: function (tipo, fn) {
if (typeof fn === 'function') {
__ascoltatori.push({ nodo: n, tipo: String(tipo), fn: fn });
}
},
removeEventListener: function () {},
appendChild: function (figlio) {
if (!figlio) { return null; }
__append(n, figlio.nodeIndex);
return figlio;
},
insertBefore: function (nuovo, riferimento) {
if (!nuovo) { return null; }
__insert_before(n, nuovo.nodeIndex, riferimento ? riferimento.nodeIndex : -1);
return nuovo;
},
removeChild: function (figlio) {
if (!figlio) { return null; }
__rimuovi(n, figlio.nodeIndex);
return figlio;
},
remove: function () { __togli_se(n); },
insertAdjacentHTML: function (dove, html) { __html_accanto(n, String(dove), String(html)); },
get dataset() {
try { return JSON.parse(__dati(n)); } catch (e) { return {}; }
},
querySelector: function (s) {
var trovato = __selettore_uno(n, String(s));
return trovato < 0 ? null : __wrap(trovato);
},
querySelectorAll: function (s) {
var indici = __elenco(__selettori(n, String(s)));
var out = [];
for (var i = 0; i < indici.length; i++) { out.push(__wrap(indici[i])); }
return out;
},
style: stile,
classList: classi,
get className() { return __attr_leggi(n, 'class') || ''; },
set className(v) { __attributo(n, 'class', String(v)); }
};
__elementi[n] = el;
return el;
}
var document = {
getElementById: function (id) {
var n = __find(String(id));
return n < 0 ? null : __wrap(n);
},
createElement: function (tag) { return __wrap(__nuovo(String(tag))); },
createTextNode: function (testo) { return __wrap(__nuovo_testo(String(testo))); },
querySelector: function (s) {
var n = __selettore_uno(-1, String(s));
return n < 0 ? null : __wrap(n);
},
querySelectorAll: function (s) {
var indici = __elenco(__selettori(-1, String(s)));
var out = [];
for (var i = 0; i < indici.length; i++) { out.push(__wrap(indici[i])); }
return out;
},
addEventListener: function () {},
get body() { return __corpo() < 0 ? null : __wrap(__corpo()); }
};
/* Il motore azzera i flag una volta per evento: se lo facesse `__dispatch`,
la propagazione al secondo nodo cancellerebbe il preventDefault del primo. */
function __azzera_preventuto() { __preventuto = false; __ferma = false; }
/* Consegna l'evento agli ascoltatori registrati e all'eventuale attributo
inline (`onclick="..."`). Restituisce quanti gestori sono stati eseguiti. */
function __dispatch(n, tipo, x, y, tasto) {
var quanti = 0;
var el = __wrap(n);
var ev = {
type: tipo,
target: el,
currentTarget: el,
clientX: x,
clientY: y,
key: (typeof tasto === 'string') ? tasto : '',
keyCode: (typeof tasto === 'string' && tasto.length === 1) ? tasto.charCodeAt(0) : 0,
defaultPrevented: false,
preventDefault: function () { this.defaultPrevented = true; __preventuto = true; },
stopPropagation: function () { __ferma = true; }
};
var inline = __inline(n, tipo);
if (inline !== null && inline !== '') {
try {
(new Function('event', inline)).call(el, ev);
quanti++;
} catch (e) {
__log('errore in on' + tipo + ': ' + e);
}
}
for (var i = 0; i < __ascoltatori.length; i++) {
var a = __ascoltatori[i];
if (a.tipo !== tipo || a.nodo !== n) { continue; }
a.fn.call(el, ev);
quanti++;
}
return quanti;
}
"#;
fn argomento_stringa(args: &[JsValue], ctx: &mut Context, i: usize) -> String {
args.get(i)
.and_then(|v| v.to_string(ctx).ok())
.map(|s| s.to_std_string_escaped())
.unwrap_or_default()
}
fn argomento_nodo(args: &[JsValue], ctx: &mut Context, i: usize) -> usize {
args.get(i)
.and_then(|v| v.to_number(ctx).ok())
.unwrap_or(0.0) as usize
}
/// `__find(id)`: indice del nodo con quell'id, oppure -1.
fn trova(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let id = argomento_stringa(args, ctx, 0);
let indice = STATO.with(|s| s.borrow().id.get(&id).map(|v| *v as i64).unwrap_or(-1));
Ok(JsValue::from(indice))
}
/// `__leggi(nodo)`: testo corrente dell'elemento.
fn leggi(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let testo = STATO.with(|s| s.borrow().testi.get(&nodo).cloned().unwrap_or_default());
Ok(JsValue::from(js_string!(testo.as_str())))
}
/// `__scrivi(nodo, testo)`: accoda il nuovo testo.
fn scrivi(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let testo = argomento_stringa(args, ctx, 1);
STATO.with(|s| s.borrow_mut().ops.push(Op::Testo(nodo, testo)));
Ok(JsValue::undefined())
}
/// `__attributo(nodo, nome, valore)`.
fn attributo(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let nome = argomento_stringa(args, ctx, 1);
let valore = argomento_stringa(args, ctx, 2);
STATO.with(|s| s.borrow_mut().ops.push(Op::Attributo(nodo, nome, valore)));
Ok(JsValue::undefined())
}
/// `__attr_togli(nodo, nome)`.
fn attr_togli(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let nome = argomento_stringa(args, ctx, 1);
STATO.with(|s| s.borrow_mut().ops.push(Op::TogliAttributo(nodo, nome)));
Ok(JsValue::undefined())
}
/// `__attr_leggi(nodo, nome)`: valore dell'attributo, oppure null.
fn attr_leggi(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let nome = argomento_stringa(args, ctx, 1).to_ascii_lowercase();
let valore = STATO.with(|s| {
s.borrow()
.attributi
.get(&nodo)
.and_then(|m| m.get(&nome).cloned())
});
Ok(match valore {
Some(v) => JsValue::from(js_string!(v.as_str())),
None => JsValue::null(),
})
}
/// `__stile(nodo, proprietà, valore)`: nome JS → nome CSS (`backgroundColor`).
fn stile(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let prop = kebab(&argomento_stringa(args, ctx, 1));
let valore = argomento_stringa(args, ctx, 2);
STATO.with(|s| s.borrow_mut().ops.push(Op::Stile(nodo, prop, valore)));
Ok(JsValue::undefined())
}
/// `__stile_leggi(nodo, proprietà)`: valore dichiarato inline, o stringa vuota.
fn stile_leggi(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let prop = kebab(&argomento_stringa(args, ctx, 1));
let valore = STATO.with(|s| {
let stato = s.borrow();
let inline = stato.stili_inline.get(&nodo).cloned().unwrap_or_default();
inline
.split(';')
.filter_map(|d| d.split_once(':'))
.find(|(k, _)| k.trim().eq_ignore_ascii_case(&prop))
.map(|(_, v)| v.trim().to_string())
.unwrap_or_default()
});
Ok(JsValue::from(js_string!(valore.as_str())))
}
/// `__classe(nodo, nome, aggiungi)`.
fn classe(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let nome = argomento_stringa(args, ctx, 1);
let aggiungi = args.get(2).map(|v| v.to_boolean()).unwrap_or(true);
STATO.with(|s| s.borrow_mut().ops.push(Op::Classe(nodo, nome, aggiungi)));
Ok(JsValue::undefined())
}
/// `__classe_ha(nodo, nome)`.
fn classe_ha(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let nome = argomento_stringa(args, ctx, 1);
let ha = STATO.with(|s| {
s.borrow()
.classi
.get(&nodo)
.map(|c| c.split_whitespace().any(|x| x == nome))
.unwrap_or(false)
});
Ok(JsValue::from(ha))
}
/// `__nuovo(tag)`: registra un elemento da creare e restituisce l'indice
/// sintetico (fuori dal range dei nodi reali, che stanno sotto 100000).
fn nuovo(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let tag = argomento_stringa(args, ctx, 0);
let indice = STATO.with(|s| {
let mut stato = s.borrow_mut();
let sintetico = 100_000 + stato.nuovi.len();
stato.nuovi.push(tag.clone());
stato.ops.push(Op::NuovoElemento(sintetico, tag));
sintetico
});
Ok(JsValue::from(indice as i64))
}
/// `__nuovo_testo(testo)`: come `__nuovo`, ma per un nodo di testo.
fn nuovo_testo(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let testo = argomento_stringa(args, ctx, 0);
let indice = STATO.with(|s| {
let mut stato = s.borrow_mut();
let sintetico = 100_000 + stato.nuovi.len();
stato.nuovi.push("#text".to_string());
stato.ops.push(Op::NuovoTesto(sintetico, testo));
sintetico
});
Ok(JsValue::from(indice as i64))
}
/// `__valore(nodo)`: valore corrente del campo (digitato), o attributo `value`.
fn valore(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let digitato = VALORI.with(|v| v.borrow().get(&nodo).cloned());
let testo = match digitato {
Some(v) => v,
None => STATO.with(|s| {
s.borrow()
.attributi
.get(&nodo)
.and_then(|m| m.get("value").cloned())
.unwrap_or_default()
}),
};
Ok(JsValue::from(js_string!(testo.as_str())))
}
/// `__append(padre, figlio)`.
fn append(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let padre = argomento_nodo(args, ctx, 0);
let figlio = argomento_nodo(args, ctx, 1);
STATO.with(|s| s.borrow_mut().ops.push(Op::Append(padre, figlio)));
Ok(JsValue::undefined())
}
/// `__rimuovi(padre, figlio)`.
fn rimuovi(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let padre = argomento_nodo(args, ctx, 0);
let figlio = argomento_nodo(args, ctx, 1);
STATO.with(|s| s.borrow_mut().ops.push(Op::RemoveChild(padre, figlio)));
Ok(JsValue::undefined())
}
/// `__corpo()`: indice del nodo `<body>`, oppure -1.
fn corpo(_this: &JsValue, _args: &[JsValue], _ctx: &mut Context) -> JsResult<JsValue> {
let indice = STATO.with(|s| s.borrow().corpo.map(|v| v as i64).unwrap_or(-1));
Ok(JsValue::from(indice))
}
/// `__padre(n)`.
fn padre(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let p = STATO.with(|s| s.borrow().padre.get(&nodo).map(|v| *v as i64).unwrap_or(-1));
Ok(JsValue::from(p))
}
/// `__figli(n)`: indici separati da virgola, per comodità del preludio.
fn figli(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let elenco = STATO.with(|s| {
s.borrow()
.figli
.get(&nodo)
.map(|v| {
v.iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(",")
})
.unwrap_or_default()
});
Ok(JsValue::from(js_string!(elenco.as_str())))
}
/// `__fratello(n)`: indice del fratello successivo, -1 se è l'ultimo.
fn fratello(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let f = STATO.with(|s| {
let stato = s.borrow();
stato
.padre
.get(&nodo)
.and_then(|p| stato.figli.get(p))
.and_then(|elenco| {
elenco
.iter()
.position(|x| *x == nodo)
.and_then(|i| elenco.get(i + 1))
.map(|x| *x as i64)
})
.unwrap_or(-1)
});
Ok(JsValue::from(f))
}
/// `__togli_sé(n)`: stacca il nodo dal padre.
fn togli_se(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
STATO.with(|s| s.borrow_mut().ops.push(Op::TogliSe(nodo)));
Ok(JsValue::undefined())
}
/// `__insert_before(padre, nuovo, riferimento)`; riferimento -1 = in fondo.
fn insert_before(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let padre_n = argomento_nodo(args, ctx, 0);
let nuovo = argomento_nodo(args, ctx, 1);
let rif = args
.get(2)
.and_then(|v| v.to_number(ctx).ok())
.map(|n| n as i64)
.unwrap_or(-1);
STATO.with(|s| {
s.borrow_mut()
.ops
.push(Op::InsertBefore(padre_n, nuovo, rif))
});
Ok(JsValue::undefined())
}
/// `__imposta_valore(n, testo)`: scrive nel campo (il guscio recepisce).
fn imposta_valore(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let testo = argomento_stringa(args, ctx, 1);
STATO.with(|s| s.borrow_mut().ops.push(Op::Valore(nodo, testo)));
Ok(JsValue::undefined())
}
/// `__html(n, testo)`: `innerHTML`, analizzato come HTML.
fn html(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let testo = argomento_stringa(args, ctx, 1);
STATO.with(|s| s.borrow_mut().ops.push(Op::Html(nodo, testo)));
Ok(JsValue::undefined())
}
/// `__html_accanto(n, dove, html)`: `insertAdjacentHTML`.
/// `dove` accetta `beforebegin`, `afterbegin`, `beforeend`, `afterend`.
fn html_accanto(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let dove = argomento_stringa(args, ctx, 1).to_ascii_lowercase();
let testo = argomento_stringa(args, ctx, 2);
STATO.with(|s| s.borrow_mut().ops.push(Op::HtmlAccanto(nodo, dove, testo)));
Ok(JsValue::undefined())
}
/// `__dati(n)`: attributi `data-*` come oggetto JSON (per `dataset`).
fn elenco_dati(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let dati = STATO.with(|s| {
let stato = s.borrow();
let mut mappa = serde_json::Map::new();
if let Some(attrs) = stato.attributi.get(&nodo) {
for (k, v) in attrs {
if let Some(nome) = k.strip_prefix("data-") {
mappa.insert(nome.to_string(), serde_json::Value::String(v.clone()));
}
}
}
serde_json::Value::Object(mappa).to_string()
});
Ok(JsValue::from(js_string!(dati.as_str())))
}
/// `__inline(n, tipo)`: codice dell'attributo `onclick`/`oninput`/…, o null.
fn inline(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0);
let tipo = argomento_stringa(args, ctx, 1).to_ascii_lowercase();
let codice = STATO.with(|s| {
s.borrow()
.attributi
.get(&nodo)
.and_then(|m| m.get(&format!("on{}", tipo)).cloned())
});
Ok(match codice {
Some(c) => JsValue::from(js_string!(c.as_str())),
None => JsValue::null(),
})
}
/// `__adesso()`: tempo corrente in millisecondi, fornito dal guscio.
fn adesso(_this: &JsValue, _args: &[JsValue], _ctx: &mut Context) -> JsResult<JsValue> {
let ora = OROLOGIO.with(|o| o.get());
Ok(JsValue::from(ora as f64))
}
/// `__log(testo)`: `console.log`. I messaggi finiscono in `MOSAIC_JS_LOG`
/// (stderr) e nella lista degli errori, così non si perdono.
fn log(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let testo = argomento_stringa(args, ctx, 0);
if std::env::var("MOSAIC_JS_LOG").is_ok() {
eprintln!("js: {}", testo);
}
STATO.with(|s| {
let mut stato = s.borrow_mut();
if stato.log.len() < 200 {
stato.log.push(testo);
}
});
Ok(JsValue::undefined())
}
/// `__selettore_uno(da, selettore)`: primo discendente che corrisponde (-1 = nessuno).
/// `da = -1` significa "da tutto il documento".
fn selettore_uno(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let da = args
.first()
.and_then(|v| v.to_number(ctx).ok())
.map(|n| n as i64)
.unwrap_or(-1);
let sel = argomento_stringa(args, ctx, 1);
let trovato = STATO.with(|s| {
let stato = s.borrow();
matching::primo(&stato, da, &sel)
.map(|n| n as i64)
.unwrap_or(-1)
});
Ok(JsValue::from(trovato))
}
/// `__selettori(da, selettore)`: tutti i discendenti che corrispondono.
fn selettori(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let da = args
.first()
.and_then(|v| v.to_number(ctx).ok())
.map(|n| n as i64)
.unwrap_or(-1);
let sel = argomento_stringa(args, ctx, 1);
let elenco = STATO.with(|s| {
let stato = s.borrow();
matching::tutti(&stato, da, &sel)
.iter()
.map(|n| n.to_string())
.collect::<Vec<_>>()
.join(",")
});
Ok(JsValue::from(js_string!(elenco.as_str())))
}
/// Riconoscimento dei selettori CSS usati da `querySelector`.
mod matching {
use super::Stato;
/// Un pezzo di selettore: `div`, `#id`, `.classe`, `[attributo]`.
#[derive(Debug, PartialEq)]
pub struct Pezzo {
tag: Option<String>,
id: Option<String>,
classi: Vec<String>,
attributi: Vec<String>,
}
pub fn analizza(selettore: &str) -> Vec<Pezzo> {
let mut out = Vec::new();
for pezzo in selettore.split_whitespace() {
let mut p = Pezzo {
tag: None,
id: None,
classi: Vec::new(),
attributi: Vec::new(),
};
let mut resto = pezzo;
// il tag è la parte iniziale, se non comincia con # . [
let fine_tag = resto
.find(|c| c == '#' || c == '.' || c == '[')
.unwrap_or(resto.len());
if fine_tag > 0 {
let t = &resto[..fine_tag];
if t != "*" {
p.tag = Some(t.to_ascii_lowercase());
}
}
resto = &resto[fine_tag..];
while !resto.is_empty() {
match resto.chars().next() {
Some('#') => {
let fine = resto[1..]
.find(|c| c == '#' || c == '.' || c == '[')
.map(|i| i + 1)
.unwrap_or(resto.len());
p.id = Some(resto[1..fine].to_string());
resto = &resto[fine..];
}
Some('.') => {
let fine = resto[1..]
.find(|c| c == '#' || c == '.' || c == '[')
.map(|i| i + 1)
.unwrap_or(resto.len());
p.classi.push(resto[1..fine].to_string());
resto = &resto[fine..];
}
Some('[') => {
let fine = resto.find(']').unwrap_or(resto.len() - 1);
p.attributi.push(resto[1..fine].to_string());
resto = &resto[fine + 1..];
}
_ => break,
}
}
out.push(p);
}
out
}
fn corrisponde(stato: &Stato, nodo: usize, p: &Pezzo) -> bool {
if let Some(t) = &p.tag {
let Some(tag) = stato.tag.get(&nodo) else {
return false;
};
if !tag.eq_ignore_ascii_case(t) {
return false;
}
}
let attrs = stato.attributi.get(&nodo);
if let Some(id) = &p.id {
let ok = attrs
.and_then(|m| m.get("id"))
.map(|v| v == id)
.unwrap_or(false);
if !ok {
return false;
}
}
if !p.classi.is_empty() {
let classi = stato.classi.get(&nodo).cloned().unwrap_or_default();
for c in &p.classi {
if !classi.split_whitespace().any(|x| x == c) {
return false;
}
}
}
for a in &p.attributi {
// si accetta `nome` e `nome="valore"`; il valore va fra virgolette
let (nome, valore) = match a.split_once('=') {
Some((n, v)) => (
n.trim(),
Some(v.trim().trim_matches('"').trim_matches('\'')),
),
None => (a.trim(), None),
};
let Some(m) = attrs else { return false };
let Some(v) = m.get(&nome.to_ascii_lowercase()) else {
return false;
};
if let Some(atteso) = valore {
if v != atteso {
return false;
}
}
}
true
}
/// Vero se `nodo` corrisponde all'ultimo pezzo e i precedenti si trovano
/// risalendo gli antenati (discendenza).
fn catena_ok(stato: &Stato, nodo: usize, pezzi: &[Pezzo]) -> bool {
let Some(ultimo) = pezzi.last() else {
return false;
};
if !corrisponde(stato, nodo, ultimo) {
return false;
}
let mut restanti = pezzi.len() as isize - 2;
let mut corrente = nodo;
while restanti >= 0 {
let Some(p) = stato.padre.get(&corrente) else {
return false;
};
corrente = *p;
if corrisponde(stato, corrente, &pezzi[restanti as usize]) {
restanti -= 1;
}
}
true
}
fn discendenti(stato: &Stato, da: i64, out: &mut Vec<usize>) {
let radici: Vec<usize> = if da < 0 {
// tutti i nodi, in ordine di indice (approssima l'ordine del documento)
let mut primi: Vec<usize> = stato
.figli
.keys()
.copied()
.filter(|n| !stato.padre.contains_key(n))
.collect();
primi.sort_unstable();
primi
} else {
vec![da as usize]
};
let mut pila: Vec<usize> = radici.into_iter().rev().collect();
while let Some(nodo) = pila.pop() {
if let Some(f) = stato.figli.get(&nodo) {
for &figlio in f.iter().rev() {
pila.push(figlio);
}
}
out.push(nodo);
}
}
pub fn tutti(stato: &Stato, da: i64, selettore: &str) -> Vec<usize> {
let pezzi = analizza(selettore);
if pezzi.is_empty() {
return Vec::new();
}
let mut nodi = Vec::new();
discendenti(stato, da, &mut nodi);
nodi.into_iter()
.filter(|n| stato.tag.contains_key(n) && catena_ok(stato, *n, &pezzi))
.collect()
}
pub fn primo(stato: &Stato, da: i64, selettore: &str) -> Option<usize> {
tutti(stato, da, selettore).into_iter().next()
}
}
/// `backgroundColor` → `background-color`.
fn kebab(prop: &str) -> String {
let mut out = String::with_capacity(prop.len() + 4);
for c in prop.chars() {
if c.is_ascii_uppercase() {
out.push('-');
out.push(c.to_ascii_lowercase());
} else {
out.push(c);
}
}
out
}
/// Testo concatenato dei discendenti di un nodo.
fn testo_di(doc: &Document, nodo: usize) -> String {
let mut out = String::new();
for &c in &doc.node(nodo).children {
match &doc.node(c).kind {
NodeKind::Text(t) => out.push_str(t),
NodeKind::Element(_) => out.push_str(&testo_di(doc, c)),
_ => {}
}
}
out
}
/// Snapshot del documento visto dagli script: id, testi, attributi, classi.
fn prepara(doc: &Document) {
let mut stato = Stato::default();
for (i, nodo) in doc.nodes.iter().enumerate() {
// struttura dell'albero: serve a navigazione e selettori, vale per ogni nodo
if let Some(p) = nodo.parent {
stato.padre.insert(i, p);
}
stato
.figli
.insert(i, doc.node(i).children.iter().copied().collect());
if let NodeKind::Element(e) = &nodo.kind {
if e.name.eq_ignore_ascii_case("script") {
continue;
}
if let Some(id) = e.attr("id") {
stato.id.insert(id.to_string(), i);
}
if e.name.eq_ignore_ascii_case("body") {
stato.corpo = Some(i);
}
stato.testi.insert(i, testo_di(doc, i));
stato.tag.insert(i, e.name.to_ascii_lowercase());
let mut attrs = HashMap::new();
for (k, v) in &e.attrs {
attrs.insert(k.to_ascii_lowercase(), v.clone());
}
stato.attributi.insert(i, attrs);
stato
.stili_inline
.insert(i, e.attr("style").unwrap_or("").to_string());
stato
.classi
.insert(i, e.attr("class").unwrap_or("").to_string());
}
}
STATO.with(|s| *s.borrow_mut() = stato);
}
/// Applica al DOM le scritture accodate.
fn applica(doc: &mut Document, ops: Vec<Op>) {
// gli indici sintetici dei nodi creati da script diventano reali appena il
// nodo nasce: le operazioni successive li ritrovano qui
let mut mappa: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
// i valori scritti dagli script vanno riportati al guscio
SCRITTI.with(|s| s.borrow_mut().clear());
let risolvi = |mappa: &std::collections::HashMap<usize, usize>, id: usize| -> usize {
*mappa.get(&id).unwrap_or(&id)
};
for op in ops {
match op {
Op::NuovoElemento(sintetico, tag) => {
let reale = doc.nodes.len();
let nodo = doc.create_element(&tag, Vec::new());
mappa.insert(sintetico, nodo);
debug_assert_eq!(reale, nodo);
}
Op::NuovoTesto(sintetico, testo) => {
let nodo = doc.create_text(&testo);
mappa.insert(sintetico, nodo);
}
Op::Append(padre, figlio) => {
let p = risolvi(&mappa, padre);
let f = risolvi(&mappa, figlio);
if p < doc.nodes.len() && f < doc.nodes.len() {
doc.append_child(p, f);
}
}
Op::InsertBefore(padre, figlio, rif) => {
let p = risolvi(&mappa, padre);
let f = risolvi(&mappa, figlio);
if p < doc.nodes.len() && f < doc.nodes.len() {
// via dal padre precedente, se c'era
if let Some(vecchio) = doc.node(f).parent {
doc.node_mut(vecchio).children.retain(|x| *x != f);
}
let posizione = if rif < 0 {
doc.node(p).children.len()
} else {
let r = risolvi(&mappa, rif as usize);
doc.node(p)
.children
.iter()
.position(|x| *x == r)
.unwrap_or(usize::MAX)
};
let posizione = posizione.min(doc.node(p).children.len());
doc.node_mut(p).children.insert(posizione, f);
doc.node_mut(f).parent = Some(p);
}
}
Op::TogliSe(nodo) => {
let n = risolvi(&mappa, nodo);
if n < doc.nodes.len() {
if let Some(p) = doc.node(n).parent {
doc.node_mut(p).children.retain(|x| *x != n);
}
doc.node_mut(n).parent = None;
}
}
Op::Valore(nodo, testo) => {
let n = risolvi(&mappa, nodo);
SCRITTI.with(|s| s.borrow_mut().push((n, testo)));
}
Op::HtmlAccanto(nodo, dove, testo) => {
let n = risolvi(&mappa, nodo);
if n < doc.nodes.len() {
// i nodi nuovi si creano staccati, poi si mettono dove serve
let frammento = crate::treebuilder::parse(&testo);
let radice = frammento
.doc
.find_element(frammento.doc.root(), "body")
.unwrap_or_else(|| frammento.doc.root());
let figli: Vec<usize> = frammento.doc.node(radice).children.clone();
let creati: Vec<usize> = figli
.iter()
.map(|f| copia_nodo_staccato(&frammento.doc, doc, *f))
.collect();
let (padre, posizione) = match dove.as_str() {
"afterbegin" => (Some(n), 0usize),
"beforebegin" => doc
.node(n)
.parent
.map(|p| {
let i = doc
.node(p)
.children
.iter()
.position(|x| *x == n)
.unwrap_or(0);
(Some(p), i)
})
.unwrap_or((Some(n), 0)),
"afterend" => doc
.node(n)
.parent
.map(|p| {
let i = doc
.node(p)
.children
.iter()
.position(|x| *x == n)
.unwrap_or(0);
(Some(p), i + 1)
})
.unwrap_or((Some(n), doc.node(n).children.len())),
// beforeend, e qualunque valore non riconosciuto
_ => (Some(n), doc.node(n).children.len()),
};
if let Some(p) = padre {
let mut dove = posizione;
for figlio in &creati {
// `insert` va oltre la fine se la posizione è l'ultima:
// si limita alla lunghezza corrente
let lunghezza = doc.node(p).children.len();
dove = dove.min(lunghezza);
doc.node_mut(p).children.insert(dove, *figlio);
doc.node_mut(*figlio).parent = Some(p);
dove += 1;
}
}
}
}
Op::Html(nodo, testo) => {
let n = risolvi(&mappa, nodo);
if n < doc.nodes.len() {
copia_frammento(doc, n, &testo);
}
}
Op::RemoveChild(padre, figlio) => {
let p = risolvi(&mappa, padre);
let f = risolvi(&mappa, figlio);
if p < doc.nodes.len() && f < doc.nodes.len() {
doc.node_mut(p).children.retain(|x| *x != f);
doc.node_mut(f).parent = None;
}
}
Op::Testo(nodo, testo) => {
let nodo = risolvi(&mappa, nodo);
if nodo >= doc.nodes.len() {
continue;
}
let nuovo = doc.nodes.len();
doc.nodes.push(Node {
kind: NodeKind::Text(testo),
parent: Some(nodo),
children: Vec::new(),
});
doc.nodes[nodo].children = vec![nuovo];
}
Op::Attributo(nodo, nome, valore) => {
let nodo = risolvi(&mappa, nodo);
if nodo < doc.nodes.len() {
doc.set_attr(nodo, &nome, &valore);
}
}
Op::TogliAttributo(nodo, nome) => {
let nodo = risolvi(&mappa, nodo);
if nodo < doc.nodes.len() {
doc.remove_attr(nodo, &nome);
}
}
Op::Stile(nodo, prop, valore) => {
let nodo = risolvi(&mappa, nodo);
if nodo >= doc.nodes.len() {
continue;
}
let esistente = doc.attr(nodo, "style").unwrap_or("").to_string();
let nuovo = fondi_stile(&esistente, &prop, &valore);
doc.set_attr(nodo, "style", &nuovo);
}
Op::Classe(nodo, nome, aggiungi) => {
let nodo = risolvi(&mappa, nodo);
if nodo >= doc.nodes.len() {
continue;
}
let attuale = doc.attr(nodo, "class").unwrap_or("").to_string();
let mut pezzi: Vec<&str> = attuale.split_whitespace().collect();
let presente = pezzi.iter().any(|x| *x == nome);
if aggiungi && !presente {
pezzi.push(&nome);
} else if !aggiungi {
pezzi.retain(|x| *x != nome);
}
doc.set_attr(nodo, "class", &pezzi.join(" "));
}
}
}
}
/// Analizza `html` e ne copia i nodi come figli di `destinazione`: è quello che
/// serve a `innerHTML = ...`, che in HTML non è "scrivi dei caratteri".
fn copia_frammento(doc: &mut Document, destinazione: usize, html: &str) {
let frammento = crate::treebuilder::parse(html);
// i figli utili stanno nel <body> implicito
let radice = frammento
.doc
.find_element(frammento.doc.root(), "body")
.unwrap_or_else(|| frammento.doc.root());
doc.node_mut(destinazione).children.clear();
let figli: Vec<usize> = frammento.doc.node(radice).children.clone();
for figlio in figli {
copia_nodo(&frammento.doc, doc, figlio, destinazione);
}
}
/// Copia un nodo (e i suoi discendenti) senza attaccarlo a nessuno: serve a
/// `insertAdjacentHTML`, che deve metterlo in un punto preciso.
fn copia_nodo_staccato(sorgente: &Document, destinazione: &mut Document, nodo: usize) -> usize {
use crate::dom::NodeKind as K;
let nuovo = match &sorgente.node(nodo).kind {
K::Element(e) => {
let attrs = e.attrs.clone();
destinazione.create_element(&e.name, attrs)
}
K::Text(t) => destinazione.create_text(t),
K::Comment(t) => destinazione.create_comment(t),
_ => destinazione.create_text(""),
};
let figli: Vec<usize> = sorgente.node(nodo).children.clone();
for figlio in figli {
let copia = copia_nodo_staccato(sorgente, destinazione, figlio);
destinazione.append_child(nuovo, copia);
}
nuovo
}
fn copia_nodo(sorgente: &Document, destinazione: &mut Document, nodo: usize, padre: usize) {
use crate::dom::NodeKind as K;
let nuovo = match &sorgente.node(nodo).kind {
K::Element(e) => {
let attrs = e.attrs.clone();
destinazione.create_element(&e.name, attrs)
}
K::Text(t) => destinazione.create_text(t),
K::Comment(t) => destinazione.create_comment(t),
_ => return,
};
destinazione.append_child(padre, nuovo);
let figli: Vec<usize> = sorgente.node(nodo).children.clone();
for figlio in figli {
copia_nodo(sorgente, destinazione, figlio, nuovo);
}
}
/// Sostituisce (o aggiunge) una dichiarazione nel testo dell'attributo `style`.
fn fondi_stile(esistente: &str, prop: &str, valore: &str) -> String {
let mut pezzi: Vec<String> = Vec::new();
let mut trovato = false;
for dichiarazione in esistente.split(';') {
let d = dichiarazione.trim();
if d.is_empty() {
continue;
}
match d.split_once(':') {
Some((k, _)) if k.trim().eq_ignore_ascii_case(prop) => {
// `style.colore = ''` in HTML **toglie** la dichiarazione
if !valore.trim().is_empty() {
pezzi.push(format!("{}: {}", prop, valore));
}
trovato = true;
}
_ => pezzi.push(d.to_string()),
}
}
if !trovato && !valore.trim().is_empty() {
pezzi.push(format!("{}: {}", prop, valore));
}
pezzi.join("; ")
}
type FunzioneOspite = fn(&JsValue, &[JsValue], &mut Context) -> JsResult<JsValue>;
/// Macchina JavaScript con stato fra una chiamata e l'altra: serve agli eventi,
/// che arrivano dopo il caricamento.
pub struct Macchina {
ctx: Context,
}
impl Macchina {
/// Costruisce l'interprete con il preludio DOM già valutato.
pub fn nuova() -> Result<Macchina, String> {
let mut ctx = Context::default();
let registrazioni: Vec<(&str, usize, FunzioneOspite)> = vec![
("__find", 1, trova),
("__leggi", 1, leggi),
("__scrivi", 2, scrivi),
("__attributo", 3, attributo),
("__attr_togli", 2, attr_togli),
("__attr_leggi", 2, attr_leggi),
("__stile", 3, stile),
("__stile_leggi", 2, stile_leggi),
("__classe", 3, classe),
("__classe_ha", 2, classe_ha),
("__nuovo", 1, nuovo),
("__nuovo_testo", 1, nuovo_testo),
("__append", 2, append),
("__rimuovi", 2, rimuovi),
("__corpo", 0, corpo),
("__valore", 1, valore),
("__padre", 1, padre),
("__figli", 1, figli),
("__fratello", 1, fratello),
("__togli_se", 1, togli_se),
("__insert_before", 3, insert_before),
("__imposta_valore", 2, imposta_valore),
("__html", 2, html),
("__inline", 2, inline),
("__log", 1, log),
("__selettore_uno", 2, selettore_uno),
("__selettori", 2, selettori),
("__adesso", 0, adesso),
("__html_accanto", 3, html_accanto),
("__dati", 1, elenco_dati),
];
for (nome, arita, f) in registrazioni {
ctx.register_global_builtin_callable(
js_string!(nome),
arita,
NativeFunction::from_fn_ptr(f),
)
.map_err(|e| format!("registrazione di {}: {}", nome, e))?;
}
ctx.eval(Source::from_bytes(PRELUDIO))
.map_err(|e| format!("preludio DOM: {}", e))?;
Ok(Macchina { ctx })
}
/// Valori correnti dei campi (nodo → testo digitato), forniti dal guscio:
/// servono a `element.value` dentro i gestori di evento.
pub fn imposta_valori(&mut self, valori: std::collections::HashMap<usize, String>) {
VALORI.with(|v| *v.borrow_mut() = valori);
}
/// Esegue una sequenza di script (inline ed esterni), nell'ordine dato.
/// `carica` risolve un `<script src>` nel suo codice; se restituisce `None`
/// l'errore viene riportato e si prosegue col successivo.
pub fn esegui_sequenza(
&mut self,
doc: &mut Document,
sequenza: &[crate::script::Sorgente],
carica: &dyn Fn(&str) -> Option<String>,
) -> Vec<String> {
if sequenza.is_empty() {
return Vec::new();
}
prepara(doc);
OROLOGIO.with(|o| o.set(OROLOGIO.with(|x| x.get())));
let mut errori = Vec::new();
for (i, voce) in sequenza.iter().enumerate() {
let codice = match voce {
crate::script::Sorgente::Inline(c) => c.clone(),
crate::script::Sorgente::Esterno(src) => match carica(src) {
Some(c) => c,
None => {
errori.push(format!("script esterno non caricabile: {}", src));
continue;
}
},
};
if codice.trim().is_empty() {
continue;
}
if let Err(e) = self.ctx.eval(Source::from_bytes(codice.as_str())) {
errori.push(format!("script #{}: {}", i + 1, e));
}
// le continuazioni delle Promise (then/await) sono microtask: senza
// questo restano in coda per sempre e la pagina non si aggiorna
self.ctx.run_jobs();
}
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
applica(doc, ops);
errori
}
/// Esegue gli script inline del documento, applicando poi le scritture.
pub fn esegui(&mut self, doc: &mut Document, sorgenti: &[String]) -> Vec<String> {
let codici: Vec<&String> = sorgenti.iter().filter(|c| !c.trim().is_empty()).collect();
if codici.is_empty() {
return Vec::new();
}
prepara(doc);
let mut errori = Vec::new();
for (i, codice) in codici.iter().enumerate() {
if let Err(e) = self.ctx.eval(Source::from_bytes(codice.as_str())) {
errori.push(format!("script #{}: {}", i + 1, e));
}
// le continuazioni delle Promise (then/await) sono microtask: senza
// questo restano in coda per sempre e la pagina non si aggiorna
self.ctx.run_jobs();
}
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
applica(doc, ops);
errori
}
/// Consegna un evento al nodo e ai suoi antenati (prima il bersaglio, poi la
/// propagazione verso l'alto). Restituisce quanti gestori sono stati eseguiti.
pub fn evento(
&mut self,
doc: &mut Document,
tipo: &str,
catena: &[usize],
x: f32,
y: f32,
) -> usize {
prepara(doc);
let _ = self.ctx.eval(Source::from_bytes("__azzera_preventuto()"));
let mut eseguiti = 0usize;
for &nodo in catena {
let codice = format!("__dispatch({}, '{}', {}, {})", nodo, tipo, x, y);
match self.ctx.eval(Source::from_bytes(codice.as_str())) {
Ok(v) => {
eseguiti += v.to_number(&mut self.ctx).unwrap_or(0.0) as usize;
// `stopPropagation` ferma la risalita agli antenati
let ferma = self
.ctx
.eval(Source::from_bytes("__ferma === true"))
.map(|v| v.to_boolean())
.unwrap_or(false);
if ferma {
break;
}
}
Err(e) => {
// un gestore rotto non deve fermare la pagina
eprintln!("mosaic: errore nel gestore di clic: {}", e);
break;
}
}
}
// il gestore può aver acceso una Promise: le sue continuazioni girano ora
self.ctx.run_jobs();
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
applica(doc, ops);
eseguiti
}
/// Valori che gli script hanno scritto nei campi: il guscio li applica
/// allo stato dei moduli (il motore non può toccarlo).
pub fn preleva_valori_scritti(&mut self) -> Vec<(usize, String)> {
SCRITTI.with(|s| s.borrow_mut().drain(..).collect())
}
/// Messaggi di `console.log` raccolti finora.
pub fn messaggi_log(&self) -> Vec<String> {
STATO.with(|s| s.borrow().log.clone())
}
/// Esegue i timer scaduti entro `adesso_ms` (orologio del guscio) e applica
/// le modifiche al DOM. Restituisce quanti timer sono stati eseguiti.
pub fn pompa_timer(&mut self, doc: &mut Document, adesso_ms: u64, limite: usize) -> usize {
OROLOGIO.with(|o| o.set(adesso_ms));
let codice = format!("__timer_pompa({}, {})", adesso_ms, limite);
let eseguiti = match self.ctx.eval(Source::from_bytes(codice.as_str())) {
Ok(v) => v.to_number(&mut self.ctx).unwrap_or(0.0) as usize,
Err(e) => {
eprintln!("mosaic: errore nei timer: {}", e);
0
}
};
self.ctx.run_jobs();
if eseguiti > 0 {
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
applica(doc, ops);
}
eseguiti
}
/// Richieste `fetch` in attesa: (id, url, metodo, corpo). Le esegue il guscio,
/// che sa fare rete; il motore non esce mai da solo.
pub fn richieste_pendenti(&mut self) -> Vec<(u64, String, String, Option<String>)> {
let esito = self.ctx.eval(Source::from_bytes("__richieste_pendenti()"));
let Ok(v) = esito else { return Vec::new() };
let Ok(testo) = v.to_string(&mut self.ctx) else {
return Vec::new();
};
let json: serde_json::Value =
serde_json::from_str(&testo.to_std_string_escaped()).unwrap_or(serde_json::Value::Null);
let mut out = Vec::new();
if let Some(elenco) = json.as_array() {
for r in elenco {
out.push((
r.get("id").and_then(|v| v.as_u64()).unwrap_or(0),
r.get("url")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
r.get("metodo")
.and_then(|v| v.as_str())
.unwrap_or("GET")
.to_string(),
r.get("corpo")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
));
}
}
out
}
/// Consegna la risposta di una `fetch`: esegue il callback e applica al DOM
/// quello che ha scritto. `stato` negativo significa richiesta fallita.
pub fn consegna_risposta(
&mut self,
doc: &mut Document,
id: u64,
stato: i32,
corpo: &str,
) -> usize {
prepara(doc);
let corpo_json = serde_json::Value::String(corpo.to_string()).to_string();
let codice = format!("__risposta({}, {}, {})", id, stato, corpo_json);
let eseguiti = match self.ctx.eval(Source::from_bytes(codice.as_str())) {
Ok(v) => v.to_number(&mut self.ctx).unwrap_or(0.0) as usize,
Err(e) => {
eprintln!("mosaic: errore nella risposta di fetch: {}", e);
0
}
};
// la risposta sblocca `await fetch(...)`: le continuazioni girano adesso
self.ctx.run_jobs();
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
applica(doc, ops);
eseguiti
}
/// Prima scadenza futura secondo l'orologio del guscio, se c'è un timer in coda.
pub fn prossima_scadenza(&mut self) -> Option<u64> {
match self.ctx.eval(Source::from_bytes("__timer_prossimo()")) {
Ok(v) => v
.to_number(&mut self.ctx)
.ok()
.filter(|n| *n >= 0.0)
.map(|n| n as u64),
Err(_) => None,
}
}
/// Vero se l'ultimo evento consegnato è stato annullato con `preventDefault`.
pub fn preventuto_default(&mut self) -> bool {
self.ctx
.eval(Source::from_bytes("__preventuto === true"))
.map(|v| v.to_boolean())
.unwrap_or(false)
}
/// Consegna un evento di tastiera, con il tasto premuto.
pub fn evento_tasto(&mut self, doc: &mut Document, catena: &[usize], tasto: &str) -> usize {
prepara(doc);
let _ = self.ctx.eval(Source::from_bytes("__azzera_preventuto()"));
let mut eseguiti = 0usize;
for &nodo in catena {
let codice = format!(
"__dispatch({}, 'keydown', 0, 0, {})",
nodo,
serde_json::Value::String(tasto.to_string())
);
match self.ctx.eval(Source::from_bytes(codice.as_str())) {
Ok(v) => {
eseguiti += v.to_number(&mut self.ctx).unwrap_or(0.0) as usize;
let ferma = self
.ctx
.eval(Source::from_bytes("__ferma === true"))
.map(|v| v.to_boolean())
.unwrap_or(false);
if ferma {
break;
}
}
Err(e) => {
eprintln!("mosaic: errore in keydown: {}", e);
break;
}
}
}
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
applica(doc, ops);
eseguiti
}
/// Scorciatoia per l'evento più usato.
pub fn clic(&mut self, doc: &mut Document, catena: &[usize], x: f32, y: f32) -> usize {
self.evento(doc, "click", catena, x, y)
}
}
/// Esegue gli script inline del documento e applica le scritture al DOM.
/// Restituisce gli errori, che il chiamante riporta senza interrompere il rendering.
pub fn esegui(doc: &mut Document, sorgenti: &[String]) -> Vec<String> {
match Macchina::nuova() {
Ok(mut m) => m.esegui(doc, sorgenti),
Err(e) => vec![e],
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::treebuilder;
fn testo_del_div(doc: &Document, id: &str) -> String {
for (i, n) in doc.nodes.iter().enumerate() {
if let NodeKind::Element(e) = &n.kind {
if e.attr("id") == Some(id) {
return testo_di(doc, i);
}
}
}
String::new()
}
/// Nodo e antenati, come li consegna il guscio.
fn catena_nodi(doc: &Document, nodo: usize) -> Vec<usize> {
let mut out = Vec::new();
let mut corrente = Some(nodo);
while let Some(n) = corrente {
out.push(n);
corrente = doc.nodes.get(n).and_then(|x| x.parent);
}
out
}
fn nodo_con_id(doc: &Document, id: &str) -> usize {
for (i, n) in doc.nodes.iter().enumerate() {
if let NodeKind::Element(e) = &n.kind {
if e.attr("id") == Some(id) {
return i;
}
}
}
panic!("nodo {} assente", id);
}
#[test]
fn script_cambia_il_testo() {
let mut built = treebuilder::parse(
"<div id=\"t\">prima</div><script>document.getElementById('t').textContent = 'dopo';</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
assert_eq!(testo_del_div(&built.doc, "t"), "dopo");
}
#[test]
fn script_legge_il_testo_e_calcola() {
let mut built = treebuilder::parse(
"<p id=\"n\">12</p><script>var n = document.getElementById('n'); n.textContent = 'valore ' + (Number(n.textContent) * 2);</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
assert_eq!(testo_del_div(&built.doc, "n"), "valore 24");
}
#[test]
fn errore_di_sintassi_non_blocca() {
let mut built =
treebuilder::parse("<div id=\"t\">x</div><script>questo non è javascript;</script>");
let errori = esegui(&mut built.doc, &built.scripts);
assert_eq!(errori.len(), 1);
assert_eq!(testo_del_div(&built.doc, "t"), "x");
}
#[test]
fn elemento_inesistente_e_null() {
let mut built =
treebuilder::parse("<div id=\"t\">x</div><script>if (document.getElementById('manca') === null) { document.getElementById('t').textContent = 'ok'; }</script>");
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
assert_eq!(testo_del_div(&built.doc, "t"), "ok");
}
#[test]
fn set_attribute_arriva_al_dom() {
let mut built = treebuilder::parse(
"<div id=\"t\">x</div><script>document.getElementById('t').setAttribute('data-stato', 'pronto');</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
let n = nodo_con_id(&built.doc, "t");
assert_eq!(built.doc.attr(n, "data-stato"), Some("pronto"));
}
#[test]
fn stile_inline_con_nome_camel_case() {
let mut built = treebuilder::parse(
"<div id=\"t\">x</div><script>document.getElementById('t').style.backgroundColor = '#ff0000';</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
let n = nodo_con_id(&built.doc, "t");
assert_eq!(
built.doc.attr(n, "style"),
Some("background-color: #ff0000")
);
}
#[test]
fn classlist_aggiunge_e_toglie() {
let mut built = treebuilder::parse(
"<div id=\"t\" class=\"a\">x</div><script>var e = document.getElementById('t'); e.classList.add('b'); e.classList.remove('a');</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
let n = nodo_con_id(&built.doc, "t");
assert_eq!(built.doc.attr(n, "class"), Some("b"));
}
#[test]
fn clic_esegue_il_gestore() {
let mut built = treebuilder::parse(
"<div id=\"t\">prima</div><script>document.getElementById('t').addEventListener('click', function (ev) { this.textContent = 'cliccato a ' + ev.clientX; });</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
let errori = macchina.esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
assert_eq!(testo_del_div(&built.doc, "t"), "prima");
let nodo = nodo_con_id(&built.doc, "t");
let eseguiti = macchina.clic(&mut built.doc, &[nodo], 12.0, 34.0);
assert_eq!(eseguiti, 1, "il gestore non è stato chiamato");
assert_eq!(testo_del_div(&built.doc, "t"), "cliccato a 12");
}
#[test]
fn get_element_by_id_funziona_al_clic() {
// il gestore annota nel documento quello che trova: così si vede, dal
// lato Rust, se `getElementById` funziona anche al momento del clic
let mut built = treebuilder::parse(
"<div id=\"zona\">x</div><div id=\"elenco\"></div><script>\
document.getElementById('zona').addEventListener('click', function () {\
var e = document.getElementById('elenco');\
var z = document.getElementById('zona');\
z.textContent = (e === null ? 'elenco nullo' : 'elenco trovato');\
});</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
let errori = macchina.esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
let zona = nodo_con_id(&built.doc, "zona");
macchina.clic(&mut built.doc, &[zona], 1.0, 1.0);
assert_eq!(testo_del_div(&built.doc, "zona"), "elenco trovato");
}
#[test]
fn costruzione_di_nodi_al_clic() {
let mut built = treebuilder::parse(
"<div id=\"zona\">x</div><div id=\"elenco\"></div><script>\
document.getElementById('zona').addEventListener('click', function () {\
var p = document.createElement('p');\
p.textContent = 'nuovo';\
document.getElementById('elenco').appendChild(p);\
});</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
let errori = macchina.esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
let zona = nodo_con_id(&built.doc, "zona");
let eseguiti = macchina.clic(&mut built.doc, &[zona], 1.0, 1.0);
assert_eq!(eseguiti, 1);
assert_eq!(testo_del_div(&built.doc, "elenco"), "nuovo");
}
#[test]
fn evento_input_arriva_al_gestore() {
let mut built = treebuilder::parse(
"<input id=\"campo\" type=\"text\"><div id=\"eco\"></div><script>\
document.getElementById('campo').addEventListener('input', function () {\
document.getElementById('eco').textContent = 'cambiato:' + this.value;\
});</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
macchina.esegui(&mut built.doc, &built.scripts);
// il guscio comunica il valore digitato prima dell'evento
let campo = nodo_con_id(&built.doc, "campo");
let mut valori = std::collections::HashMap::new();
valori.insert(campo, "ciao".to_string());
macchina.imposta_valori(valori);
assert_eq!(
macchina.evento(&mut built.doc, "input", &[campo], 0.0, 0.0),
1
);
assert_eq!(testo_del_div(&built.doc, "eco"), "cambiato:ciao");
}
#[test]
fn evento_submit_sul_form() {
let mut built = treebuilder::parse(
"<form id=\"f\"><input id=\"b\" type=\"submit\" value=\"Invia\"></form>\
<div id=\"esito\"></div><script>\
document.getElementById('f').addEventListener('submit', function (ev) {\
ev.preventDefault();\
document.getElementById('esito').textContent = 'intercettato';\
});</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
macchina.esegui(&mut built.doc, &built.scripts);
let form = nodo_con_id(&built.doc, "f");
assert_eq!(
macchina.evento(&mut built.doc, "submit", &[form], 0.0, 0.0),
1
);
assert_eq!(testo_del_div(&built.doc, "esito"), "intercettato");
}
#[test]
fn navigazione_dell_albero() {
let mut built = treebuilder::parse(
"<div id=\"padre\"><span id=\"primo\">a</span><span id=\"secondo\">b</span></div>\
<script>var s = document.getElementById('primo');\
document.getElementById('secondo').textContent =\
(s.parentNode ? 'padre-ok' : 'padre-no') + ' ' + s.nextSibling.getAttribute('id');\
</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
assert_eq!(testo_del_div(&built.doc, "secondo"), "padre-ok secondo");
let padre = nodo_con_id(&built.doc, "padre");
assert_eq!(built.doc.node(padre).children.len(), 2);
}
#[test]
fn remove_stacca_il_nodo() {
let mut built = treebuilder::parse(
"<div id=\"p\"><span id=\"a\">a</span><span id=\"b\">b</span></div>\
<script>document.getElementById('a').remove();</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
let p = nodo_con_id(&built.doc, "p");
assert_eq!(built.doc.node(p).children.len(), 1);
assert_eq!(testo_del_div(&built.doc, "p"), "b");
}
#[test]
fn insert_before_mette_in_mezzo() {
let mut built = treebuilder::parse(
"<div id=\"p\"><span id=\"b\">b</span></div><script>\
var nuovo = document.createElement('span');\
nuovo.textContent = 'a';\
document.getElementById('p').insertBefore(nuovo, document.getElementById('b'));\
</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
assert_eq!(testo_del_div(&built.doc, "p"), "ab");
}
#[test]
fn stop_propagation_ferma_la_risalita() {
let mut built = treebuilder::parse(
"<div id=\"fuori\"><span id=\"dentro\">x</span></div><script>\
document.getElementById('dentro').addEventListener('click', function (ev) {\
ev.stopPropagation(); document.getElementById('dentro').textContent = 'dentro';\
});\
document.getElementById('fuori').addEventListener('click', function () {\
document.getElementById('fuori').textContent = 'fuori';\
});</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
macchina.esegui(&mut built.doc, &built.scripts);
let dentro = nodo_con_id(&built.doc, "dentro");
let catena = catena_nodi(&built.doc, dentro);
macchina.evento(&mut built.doc, "click", &catena, 0.0, 0.0);
assert_eq!(testo_del_div(&built.doc, "dentro"), "dentro");
// l'antenato non deve essere stato toccato: il suo testo resta quello di prima
assert!(testo_del_div(&built.doc, "fuori").contains("dentro"));
}
#[test]
fn handler_inline_onclick() {
let mut built = treebuilder::parse(
"<div id=\"t\">x</div><button id=\"b\" onclick=\"document.getElementById('t').textContent = 'premuto'\">vai</button>",
);
let mut macchina = Macchina::nuova().expect("interprete");
macchina.esegui(&mut built.doc, &built.scripts);
let b = nodo_con_id(&built.doc, "b");
assert_eq!(macchina.evento(&mut built.doc, "click", &[b], 0.0, 0.0), 1);
assert_eq!(testo_del_div(&built.doc, "t"), "premuto");
}
#[test]
fn innerhtml_analizza_i_tag() {
let mut built = treebuilder::parse(
"<div id=\"t\"></div><script>\
document.getElementById('t').innerHTML = '<b id=\"grassetto\">ciao</b>';</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
assert_eq!(testo_del_div(&built.doc, "t"), "ciao");
let grassetto = nodo_con_id(&built.doc, "grassetto");
assert_eq!(built.doc.element_name(grassetto), Some("b"));
}
#[test]
fn query_selector_per_id_classe_e_discendenza() {
let mut built = treebuilder::parse(
"<div class=\"scatola\"><p id=\"uno\">a</p><p class=\"evidenza\">b</p></div>\
<script>var e = document.getElementById('uno');\
var per_id = document.querySelector('#uno');\
var per_classe = document.querySelector('.evidenza');\
var discendente = document.querySelector('div p');\
var tutti = document.querySelectorAll('p');\
e.textContent = (per_id ? 'id' : '-') + ' ' + (per_classe ? 'classe' : '-') + ' ' +\
(discendente ? 'discente' : '-') + ' ' + tutti.length;\
</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
assert_eq!(testo_del_div(&built.doc, "uno"), "id classe discente 2");
}
#[test]
fn stile_vuoto_toglie_la_dichiarazione() {
let mut built = treebuilder::parse(
"<div id=\"t\" style=\"color: red; font-size: 20px\">x</div><script>\
document.getElementById('t').style.color = '';</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
let n = nodo_con_id(&built.doc, "t");
let stile = built.doc.attr(n, "style").unwrap_or("").to_string();
assert!(!stile.contains("color"), "stile: {}", stile);
assert!(stile.contains("font-size"), "stile: {}", stile);
}
#[test]
fn console_log_viene_raccolto() {
let mut built = treebuilder::parse("<div>x</div><script>console.log('ciao', 42);</script>");
let mut macchina = Macchina::nuova().expect("interprete");
let errori = macchina.esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
assert_eq!(macchina.messaggi_log(), vec!["ciao 42".to_string()]);
}
#[test]
fn valore_scritto_dallo_script_arriva_al_guscio() {
let mut built = treebuilder::parse(
"<input id=\"c\" type=\"text\"><script>\
document.getElementById('c').value = 'impostato';</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
macchina.esegui(&mut built.doc, &built.scripts);
let scritti = macchina.preleva_valori_scritti();
let nodo = nodo_con_id(&built.doc, "c");
assert_eq!(scritti, vec![(nodo, "impostato".to_string())]);
}
#[test]
fn timer_scatta_quando_il_tempo_avanza() {
let mut built = treebuilder::parse(
"<div id=\"t\">fermo</div><script>\
setTimeout(function () {\
document.getElementById('t').textContent = 'scattato';\
}, 100);</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
macchina.esegui(&mut built.doc, &built.scripts);
assert_eq!(testo_del_div(&built.doc, "t"), "fermo");
// il tempo lo decide il test: prima della scadenza non succede nulla
assert_eq!(macchina.pompa_timer(&mut built.doc, 50, 10), 0);
assert_eq!(testo_del_div(&built.doc, "t"), "fermo");
assert_eq!(macchina.pompa_timer(&mut built.doc, 150, 10), 1);
assert_eq!(testo_del_div(&built.doc, "t"), "scattato");
}
#[test]
fn interval_ripete_e_clear_ferma() {
let mut built = treebuilder::parse(
"<div id=\"t\">0</div><script>\
var n = 0;\
var id = setInterval(function () {\
n = n + 1;\
document.getElementById('t').textContent = String(n);\
if (n >= 3) { clearInterval(id); }\
}, 10);</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
macchina.esegui(&mut built.doc, &built.scripts);
// un tick per volta, come farebbe un vero ciclo di eventi
assert_eq!(macchina.pompa_timer(&mut built.doc, 10, 10), 1);
assert_eq!(testo_del_div(&built.doc, "t"), "1");
assert_eq!(macchina.pompa_timer(&mut built.doc, 20, 10), 1);
assert_eq!(testo_del_div(&built.doc, "t"), "2");
assert_eq!(macchina.pompa_timer(&mut built.doc, 30, 10), 1);
assert_eq!(testo_del_div(&built.doc, "t"), "3");
// dopo clearInterval non resta nulla in coda
assert_eq!(macchina.pompa_timer(&mut built.doc, 999, 10), 0);
assert_eq!(macchina.prossima_scadenza(), None);
assert_eq!(testo_del_div(&built.doc, "t"), "3");
}
#[test]
fn salto_grande_non_ripete_i_tick_persi() {
// un solo salto in avanti esegue l'intervallo una volta sola, come i browser
let mut built = treebuilder::parse(
"<div id=\"t\">0</div><script>\
var n = 0;\
setInterval(function () { n = n + 1; document.getElementById('t').textContent = String(n); }, 10);\
</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
macchina.esegui(&mut built.doc, &built.scripts);
assert_eq!(macchina.pompa_timer(&mut built.doc, 1000, 50), 1);
assert_eq!(testo_del_div(&built.doc, "t"), "1");
}
#[test]
fn prossima_scadenza_riportata_al_guscio() {
let mut built =
treebuilder::parse("<div>x</div><script>setTimeout(function () {}, 400);</script>");
let mut macchina = Macchina::nuova().expect("interprete");
macchina.esegui(&mut built.doc, &built.scripts);
macchina.pompa_timer(&mut built.doc, 0, 10);
assert_eq!(macchina.prossima_scadenza(), Some(400));
macchina.pompa_timer(&mut built.doc, 399, 10);
assert_eq!(macchina.prossima_scadenza(), Some(400));
macchina.pompa_timer(&mut built.doc, 400, 10);
assert_eq!(macchina.prossima_scadenza(), None);
}
#[test]
fn timer_che_crea_contenuto() {
let mut built = treebuilder::parse(
"<div id=\"zona\"></div><script>\
setTimeout(function () {\
var p = document.createElement('p');\
p.textContent = 'dopo 1 secondo';\
document.getElementById('zona').appendChild(p);\
}, 1000);</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
macchina.esegui(&mut built.doc, &built.scripts);
assert_eq!(testo_del_div(&built.doc, "zona"), "");
macchina.pompa_timer(&mut built.doc, 1000, 10);
assert_eq!(testo_del_div(&built.doc, "zona"), "dopo 1 secondo");
}
#[test]
fn fetch_accoda_e_la_risposta_esegue_il_callback() {
// `r.text()` restituisce una Promise, come nel browser: la catena è
// annidata, e questo test difende proprio quello (prima era sincrona)
let mut built = treebuilder::parse(
"<div id=\"t\">vuoto</div><script>\
fetch('/dati.json').then(function (r) {\
return r.text().then(function (t) {\
document.getElementById('t').textContent = 'stato ' + r.status + ': ' + t;\
});\
});</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
let errori = macchina.esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
assert_eq!(testo_del_div(&built.doc, "t"), "vuoto");
let pendenti = macchina.richieste_pendenti();
assert_eq!(pendenti.len(), 1, "{:?}", pendenti);
let (id, url, metodo, corpo) = pendenti[0].clone();
assert_eq!(url, "/dati.json");
assert_eq!(metodo, "GET");
assert!(corpo.is_none());
// la risposta la consegna il guscio: qui la inventiamo
assert_eq!(
macchina.consegna_risposta(&mut built.doc, id, 200, "ciao"),
1
);
assert_eq!(testo_del_div(&built.doc, "t"), "stato 200: ciao");
assert!(macchina.richieste_pendenti().is_empty());
}
#[test]
fn fetch_con_metodo_e_corpo() {
let mut built = treebuilder::parse(
"<div>x</div><script>fetch('/invia', { method: 'post', body: 'a=1' });</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
macchina.esegui(&mut built.doc, &built.scripts);
let pendenti = macchina.richieste_pendenti();
assert_eq!(pendenti.len(), 1);
assert_eq!(pendenti[0].2, "POST");
assert_eq!(pendenti[0].3.as_deref(), Some("a=1"));
}
#[test]
fn fetch_fallita_chiama_catch() {
let mut built = treebuilder::parse(
"<div id=\"t\">vuoto</div><script>\
fetch('/non-esiste').then(function () {\
document.getElementById('t').textContent = 'riuscita';\
}).catch(function () {\
document.getElementById('t').textContent = 'fallita';\
});</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
macchina.esegui(&mut built.doc, &built.scripts);
let id = macchina.richieste_pendenti()[0].0;
macchina.consegna_risposta(&mut built.doc, id, -1, "");
assert_eq!(testo_del_div(&built.doc, "t"), "fallita");
}
#[test]
fn insert_adjacent_html_in_tre_posizioni() {
let mut built = treebuilder::parse(
"<div id=\"p\"><span id=\"mezzo\">m</span></div><script>\
var m = document.getElementById('mezzo');\
m.insertAdjacentHTML('beforebegin', '<i>prima</i>');\
m.insertAdjacentHTML('afterend', '<i>dopo</i>');\
m.insertAdjacentHTML('beforeend', '<b>dentro</b>');</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
let p = nodo_con_id(&built.doc, "p");
let testo_p = testo_di(&built.doc, p);
assert_eq!(testo_p, "primamdentrodopo");
let mezzo = nodo_con_id(&built.doc, "mezzo");
assert_eq!(testo_di(&built.doc, mezzo), "mdentro");
}
#[test]
fn dataset_legge_gli_attributi_data() {
let mut built = treebuilder::parse(
"<div id=\"t\" data-stato=\"pronto\" data-n=\"7\">x</div><script>\
var d = document.getElementById('t').dataset;\
document.getElementById('t').textContent = d.stato + '/' + d.n;</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
assert_eq!(testo_del_div(&built.doc, "t"), "pronto/7");
}
#[test]
fn prevent_default_sopravvive_alla_propagazione() {
// il gestore sta sul form; l'evento prosegue su body e html: il flag non
// deve essere cancellato dai nodi successivi (era il difetto)
let mut built = treebuilder::parse(
"<form id=\"f\"><input type=\"submit\" value=\"Invia\"></form><script>\
document.getElementById('f').addEventListener('submit', function (ev) {\
ev.preventDefault();\
});</script>",
);
let mut macchina = Macchina::nuova().expect("interprete");
macchina.esegui(&mut built.doc, &built.scripts);
let form = nodo_con_id(&built.doc, "f");
let catena = catena_nodi(&built.doc, form);
macchina.evento(&mut built.doc, "submit", &catena, 0.0, 0.0);
assert!(
macchina.preventuto_default(),
"preventDefault perso nella propagazione"
);
}
#[test]
fn create_element_e_append_child() {
let mut built = treebuilder::parse(
"<div id=\"pai\"></div><script>\
var nuovo = document.createElement('div'); \
nuovo.setAttribute('id', 'figlio'); \
nuovo.textContent = 'costruito'; \
document.getElementById('pai').appendChild(nuovo);\
</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
assert_eq!(testo_del_div(&built.doc, "pai"), "costruito");
let figlio = nodo_con_id(&built.doc, "figlio");
assert_eq!(built.doc.element_name(figlio), Some("div"));
}
#[test]
fn create_text_node_e_remove_child() {
let mut built = treebuilder::parse(
"<div id=\"pai\"><span id=\"vecchio\">prima</span></div><script>\
var pai = document.getElementById('pai'); \
pai.removeChild(document.getElementById('vecchio')); \
pai.appendChild(document.createTextNode('solo testo'));\
</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
assert_eq!(testo_del_div(&built.doc, "pai"), "solo testo");
}
#[test]
fn elemento_costruito_con_stile() {
let mut built = treebuilder::parse(
"<div id=\"pai\"></div><script>\
var nuovo = document.createElement('p'); \
nuovo.style.color = '#00ff00'; \
nuovo.textContent = 'verde'; \
document.body.appendChild(nuovo);\
</script>",
);
let errori = esegui(&mut built.doc, &built.scripts);
assert!(errori.is_empty(), "errori: {:?}", errori);
// il testo "verde" è nel body e il paragrafo ha lo stile inline
let corpo = built
.doc
.find_element(built.doc.root(), "body")
.expect("body");
assert!(testo_di(&built.doc, corpo).contains("verde"));
let trovato = built
.doc
.nodes
.iter()
.any(|n| matches!(&n.kind, NodeKind::Element(e) if e.attr("style") == Some("color: #00ff00")));
assert!(trovato, "lo stile inline non è stato applicato");
}
#[test]
fn clic_senza_ascoltatori_non_cambia_nulla() {
let mut built = treebuilder::parse("<div id=\"t\">fermo</div><script>var x = 1;</script>");
let mut macchina = Macchina::nuova().expect("interprete");
macchina.esegui(&mut built.doc, &built.scripts);
let nodo = nodo_con_id(&built.doc, "t");
assert_eq!(macchina.clic(&mut built.doc, &[nodo], 1.0, 1.0), 0);
assert_eq!(testo_del_div(&built.doc, "t"), "fermo");
}
}