Mosaic: motore di rendering proprio, gusci desktop e Sailfish
Primo commit del progetto: motore Rust con parser HTML, cascata CSS, layout, raster CPU, formulari, bidi, flex, tabelle, JavaScript (Boa) con eventi e costruzione di nodi, rete HTTP/HTTPS con TLS, sotto-risorse, invio dei formulari; guscio grafico per Sailfish (QML/Silica) e per desktop (minifb, distribuito come AppImage), con 11 documenti di specifica e 91 casi di reftest.
This commit is contained in:
commit
577682ae22
173 files changed
+23685
No files matched your search
@@ -0,0 +1,949 @@
|
||||
//! 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),
|
||||
}
|
||||
|
||||
#[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>,
|
||||
/// 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());
|
||||
}
|
||||
|
||||
/// 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;
|
||||
|
||||
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 value() { return __valore(n); },
|
||||
get textContent() { return __leggi(n); },
|
||||
set textContent(v) { __scrivi(n, String(v)); },
|
||||
get innerHTML() { return __leggi(n); },
|
||||
set innerHTML(v) { __scrivi(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)); },
|
||||
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;
|
||||
},
|
||||
removeChild: function (figlio) {
|
||||
if (!figlio) { return null; }
|
||||
__rimuovi(n, figlio.nodeIndex);
|
||||
return figlio;
|
||||
},
|
||||
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))); },
|
||||
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`,
|
||||
la propagazione al secondo nodo cancellerebbe il preventDefault del primo. */
|
||||
function __azzera_preventuto() { __preventuto = false; }
|
||||
|
||||
function __dispatch(n, tipo, x, y) {
|
||||
var quanti = 0;
|
||||
var el = __wrap(n);
|
||||
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++;
|
||||
}
|
||||
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))
|
||||
}
|
||||
|
||||
/// `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() {
|
||||
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));
|
||||
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();
|
||||
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::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(" "));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) => {
|
||||
pezzi.push(format!("{}: {}", prop, valore));
|
||||
trovato = true;
|
||||
}
|
||||
_ => pezzi.push(d.to_string()),
|
||||
}
|
||||
}
|
||||
if !trovato {
|
||||
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: [(&str, usize, FunzioneOspite); 16] = [
|
||||
("__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),
|
||||
];
|
||||
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 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));
|
||||
}
|
||||
}
|
||||
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,
|
||||
Err(e) => {
|
||||
// un gestore rotto non deve fermare la pagina
|
||||
eprintln!("mosaic: errore nel gestore di clic: {}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
|
||||
applica(doc, ops);
|
||||
eseguiti
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// 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 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");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user