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

+107 -8
View File
@@ -93,6 +93,56 @@ fn nodo_con_id(doc: &engine::dom::Document, id: &str) -> Option<usize> {
None None
} }
/// Consegna un evento a un nodo, con la propagazione agli antenati.
fn eventi_su(
macchina: &mut engine::script::Macchina,
contenuto: &mut engine::ContenutoPagina,
nodo: usize,
tipo: &str,
) -> usize {
let rami = catena_antenati(&contenuto.doc, nodo);
macchina.evento(&mut contenuto.doc, tipo, &rami, 0.0, 0.0)
}
/// Esegue le `fetch` che gli script hanno accodato e consegna le risposte.
/// Restituisce vero se qualche callback ha modificato il DOM.
fn servi_fetch(
macchina: &mut engine::script::Macchina,
contenuto: &mut engine::ContenutoPagina,
client: &engine::net::Client,
base_url: Option<&str>,
) -> bool {
let mut cambiato = false;
for (id, riferito, metodo, corpo) in macchina.richieste_pendenti() {
// `fetch('dati.json')` è relativo al documento: si risolve come le altre risorse
let url = engine::resource::risolvi_url(base_url, &riferito).unwrap_or(riferito);
let limiti = engine::net::Limiti::default();
let esito = if metodo == "POST" {
client.post(&url, corpo.as_deref().unwrap_or(""), &limiti)
} else {
client.get(&url, &limiti)
};
let (stato, testo) = match esito {
Ok(r) => match r.text() {
Ok(t) => (r.status as i32, t),
Err(e) => {
eprintln!("mosaic: risposta illeggibile da {}: {}", url, e);
(-1, String::new())
}
},
Err(e) => {
eprintln!("mosaic: fetch {} fallita: {}", url, e);
(-1, String::new())
}
};
// la fetch può scrivere nel DOM: va contata come modifica
if macchina.consegna_risposta(&mut contenuto.doc, id, stato, &testo) > 0 {
cambiato = true;
}
}
cambiato
}
/// Ora corrente in millisecondi: è il motore a non doverla conoscere. /// Ora corrente in millisecondi: è il motore a non doverla conoscere.
fn adesso_ms() -> u64 { fn adesso_ms() -> u64 {
std::time::SystemTime::now() std::time::SystemTime::now()
@@ -236,17 +286,19 @@ fn esegui_invio(
contenuto: &mut engine::ContenutoPagina, contenuto: &mut engine::ContenutoPagina,
macchina: &mut engine::script::Macchina, macchina: &mut engine::script::Macchina,
richiesta: &engine::invio::Invio, richiesta: &engine::invio::Invio,
client: &std::rc::Rc<engine::net::Client>,
) -> Result<(), String> { ) -> Result<(), String> {
let limiti = engine::net::Limiti::default(); let limiti = engine::net::Limiti::default();
let risposta = match (&richiesta.corpo, richiesta.metodo.as_str()) { let risposta = match (&richiesta.corpo, richiesta.metodo.as_str()) {
(Some(corpo), "POST") => engine::net::post(&richiesta.url, corpo, &limiti), (Some(corpo), "POST") => client.post(&richiesta.url, corpo, &limiti),
_ => engine::net::get(&richiesta.url, &limiti), _ => client.get(&richiesta.url, &limiti),
}?; }?;
let testo = risposta.text()?; let testo = risposta.text()?;
eprintln!("mosaic: invio {} -> HTTP {}", richiesta.url, risposta.status); eprintln!("mosaic: invio {} -> HTTP {}", richiesta.url, risposta.status);
page.html = testo; page.html = testo;
page.base_url = Some(risposta.url.clone()); page.base_url = Some(risposta.url.clone());
*contenuto = engine::ContenutoPagina::da_html(&page.html); *contenuto = engine::ContenutoPagina::da_html(&page.html);
contenuto.client = Some(client.clone());
if let Ok(m) = engine::script::Macchina::nuova() { if let Ok(m) = engine::script::Macchina::nuova() {
*macchina = m; *macchina = m;
let cartella = page.base_dir.clone(); let cartella = page.base_dir.clone();
@@ -374,7 +426,16 @@ fn main() {
.map(|p| p.to_path_buf()) .map(|p| p.to_path_buf())
.unwrap_or_else(|| PathBuf::from(".")); .unwrap_or_else(|| PathBuf::from("."));
let mut page = match load(&html_path, css_path.as_deref(), &base_dir, url.as_deref()) { // client con stato di sessione: cookie e cache vivono quanto la navigazione
let client = std::rc::Rc::new(engine::net::Client::new());
let mut page = match load(
&html_path,
css_path.as_deref(),
&base_dir,
url.as_deref(),
&client,
) {
Ok(p) => p, Ok(p) => p,
Err(e) => { Err(e) => {
eprintln!("errore: {}", e); eprintln!("errore: {}", e);
@@ -385,6 +446,7 @@ fn main() {
// documento vivo: gli eventi modificano questo DOM e la pagina si ridisegna // documento vivo: gli eventi modificano questo DOM e la pagina si ridisegna
// senza ripartire dall'HTML (M2.5b) // senza ripartire dall'HTML (M2.5b)
let mut contenuto = engine::ContenutoPagina::da_html(&page.html); let mut contenuto = engine::ContenutoPagina::da_html(&page.html);
contenuto.client = Some(client.clone());
let mut macchina = match engine::script::Macchina::nuova() { let mut macchina = match engine::script::Macchina::nuova() {
Ok(m) => m, Ok(m) => m,
Err(e) => { Err(e) => {
@@ -478,7 +540,7 @@ fn main() {
} }
AzioneClic::Invia(richiesta) => { AzioneClic::Invia(richiesta) => {
eprintln!("invio del formulario: {} {}", richiesta.metodo, richiesta.url); eprintln!("invio del formulario: {} {}", richiesta.metodo, richiesta.url);
match esegui_invio(&mut page, &mut contenuto, &mut macchina, &richiesta) { match esegui_invio(&mut page, &mut contenuto, &mut macchina, &richiesta, &client) {
Ok(()) => da_ridisegnare = true, Ok(()) => da_ridisegnare = true,
Err(e) => eprintln!("mosaic: invio fallito: {}", e), Err(e) => eprintln!("mosaic: invio fallito: {}", e),
} }
@@ -491,6 +553,21 @@ fn main() {
} }
} }
} }
// le fetch accodate dagli script (anche dopo i clic) vanno eseguite
for _ in 0..4 {
if !servi_fetch(&mut macchina, &mut contenuto, &client, page.base_url.as_deref()) {
break;
}
match render_page(&page, &contenuto, size.0, size.1, zoom as f32, &font, &form)
{
Ok(nuovo) => r = nuovo,
Err(e) => {
eprintln!("errore dopo fetch: {}", e);
break;
}
}
}
if let Err(e) = pngio::write_rgba(&out, r.width, r.height, &r.rgba) { if let Err(e) = pngio::write_rgba(&out, r.width, r.height, &r.rgba) {
eprintln!("errore scrittura PNG: {}", e); eprintln!("errore scrittura PNG: {}", e);
std::process::exit(1); std::process::exit(1);
@@ -580,7 +657,7 @@ fn main() {
needs_render = true; needs_render = true;
} }
if window.is_key_pressed(Key::R, KeyRepeat::No) { if window.is_key_pressed(Key::R, KeyRepeat::No) {
if let Ok(p) = load(&html_path, css_path.as_deref(), &base_dir, url.as_deref()) { if let Ok(p) = load(&html_path, css_path.as_deref(), &base_dir, url.as_deref(), &client) {
page = p; page = p;
contenuto = engine::ContenutoPagina::da_html(&page.html); contenuto = engine::ContenutoPagina::da_html(&page.html);
if let Ok(m) = engine::script::Macchina::nuova() { if let Ok(m) = engine::script::Macchina::nuova() {
@@ -628,7 +705,7 @@ fn main() {
} }
AzioneClic::Invia(richiesta) => { AzioneClic::Invia(richiesta) => {
eprintln!("invio del formulario: {} {}", richiesta.metodo, richiesta.url); eprintln!("invio del formulario: {} {}", richiesta.metodo, richiesta.url);
match esegui_invio(&mut page, &mut contenuto, &mut macchina, &richiesta) { match esegui_invio(&mut page, &mut contenuto, &mut macchina, &richiesta, &client) {
Ok(()) => needs_render = true, Ok(()) => needs_render = true,
Err(e) => eprintln!("mosaic: invio fallito: {}", e), Err(e) => eprintln!("mosaic: invio fallito: {}", e),
} }
@@ -763,6 +840,19 @@ fn main() {
} else { } else {
form.open_select = None; form.open_select = None;
if form.focus.as_deref() != Some(f.key.as_str()) { if form.focus.as_deref() != Some(f.key.as_str()) {
// il fuoco si sposta: blur sul vecchio, focus sul nuovo
let vecchio = rendered.as_ref().and_then(|r| {
form.focus
.as_ref()
.and_then(|k| r.focusables.iter().find(|x| &x.key == k))
.map(|x| x.node)
});
if let Some(v) = vecchio {
// uscendo dal campo si segnalano blur e change
eventi_su(&mut macchina, &mut contenuto, v, "blur");
eventi_su(&mut macchina, &mut contenuto, v, "change");
}
eventi_su(&mut macchina, &mut contenuto, f.node, "focus");
form.focus = Some(f.key.clone()); form.focus = Some(f.key.clone());
if modificabile { if modificabile {
// il cursore è già stato calcolato dal punto del clic // il cursore è già stato calcolato dal punto del clic
@@ -945,6 +1035,11 @@ fn main() {
} }
for k in window.get_keys_pressed(KeyRepeat::No) { for k in window.get_keys_pressed(KeyRepeat::No) {
if let Some(c) = key_char(k, shift) { if let Some(c) = key_char(k, shift) {
// M2.5: keydown vede il tasto prima che finisca nel campo
let rami = catena_antenati(&contenuto.doc, attivo.node);
if macchina.evento_tasto(&mut contenuto.doc, &rami, &c.to_string()) > 0 {
needs_render = true;
}
inserisci(&mut testo, c, &mut caret); inserisci(&mut testo, c, &mut caret);
cambiato = true; cambiato = true;
} }
@@ -1022,10 +1117,13 @@ fn main() {
} }
} }
// timer: la pagina può cambiare anche senza che l'utente faccia nulla // timer e fetch: la pagina può cambiare senza che l'utente faccia nulla
if pompa_timer(&mut macchina, &mut contenuto, rendered.as_ref(), &mut form) { if pompa_timer(&mut macchina, &mut contenuto, rendered.as_ref(), &mut form) {
needs_render = true; needs_render = true;
} }
if servi_fetch(&mut macchina, &mut contenuto, &client, page.base_url.as_deref()) {
needs_render = true;
}
if let Some(scadenza) = macchina.prossima_scadenza() { if let Some(scadenza) = macchina.prossima_scadenza() {
let attesa = scadenza.saturating_sub(adesso_ms()).min(16); let attesa = scadenza.saturating_sub(adesso_ms()).min(16);
std::thread::sleep(std::time::Duration::from_millis(attesa.max(1))); std::thread::sleep(std::time::Duration::from_millis(attesa.max(1)));
@@ -1107,11 +1205,12 @@ fn load(
css: Option<&Path>, css: Option<&Path>,
_base: &Path, _base: &Path,
url: Option<&str>, url: Option<&str>,
client: &engine::net::Client,
) -> Result<Page, String> { ) -> Result<Page, String> {
// con --url il documento arriva dalla rete; senza, dal file // con --url il documento arriva dalla rete; senza, dal file
let html_text = match url { let html_text = match url {
Some(u) => { Some(u) => {
let risposta = engine::net::get(u, &engine::net::Limiti::default()) let risposta = client.get(u, &engine::net::Limiti::default())
.map_err(|e| format!("richiesta a {} fallita: {}", u, e))?; .map_err(|e| format!("richiesta a {} fallita: {}", u, e))?;
risposta risposta
.text() .text()
+2 -2
View File
@@ -66,8 +66,8 @@ gusci (Sailfish e desktop) ricostruiti sullo stesso motore.
| M2.2 Flexbox | `display:flex`, direzione, `justify-content`, `align-items`, `gap`, `flex-basis/grow/shrink`, wrap | **fatto** (casi 68–73) | | M2.2 Flexbox | `display:flex`, direzione, `justify-content`, `align-items`, `gap`, `flex-basis/grow/shrink`, wrap | **fatto** (casi 68–73) |
| M2.3 Tabelle | modello tabella, `colspan`, larghezze automatiche e dichiarate | **fatto** (casi 74–76); `rowspan` e `border-collapse` restano fuori | | M2.3 Tabelle | modello tabella, `colspan`, larghezze automatiche e dichiarate | **fatto** (casi 74–76); `rowspan` e `border-collapse` restano fuori |
| M2.4 Formulari | input testo/password, checkbox, radio, select, textarea, pulsanti, fuoco, tastiera virtuale | **fatto** (casi 77–80); mancano invio del form, caret/selezione, menu a comparsa | | M2.4 Formulari | input testo/password, checkbox, radio, select, textarea, pulsanti, fuoco, tastiera virtuale | **fatto** (casi 77–80); mancano invio del form, caret/selezione, menu a comparsa |
| M2.5 Scripting | motore JS `Boa`, binding DOM, event loop | **fatto in buona parte**: script inline **ed esterni** (`<script src>`, nell'ordine del documento), `getElementById`/`querySelector`/`querySelectorAll`, testo, attributi, `style` (anche `style.x = ''`), `classList`, navigazione (`parentNode`, `children`, `firstChild`, `nextSibling`, `remove`, `insertBefore`), costruzione di nodi, `innerHTML` analizzato come HTML, eventi `click`/`input`/`submit` con propagazione, `stopPropagation`, `preventDefault`, handler inline (`onclick="…"`), `element.value` in lettura e scrittura, `console.log`. **Timer** (`setTimeout`/`setInterval`/`clearTimeout`) con orologio **iniettato dal guscio**: il motore non legge mai l'ora vera, quindi i test restano deterministici. Mancano: `fetch`, `keydown`/`change`/`focus`, `insertAdjacentHTML`, `dataset` | | M2.5 Scripting | motore JS `Boa`, binding DOM, event loop | **fatto** per il perimetro dichiarato: script inline ed esterni nell'ordine del documento, `getElementById`/`querySelector`/`querySelectorAll`, testo, attributi, `dataset`, `style`, `classList`, navigazione, costruzione di nodi, `innerHTML` e `insertAdjacentHTML`, eventi `click`/`input`/`submit`/`keydown`/`focus`/`blur`/`change` con propagazione, `stopPropagation`, `preventDefault`, handler inline, `element.value`, `console.log`, timer con orologio iniettato, `fetch` con risposta consegnata dal guscio. **Fuori ambito dichiarato:** Promise vere (il `then` di `fetch` è una catena semplificata, `await` non funziona), cattura degli eventi, pseudo-classi nei selettori, `closest`, Canvas/SVG |
| M2.6 Rete | HTTP/1.1, `fetch`, cache, processo di rete separato | **fatto in parte**: `GET` su `http` e `https`, `Content-Length` e chunked, catena di reindirizzamenti, limiti di tempo e dimensione, charset dichiarato; mancano `fetch`, cookie, cache, HTTP/2 e le sotto-risorse | | M2.6 Rete | HTTP/1.1, `fetch`, cache, cookie, processo di rete separato | **fatto** per il perimetro dichiarato: `GET`/`POST` http e https con TLS, `Content-Length`/chunked, reindirizzamenti, limiti, sotto-risorse (CSS, immagini, script) con URL risolti sul documento, invio dei formulari, `Client` con **cookie** (`Set-Cookie`, `Domain`, `Path`, `Secure`, `Max-Age`, `Expires`) e **cache** con scadenza, usato da navigazione, invio, `fetch` e sotto-risorse. **Fuori ambito dichiarato:** HTTP/2 (richiede frame e HPACK: incremento a sé), processo di rete separato (serve un disegno di IPC), proxy, `multipart/form-data`. **Sul telefono** `fetch` e i cookie non sono ancora collegati al guscio: l'FFI espone il documento ma non la consegna delle risposte |
| M2.7 Compositor | tile, danni, scroll compositato, animazioni (`wgpu`) | da fare | | M2.7 Compositor | tile, danni, scroll compositato, animazioni (`wgpu`) | da fare |
### M2.6, stato preciso ### M2.6, stato preciso
+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` | | 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` | | 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` | | 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` | | 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` | | 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 | — | | WPT (`html/syntax/parsing` ≥ 90 %) | mancante | — |
+7 -1
View File
@@ -95,6 +95,8 @@ pub struct ContenutoPagina {
pub parse_errors: Vec<String>, pub parse_errors: Vec<String>,
/// tempo di parsing misurato una volta sola, riportato in ogni render /// tempo di parsing misurato una volta sola, riportato in ogni render
pub parse_ms: f64, pub parse_ms: f64,
/// client di sessione (cookie e cache) per le sotto-risorse
pub client: Option<std::rc::Rc<net::Client>>,
} }
impl ContenutoPagina { impl ContenutoPagina {
@@ -111,6 +113,7 @@ impl ContenutoPagina {
script_errors: Vec::new(), script_errors: Vec::new(),
parse_errors: built.errors, parse_errors: built.errors,
parse_ms: avvio.elapsed().as_secs_f64() * 1000.0, parse_ms: avvio.elapsed().as_secs_f64() * 1000.0,
client: None,
} }
} }
@@ -147,6 +150,7 @@ pub fn render_contenuto(
&contenuto.script_errors, &contenuto.script_errors,
&contenuto.parse_errors, &contenuto.parse_errors,
contenuto.parse_ms, contenuto.parse_ms,
contenuto.client.clone(),
css, css,
opts, opts,
form, form,
@@ -174,13 +178,15 @@ fn render_pezzi(
script_errors: &[String], script_errors: &[String],
parse_errors: &[String], parse_errors: &[String],
parse_ms: f64, parse_ms: f64,
client: Option<std::rc::Rc<net::Client>>,
css: &str, css: &str,
opts: &RenderOptions, opts: &RenderOptions,
form: &FormState, form: &FormState,
) -> Result<RenderResult, String> { ) -> Result<RenderResult, String> {
// stili esterni della pagina (`<link rel=stylesheet>`), in ordine di documento, // stili esterni della pagina (`<link rel=stylesheet>`), in ordine di documento,
// poi gli `<style>` inline: la cascata vede tutti i fogli nell'ordine giusto // 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 fogli = fogli_esterni(doc, &risorse);
let author_css = format!("{}\n{}\n{}", fogli, fogli_inline, css); let author_css = format!("{}\n{}\n{}", fogli, fogli_inline, css);
let css_viewport = opts.viewport.0 as f32 / opts.dpi_scale; 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 { pub struct Risorse {
/// indirizzo del documento, per risolvere i riferimenti relativi /// indirizzo del documento, per risolvere i riferimenti relativi
base_url: Option<String>, 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>>>>, cache: RefCell<HashMap<String, Option<Vec<u8>>>>,
errori: RefCell<Vec<String>>, errori: RefCell<Vec<String>>,
} }
@@ -27,11 +29,19 @@ impl Risorse {
pub fn new(base_url: Option<String>) -> Self { pub fn new(base_url: Option<String>) -> Self {
Risorse { Risorse {
base_url, base_url,
client: None,
cache: RefCell::new(HashMap::new()), cache: RefCell::new(HashMap::new()),
errori: RefCell::new(Vec::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 { pub fn ha_rete(&self) -> bool {
self.base_url.is_some() self.base_url.is_some()
} }
@@ -61,7 +71,11 @@ impl Risorse {
fn leggi_davvero(&self, riferito: &str, cartella: &std::path::Path) -> Option<Vec<u8>> { fn leggi_davvero(&self, riferito: &str, cartella: &std::path::Path) -> Option<Vec<u8>> {
let url = self.risolvi(riferito)?; 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) => { Ok(r) if (200..300).contains(&r.status) => {
if r.body.len() > MAX_SOTTO_RISORSA { if r.body.len() > MAX_SOTTO_RISORSA {
self.errori self.errori
+18
View File
@@ -102,4 +102,22 @@ impl Macchina {
pub fn prossima_scadenza(&mut self) -> Option<u64> { pub fn prossima_scadenza(&mut self) -> Option<u64> {
None 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), Valore(usize, String),
/// `innerHTML = ...`: il testo va analizzato come HTML /// `innerHTML = ...`: il testo va analizzato come HTML
Html(usize, String), Html(usize, String),
/// `insertAdjacentHTML(dove, html)`
HtmlAccanto(usize, String, String),
} }
#[derive(Default)] #[derive(Default)]
@@ -169,6 +171,64 @@ function __timer_prossimo() {
return minimo; 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 = { var console = {
log: function () { log: function () {
var pezzi = []; var pezzi = [];
@@ -261,6 +321,10 @@ function __wrap(n) {
return figlio; return figlio;
}, },
remove: function () { __togli_se(n); }, 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) { querySelector: function (s) {
var trovato = __selettore_uno(n, String(s)); var trovato = __selettore_uno(n, String(s));
return trovato < 0 ? null : __wrap(trovato); 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 /* Consegna l'evento agli ascoltatori registrati e all'eventuale attributo
inline (`onclick="..."`). Restituisce quanti gestori sono stati eseguiti. */ 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 quanti = 0;
var el = __wrap(n); var el = __wrap(n);
var ev = { var ev = {
@@ -316,6 +380,8 @@ function __dispatch(n, tipo, x, y) {
currentTarget: el, currentTarget: el,
clientX: x, clientX: x,
clientY: y, clientY: y,
key: (typeof tasto === 'string') ? tasto : '',
keyCode: (typeof tasto === 'string' && tasto.length === 1) ? tasto.charCodeAt(0) : 0,
defaultPrevented: false, defaultPrevented: false,
preventDefault: function () { this.defaultPrevented = true; __preventuto = true; }, preventDefault: function () { this.defaultPrevented = true; __preventuto = true; },
stopPropagation: function () { __ferma = true; } stopPropagation: function () { __ferma = true; }
@@ -610,6 +676,34 @@ fn html(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValu
Ok(JsValue::undefined()) 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. /// `__inline(n, tipo)`: codice dell'attributo `onclick`/`oninput`/…, o null.
fn inline(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> { fn inline(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let nodo = argomento_nodo(args, ctx, 0); let nodo = argomento_nodo(args, ctx, 0);
@@ -995,6 +1089,60 @@ fn applica(doc: &mut Document, ops: Vec<Op>) {
let n = risolvi(&mappa, nodo); let n = risolvi(&mappa, nodo);
SCRITTI.with(|s| s.borrow_mut().push((n, testo))); 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) => { Op::Html(nodo, testo) => {
let n = risolvi(&mappa, nodo); let n = risolvi(&mappa, nodo);
if n < doc.nodes.len() { 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) { fn copia_nodo(sorgente: &Document, destinazione: &mut Document, nodo: usize, padre: usize) {
use crate::dom::NodeKind as K; use crate::dom::NodeKind as K;
let nuovo = match &sorgente.node(nodo).kind { let nuovo = match &sorgente.node(nodo).kind {
@@ -1163,6 +1332,8 @@ impl Macchina {
("__selettore_uno", 2, selettore_uno), ("__selettore_uno", 2, selettore_uno),
("__selettori", 2, selettori), ("__selettori", 2, selettori),
("__adesso", 0, adesso), ("__adesso", 0, adesso),
("__html_accanto", 3, html_accanto),
("__dati", 1, elenco_dati),
]; ];
for (nome, arita, f) in registrazioni { for (nome, arita, f) in registrazioni {
ctx.register_global_builtin_callable( ctx.register_global_builtin_callable(
@@ -1309,6 +1480,62 @@ impl Macchina {
eseguiti 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. /// Prima scadenza futura secondo l'orologio del guscio, se c'è un timer in coda.
pub fn prossima_scadenza(&mut self) -> Option<u64> { pub fn prossima_scadenza(&mut self) -> Option<u64> {
match self.ctx.eval(Source::from_bytes("__timer_prossimo()")) { match self.ctx.eval(Source::from_bytes("__timer_prossimo()")) {
@@ -1329,6 +1556,40 @@ impl Macchina {
.unwrap_or(false) .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. /// Scorciatoia per l'evento più usato.
pub fn clic(&mut self, doc: &mut Document, catena: &[usize], x: f32, y: f32) -> usize { pub fn clic(&mut self, doc: &mut Document, catena: &[usize], x: f32, y: f32) -> usize {
self.evento(doc, "click", catena, x, y) self.evento(doc, "click", catena, x, y)
@@ -1791,6 +2052,95 @@ mod tests {
assert_eq!(testo_del_div(&built.doc, "zona"), "dopo 1 secondo"); 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] #[test]
fn prevent_default_sopravvive_alla_propagazione() { fn prevent_default_sopravvive_alla_propagazione() {
// il gestore sta sul form; l'evento prosegue su body e html: il flag non // il gestore sta sul form; l'evento prosegue su body e html: il flag non
+6 -1
View File
@@ -1,6 +1,6 @@
Name: harbour-mosaic Name: harbour-mosaic
Summary: Mosaic browser with an independent rendering engine Summary: Mosaic browser with an independent rendering engine
Version: 0.8.5 Version: 0.8.6
Release: 1 Release: 1
Group: Qt/Qt Group: Qt/Qt
License: MIT License: MIT
@@ -21,6 +21,11 @@ engine written from scratch (no WebKit, Blink, Gecko or Servo code).
Milestone M0: HTML parsing, CSS cascade, block layout and CPU raster. Milestone M0: HTML parsing, CSS cascade, block layout and CPU raster.
%changelog %changelog
* Thu Nov 12 2026 Carlo Baratto <carlo@carlobaratto.it> - 0.8.6-1
- Motore allineato: fetch con risposte consegnate dal guscio, dataset,
insertAdjacentHTML, eventi di tastiera e di fuoco, cookie e cache nel client
di sessione anche per le sotto-risorse
* Thu Nov 12 2026 Carlo Baratto <carlo@carlobaratto.it> - 0.8.5-1 * Thu Nov 12 2026 Carlo Baratto <carlo@carlobaratto.it> - 0.8.5-1
- Allineamento al motore: JavaScript sul telefono (script inline ed esterni, - Allineamento al motore: JavaScript sul telefono (script inline ed esterni,
eventi al tocco, timer), sotto-risorse dalla rete grazie all'indirizzo del eventi al tocco, timer), sotto-risorse dalla rete grazie all'indirizzo del