Scripting: script esterni, selettori, handler inline e completamenti del DOM

A - ciò che rende viva una pagina vera:
- <script src="...">: sequenza ordinata di script inline ed esterni, caricati
  dalla rete o dal disco secondo il contesto del documento
- querySelector/querySelectorAll su documento ed elemento: tag, #id, .classe,
  [attributo] e discendenza
- attributi onclick (e ogni on<evento>) eseguiti con new Function, con 'this'
  legato all'elemento
- innerHTML in scrittura ora analizza l'HTML, invece di mostrare i tag

B - completamenti:
- navigazione: parentNode, children, firstChild, nextSibling, remove, insertBefore
- stopPropagation: ferma davvero la risalita agli antenati
- element.value anche in scrittura, riportato allo stato dei moduli dal guscio
- console.log raccolto e stampato con MOSAIC_JS_LOG=1
- style.prop = '' toglie la dichiarazione, come in HTML

Corretti: nome con accento sbagliato tra preludio e Rust (remove non
funzionava); albero dei selettori costruito solo per gli elementi, quindi la
radice non aveva figli e ogni query restituiva vuoto; flag di ridisegno
azzerato subito dopo il render, che annullava i valori impostati dagli script
al caricamento.
This commit is contained in:
Carlo Baratto committed 2026-11-12 19:26:56 +01:00
1 parent 577682ae22
commit 94faf56304
9 files changed
+973 -39

No files matched your search

+751 -21
View File
@@ -40,6 +40,14 @@ enum Op {
/// (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),
}
#[derive(Default)]
@@ -54,6 +62,14 @@ struct Stato {
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
@@ -68,6 +84,8 @@ thread_local! {
/// 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());
/// 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`),
@@ -78,6 +96,26 @@ 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;
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]; }
@@ -100,17 +138,37 @@ function __wrap(n) {
var el = {
nodeIndex: n,
get value() { return __valore(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) { __scrivi(n, String(v)); },
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 });
@@ -122,11 +180,27 @@ function __wrap(n) {
__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); },
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') || ''; },
@@ -143,33 +217,53 @@ var document = {
},
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()); }
};
/* Chiamata dal motore: consegna l'evento agli ascoltatori di un nodo.
Restituisce quanti gestori sono stati eseguiti; la propagazione agli antenati
la decide il motore, che conosce l'albero. */
/* Il motore azzera il flag una volta per evento: se lo facesse `__dispatch`,
/* 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; }
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) {
var quanti = 0;
var el = __wrap(n);
var ev = {
type: tipo,
target: el,
currentTarget: el,
clientX: x,
clientY: y,
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; }
var ev = {
type: tipo,
target: el,
currentTarget: el,
clientX: x,
clientY: y,
defaultPrevented: false,
preventDefault: function () { this.defaultPrevented = true; __preventuto = true; },
stopPropagation: function () {}
};
a.fn.call(el, ev);
quanti++;
}
@@ -360,6 +454,340 @@ fn corpo(_this: &JsValue, _args: &[JsValue], _ctx: &mut Context) -> JsResult<JsV
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())
}
/// `__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(),
})
}
/// `__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);
@@ -391,6 +819,13 @@ fn testo_di(doc: &Document, nodo: usize) -> String {
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;
@@ -402,6 +837,7 @@ fn prepara(doc: &Document) {
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());
@@ -423,6 +859,8 @@ 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)
};
@@ -445,6 +883,48 @@ fn applica(doc: &mut Document, ops: Vec<Op>) {
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::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);
@@ -506,6 +986,40 @@ fn applica(doc: &mut Document, ops: Vec<Op>) {
}
}
/// 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);
}
}
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();
@@ -517,13 +1031,16 @@ fn fondi_stile(esistente: &str, prop: &str, valore: &str) -> String {
}
match d.split_once(':') {
Some((k, _)) if k.trim().eq_ignore_ascii_case(prop) => {
pezzi.push(format!("{}: {}", prop, valore));
// `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 {
if !trovato && !valore.trim().is_empty() {
pezzi.push(format!("{}: {}", prop, valore));
}
pezzi.join("; ")
@@ -541,7 +1058,7 @@ impl Macchina {
/// Costruisce l'interprete con il preludio DOM già valutato.
pub fn nuova() -> Result<Macchina, String> {
let mut ctx = Context::default();
let registrazioni: [(&str, usize, FunzioneOspite); 16] = [
let registrazioni: Vec<(&str, usize, FunzioneOspite)> = vec![
("__find", 1, trova),
("__leggi", 1, leggi),
("__scrivi", 2, scrivi),
@@ -558,6 +1075,17 @@ impl Macchina {
("__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),
];
for (nome, arita, f) in registrazioni {
ctx.register_global_builtin_callable(
@@ -578,6 +1106,43 @@ impl Macchina {
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);
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));
}
}
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();
@@ -612,7 +1177,18 @@ impl Macchina {
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,
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);
@@ -625,6 +1201,17 @@ impl Macchina {
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())
}
/// Vero se l'ultimo evento consegnato è stato annullato con `preventDefault`.
pub fn preventuto_default(&mut self) -> bool {
self.ctx
@@ -859,6 +1446,149 @@ mod tests {
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 prevent_default_sopravvive_alla_propagazione() {
// il gestore sta sul form; l'evento prosegue su body e html: il flag non