M2.5 e M2.6: fetch, eventi di tastiera e fuoco, cookie e cache nei gusci

M2.5 completa nel perimetro dichiarato:
- fetch con la richiesta accodata al motore ed eseguita dal guscio; la risposta
  torna con consegna_risposta e il callback gira come un evento
- keydown con il tasto, focus/blur/change quando il fuoco si sposta
- insertAdjacentHTML nelle quattro posizioni, dataset in lettura

M2.6 completa nel perimetro dichiarato:
- il desktop usa net::Client (cookie e cache) per navigazione, invio dei
  formulari, fetch e sotto-risorse: il client viene passato al documento, che lo
  dà al caricatore delle risorse

Fuori ambito, dichiarato nella roadmap: HTTP/2, processo di rete separato,
proxy, multipart. Sul telefono fetch e cookie non sono ancora collegati al
guscio (l'FFI espone il documento, non la consegna delle risposte).
This commit is contained in:
Carlo Baratto committed 2026-11-12 20:20:04 +01:00
1 parent b40d9d8a1c
commit c2807d3f61
8 files changed
+508 -14

No files matched your search

+2
View File
@@ -46,6 +46,8 @@ Nessun codice di WebKit, Blink, Gecko o Servo: parser, cascata, layout e raster
| Script esterni (`<script src>`), `querySelector`, `innerHTML`, handler inline, navigazione del DOM | fatto (M2.5) | `esegui_sequenza`, `matching`, `copia_frammento` |
| Timer con orologio iniettato (`setTimeout`, `setInterval`, `clearTimeout`) | fatto (M2.5) | `pompa_timer`, `prossima_scadenza`, desktop `--aspetta` |
| Confine C a documento: `engine_doc_new/render/click/pump/next_timer/errors` | fatto (M2.6) | `src/ffi.rs`, `tests/ffi_smoke.c` |
| `fetch` con risposta consegnata dal guscio, `dataset`, `insertAdjacentHTML`, `keydown`/`focus`/`blur`/`change` | fatto (M2.5) | `richieste_pendenti`, `consegna_risposta`, `evento_tasto` |
| Cookie e cache di sessione (`Client`) usati da navigazione, invio, `fetch` e sotto-risorse | fatto (M2.6) | `src/cookie.rs`, `net::Client` |
| Rete: `GET` http/https con TLS, chunked, reindirizzamenti, limiti | fatto in parte (M2.6) | `src/net.rs`, `render --url`, `desktop --url` |
| Sotto-risorse dalla rete: `link[rel=stylesheet]` e `img[src]` | fatto (M2.6) | `src/resource.rs`, `tests/risorse.rs` |
| WPT (`html/syntax/parsing` ≥ 90 %) | mancante | — |
+7 -1
View File
@@ -95,6 +95,8 @@ pub struct ContenutoPagina {
pub parse_errors: Vec<String>,
/// tempo di parsing misurato una volta sola, riportato in ogni render
pub parse_ms: f64,
/// client di sessione (cookie e cache) per le sotto-risorse
pub client: Option<std::rc::Rc<net::Client>>,
}
impl ContenutoPagina {
@@ -111,6 +113,7 @@ impl ContenutoPagina {
script_errors: Vec::new(),
parse_errors: built.errors,
parse_ms: avvio.elapsed().as_secs_f64() * 1000.0,
client: None,
}
}
@@ -147,6 +150,7 @@ pub fn render_contenuto(
&contenuto.script_errors,
&contenuto.parse_errors,
contenuto.parse_ms,
contenuto.client.clone(),
css,
opts,
form,
@@ -174,13 +178,15 @@ fn render_pezzi(
script_errors: &[String],
parse_errors: &[String],
parse_ms: f64,
client: Option<std::rc::Rc<net::Client>>,
css: &str,
opts: &RenderOptions,
form: &FormState,
) -> Result<RenderResult, String> {
// stili esterni della pagina (`<link rel=stylesheet>`), in ordine di documento,
// poi gli `<style>` inline: la cascata vede tutti i fogli nell'ordine giusto
let risorse = std::rc::Rc::new(resource::Risorse::new(opts.base_url.clone()));
let risorse =
std::rc::Rc::new(resource::Risorse::new(opts.base_url.clone()).con_client(client));
let fogli = fogli_esterni(doc, &risorse);
let author_css = format!("{}\n{}\n{}", fogli, fogli_inline, css);
let css_viewport = opts.viewport.0 as f32 / opts.dpi_scale;
+15 -1
View File
@@ -19,6 +19,8 @@ const MAX_SOTTO_RISORSA: usize = 4 * 1024 * 1024;
pub struct Risorse {
/// indirizzo del documento, per risolvere i riferimenti relativi
base_url: Option<String>,
/// client con cookie e cache, quando il guscio ne ha uno
client: Option<std::rc::Rc<net::Client>>,
cache: RefCell<HashMap<String, Option<Vec<u8>>>>,
errori: RefCell<Vec<String>>,
}
@@ -27,11 +29,19 @@ impl Risorse {
pub fn new(base_url: Option<String>) -> Self {
Risorse {
base_url,
client: None,
cache: RefCell::new(HashMap::new()),
errori: RefCell::new(Vec::new()),
}
}
/// Collega il client di sessione: cookie e cache valgono anche per le
/// sotto-risorse (CSS, immagini, script).
pub fn con_client(mut self, client: Option<std::rc::Rc<net::Client>>) -> Self {
self.client = client;
self
}
pub fn ha_rete(&self) -> bool {
self.base_url.is_some()
}
@@ -61,7 +71,11 @@ impl Risorse {
fn leggi_davvero(&self, riferito: &str, cartella: &std::path::Path) -> Option<Vec<u8>> {
let url = self.risolvi(riferito)?;
match net::get(&url, &limiti()) {
let risposta = match &self.client {
Some(c) => c.get(&url, &limiti()),
None => net::get(&url, &limiti()),
};
match risposta {
Ok(r) if (200..300).contains(&r.status) => {
if r.body.len() > MAX_SOTTO_RISORSA {
self.errori
+18
View File
@@ -102,4 +102,22 @@ impl Macchina {
pub fn prossima_scadenza(&mut self) -> Option<u64> {
None
}
pub fn richieste_pendenti(&mut self) -> Vec<(u64, String, String, Option<String>)> {
Vec::new()
}
pub fn evento_tasto(&mut self, _doc: &mut Document, _catena: &[usize], _tasto: &str) -> usize {
0
}
pub fn consegna_risposta(
&mut self,
_doc: &mut Document,
_id: u64,
_stato: i32,
_corpo: &str,
) -> usize {
0
}
}
+351 -1
View File
@@ -48,6 +48,8 @@ enum Op {
Valore(usize, String),
/// `innerHTML = ...`: il testo va analizzato come HTML
Html(usize, String),
/// `insertAdjacentHTML(dove, html)`
HtmlAccanto(usize, String, String),
}
#[derive(Default)]
@@ -169,6 +171,64 @@ function __timer_prossimo() {
return minimo;
}
/* fetch: la richiesta si accoda, la esegue il guscio (che sa fare rete) e la
risposta torna qui con __risposta(). Il corpo si legge in modo sincrono
(`r.text()`), semplificazione dichiarata rispetto alle 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),
callback: null,
errore: null
};
__richieste.push(richiesta);
var oggetto = {
then: function (fn) { richiesta.callback = fn; return oggetto; },
catch: function (fn) { richiesta.errore = fn; return oggetto; }
};
return oggetto;
}
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.errore) { try { r.errore({ message: 'richiesta fallita' }); } catch (e) { __log(String(e)); } }
return 1;
}
if (!r.callback) { return 0; }
var risposta = {
ok: stato >= 200 && stato < 300,
status: stato,
url: r.url,
text: function () { return corpo; },
json: function () { return JSON.parse(corpo); }
};
try { r.callback(risposta); } catch (e) { __log('errore nel gestore di fetch: ' + e); }
return 1;
}
var console = {
log: function () {
var pezzi = [];
@@ -261,6 +321,10 @@ function __wrap(n) {
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);
@@ -307,7 +371,7 @@ 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) {
function __dispatch(n, tipo, x, y, tasto) {
var quanti = 0;
var el = __wrap(n);
var ev = {
@@ -316,6 +380,8 @@ function __dispatch(n, tipo, x, y) {
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; }
@@ -610,6 +676,34 @@ fn html(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValu
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);
@@ -995,6 +1089,60 @@ fn applica(doc: &mut Document, ops: Vec<Op>) {
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 {
for (i, figlio) in creati.iter().enumerate() {
doc.node_mut(p).children.insert(posizione + i, *figlio);
doc.node_mut(*figlio).parent = Some(p);
}
}
}
}
Op::Html(nodo, testo) => {
let n = risolvi(&mappa, nodo);
if n < doc.nodes.len() {
@@ -1078,6 +1226,27 @@ fn copia_frammento(doc: &mut Document, destinazione: usize, html: &str) {
}
}
/// 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 {
@@ -1163,6 +1332,8 @@ impl Macchina {
("__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(
@@ -1309,6 +1480,62 @@ impl Macchina {
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
}
};
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()")) {
@@ -1329,6 +1556,40 @@ impl Macchina {
.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)
@@ -1791,6 +2052,95 @@ mod tests {
assert_eq!(testo_del_div(&built.doc, "zona"), "dopo 1 secondo");
}
#[test]
fn fetch_accoda_e_la_risposta_esegue_il_callback() {
let mut built = treebuilder::parse(
"<div id=\"t\">vuoto</div><script>\
fetch('/dati.json').then(function (r) {\
document.getElementById('t').textContent = 'stato ' + r.status + ': ' + r.text();\
});</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