1use super::*;
3
4pub(crate) const DOCUMENT_REFERRER_KEY: &str = "\u{0}document.referrer";
6
7impl JsRuntime {
8 pub fn set_document_ready_state(&mut self, state: &str) {
15 let doc = scope_get(&self.global, "document");
16 if let Some(Value::Object(d)) = &doc {
17 d.borrow_mut().props.insert("readyState".into(), Value::str(state));
18 }
19 if state == "loading" {
20 return;
21 }
22 let rsc = self.window_listeners("_evt_readystatechange_listeners");
23 self.fire_window_listeners(&rsc, "readystatechange", &[]);
24 if let Some(d) = &doc {
25 self.call_on_handler(d, "onreadystatechange", "readystatechange");
26 }
27 let (key, ty) = if state == "interactive" {
28 ("_evt_DOMContentLoaded_listeners", "DOMContentLoaded")
29 } else {
30 ("_evt_load_listeners", "load")
31 };
32 if ty == "load" {
33 let iframes: Vec<usize> = {
34 let dom = self.dom().borrow();
35 dom.tree_order()
36 .into_iter()
37 .filter(|&i| {
38 dom.nodes
39 .get(i)
40 .is_some_and(|n| !n.is_text && n.tag == "iframe" && n.attrs.contains_key("_iframe_loaded"))
41 })
42 .collect()
43 };
44 if !iframes.is_empty() {
45 let mut it = self.new_interp();
46 for fi in iframes {
47 let _ = it.dispatch_event_object(fi, "load", &[], None);
48 }
49 it.run_event_loop();
50 self.out.push_str(&it.out);
51 }
52 }
53 let l = self.window_listeners(key);
54 self.fire_window_listeners(&l, ty, &[]);
55 if ty == "load" {
56 if let Some(w) = scope_get(&self.global, "window") {
57 let has_prop = matches!(&w, Value::Object(o) if matches!(o.borrow().props.get("onload"), Some(Value::Object(_))));
58 if has_prop {
59 self.call_on_handler(&w, "onload", "load");
60 } else {
61 let code = {
65 let dom = self.dom().borrow();
66 dom.tree_order()
67 .into_iter()
68 .find(|&i| dom.nodes.get(i).is_some_and(|n| !n.is_text && n.tag == "body"))
69 .and_then(|i| dom.get_attr(i, "onload"))
70 };
71 if let Some(code) = code.filter(|c| !c.trim().is_empty()) {
72 let wrapped = alloc::format!("(function(event){{\n{}\n}})", code);
73 let ev = Obj::plain();
74 ev.borrow_mut().props.insert("type".into(), Value::str("load"));
75 let mut it = self.new_interp();
76 match it.eval_source(&wrapped) {
77 Ok(f @ Value::Object(_)) => {
78 it.call_listener(&f, w.clone(), &[Value::Object(ev)], "onload attribute");
79 }
80 Err(thrown) => it.report_uncaught("onload attribute", &thrown),
81 _ => {}
82 }
83 it.run_event_loop();
84 self.out.push_str(&it.out);
85 }
86 }
87 }
88 }
89 if let Some(Value::Object(w)) = scope_get(&self.global, "window") {
91 let mut wb = w.borrow_mut();
92 wb.props.shift_remove(key);
93 if state == "complete" {
94 wb.props.shift_remove("_evt_readystatechange_listeners");
95 }
96 }
97 }
98
99 pub fn set_current_script(&mut self, script_node_idx: Option<usize>) {
103 let doc = scope_get(&self.global, "document");
104 if let Some(Value::Object(d)) = &doc {
105 let val = match script_node_idx {
106 Some(idx) => Value::Object(Obj::dom(idx)),
107 None => Value::Null,
108 };
109 d.borrow_mut().props.insert("currentScript".into(), val);
110 }
111 }
112
113 fn call_on_handler(&mut self, obj: &Value, prop: &str, ty: &str) {
115 let f = match obj {
116 Value::Object(o) => o.borrow().props.get(prop).cloned(),
117 _ => None,
118 };
119 if let Some(f @ Value::Object(_)) = f {
120 let ev = Obj::plain();
121 ev.borrow_mut().props.insert("type".into(), Value::str(ty));
122 let mut it = self.new_interp();
123 it.call_listener(&f, obj.clone(), &[Value::Object(ev)], ty);
124 it.run_event_loop();
125 self.out.push_str(&it.out);
126 }
127 }
128
129 pub(crate) fn install_preludes(&mut self) {
131 const BOOT: &str = include_str!("../prelude/lazy_boot.js");
132 let mut interp = self.new_interp();
133 let window = self.global.borrow().vars.get("window").cloned().unwrap_or(Value::Undefined);
134 let installer = Value::Object(Obj::native("installPrelude", prelude_install));
135 let groups = Obj::plain();
136 for (grp, names) in PRELUDE_GROUPS {
137 let list: Vec<Value> = names.iter().map(|n| Value::str(*n)).collect();
138 groups.borrow_mut().props.insert((*grp).into(), Value::Object(Obj::array(list)));
139 }
140 match interp.eval_source(BOOT) {
141 Ok(f) => {
142 if let Err(e) = interp.call_value(&f, Value::Undefined, &[window, installer, Value::Object(groups)]) {
143 crate::warn!("[JS] prelude の仕掛けの実行に失敗: {}", e.to_js_string().chars().take(160).collect::<String>());
144 }
145 }
146 Err(e) => crate::warn!("[JS] prelude の仕掛けの評価に失敗: {}", e.to_js_string().chars().take(160).collect::<String>()),
147 }
148 let names: Vec<String> = self.global.borrow().vars.keys().map(|k| String::from(k.as_ref())).collect();
150 self.dom().borrow_mut().builtin_global_names = names;
151 }
152
153 pub fn set_page_url(&mut self, url: &str) {
156 self.base_url = String::from(url);
157 super::super::builtins::update_location(&self.global, url);
158 }
159
160 pub fn location_href(&self) -> Option<String> {
162 super::super::builtins::location_href(&self.global)
163 }
164
165 pub fn set_referrer(&mut self, referrer: &str) {
167 self.global
168 .borrow_mut()
169 .vars
170 .insert(DOCUMENT_REFERRER_KEY.into(), Value::str(referrer));
171 }
172
173 pub fn set_frame_depth(&mut self, depth: u32) {
176 super::super::builtins::configure_frame_depth(&self.global, depth);
177 }
178
179 pub fn deliver_message(&mut self, data: Value, origin: &str) {
182 let mut interp = self.new_interp();
183 super::super::builtins::deliver_window_message(&mut interp, data, origin);
184 interp.run_event_loop();
185 self.out.push_str(&interp.out);
186 }
187
188 pub fn dispatch_click(&mut self, node_idx: usize) -> bool {
191 self.dispatch_event_with(node_idx, "click", &[]).0
192 }
193
194 pub fn dispatch_event(&mut self, node_idx: usize, event_type: &str) -> bool {
196 if matches!(event_type, "input" | "change") {
204 self.dom().borrow_mut().set_attr(node_idx, "_user_interacted", "1");
205 }
206 self.dispatch_event_with(node_idx, event_type, &[]).0
207 }
208
209 pub fn dispatch_mouse(
212 &mut self,
213 node_idx: usize,
214 event_type: &str,
215 x: i32,
216 y: i32,
217 ) -> (bool, bool) {
218 self.dispatch_mouse_full(node_idx, event_type, x, y, 0, 0)
219 }
220
221 pub fn dispatch_mouse_full(
226 &mut self,
227 node_idx: usize,
228 event_type: &str,
229 x: i32,
230 y: i32,
231 button: i32,
232 wheel_delta: i32,
233 ) -> (bool, bool) {
234 let buttons = match event_type {
236 "mousedown" => match button {
237 0 => 1,
238 2 => 2,
239 1 => 4,
240 _ => 0,
241 },
242 _ => 0,
243 };
244 let detail = match event_type {
246 "click" | "mousedown" | "mouseup" => 1.0,
247 "dblclick" => 2.0,
248 _ => 0.0,
249 };
250 let (ox, oy) = (x, y);
253 let mut extra = alloc::vec![
254 (String::from("clientX"), Value::Number(x as f64)),
255 (String::from("clientY"), Value::Number(y as f64)),
256 (String::from("pageX"), Value::Number(x as f64)),
257 (String::from("pageY"), Value::Number(y as f64)),
258 (String::from("screenX"), Value::Number(x as f64)),
259 (String::from("screenY"), Value::Number(y as f64)),
260 (String::from("offsetX"), Value::Number(ox as f64)),
261 (String::from("offsetY"), Value::Number(oy as f64)),
262 (String::from("movementX"), Value::Number(0.0)),
263 (String::from("movementY"), Value::Number(0.0)),
264 (String::from("button"), Value::Number(button as f64)),
265 (String::from("buttons"), Value::Number(buttons as f64)),
266 (String::from("detail"), Value::Number(detail)),
267 ];
268 if event_type == "wheel" {
270 extra.push((String::from("deltaX"), Value::Number(0.0)));
271 extra.push((
272 String::from("deltaY"),
273 Value::Number((wheel_delta * 100) as f64),
274 ));
275 extra.push((String::from("deltaZ"), Value::Number(0.0)));
276 extra.push((String::from("deltaMode"), Value::Number(0.0))); }
278 Self::push_modifier_props(&mut extra);
279 self.dispatch_event_with(node_idx, event_type, &extra)
280 }
281
282 fn push_modifier_props(extra: &mut Vec<(String, Value)>) {
284 extra.push((
285 String::from("shiftKey"),
286 Value::Bool(crate::os_lib::platform::shift_down()),
287 ));
288 extra.push((
289 String::from("ctrlKey"),
290 Value::Bool(crate::os_lib::platform::ctrl_down()),
291 ));
292 extra.push((
293 String::from("altKey"),
294 Value::Bool(crate::os_lib::platform::alt_down()),
295 ));
296 extra.push((
297 String::from("metaKey"),
298 Value::Bool(crate::os_lib::platform::meta_down()),
299 ));
300 }
301
302 pub fn dispatch_key(&mut self, node_idx: usize, event_type: &str, key: &str) -> (bool, bool) {
306 self.dispatch_key_full(node_idx, event_type, key, false)
307 }
308
309 pub fn dispatch_key_full(
312 &mut self,
313 node_idx: usize,
314 event_type: &str,
315 key: &str,
316 repeat: bool,
317 ) -> (bool, bool) {
318 let (key_code, code, location) = Self::key_attributes(key);
319 let mut extra = alloc::vec![
320 (String::from("key"), Value::str(key)),
321 (String::from("keyCode"), Value::Number(key_code as f64)),
322 (String::from("which"), Value::Number(key_code as f64)),
323 (
324 String::from("charCode"),
325 Value::Number(if event_type == "keypress" {
326 key_code as f64
327 } else {
328 0.0
329 })
330 ),
331 (String::from("code"), Value::str(&code)),
332 (String::from("location"), Value::Number(location as f64)),
333 (String::from("repeat"), Value::Bool(repeat)),
334 ];
335 Self::push_modifier_props(&mut extra);
336 self.dispatch_event_with(node_idx, event_type, &extra)
337 }
338
339 fn key_attributes(key: &str) -> (u32, String, u32) {
342 match key {
344 "Enter" => (13, String::from("Enter"), 0),
345 "Tab" => (9, String::from("Tab"), 0),
346 "Backspace" => (8, String::from("Backspace"), 0),
347 "Escape" => (27, String::from("Escape"), 0),
348 " " => (32, String::from("Space"), 0),
349 "Delete" => (46, String::from("Delete"), 0),
350 "ArrowLeft" => (37, String::from("ArrowLeft"), 0),
351 "ArrowUp" => (38, String::from("ArrowUp"), 0),
352 "ArrowRight" => (39, String::from("ArrowRight"), 0),
353 "ArrowDown" => (40, String::from("ArrowDown"), 0),
354 "Home" => (36, String::from("Home"), 0),
355 "End" => (35, String::from("End"), 0),
356 "PageUp" => (33, String::from("PageUp"), 0),
357 "PageDown" => (34, String::from("PageDown"), 0),
358 "Shift" => (16, String::from("ShiftLeft"), 1),
359 "Control" => (17, String::from("ControlLeft"), 1),
360 "Alt" => (18, String::from("AltLeft"), 1),
361 "Meta" => (91, String::from("MetaLeft"), 1),
362 _ => {
363 let mut chars = key.chars();
365 if let (Some(c), None) = (chars.next(), chars.clone().next()) {
366 let upper = c.to_ascii_uppercase();
367 if upper.is_ascii_alphabetic() {
368 let code = alloc::format!("Key{}", upper);
369 return (upper as u32, code, 0);
370 }
371 if c.is_ascii_digit() {
372 let code = alloc::format!("Digit{}", c);
373 return (c as u32, code, 0);
374 }
375 return (c as u32, String::new(), 0);
376 }
377 (0, String::new(), 0)
378 }
379 }
380 }
381
382 pub fn dispatch_event_with(
388 &mut self,
389 node_idx: usize,
390 event_type: &str,
391 extra: &[(String, Value)],
392 ) -> (bool, bool) {
393 let mut interp = self.new_interp();
398 let r = interp.dispatch_event_in_interp(node_idx, event_type, extra);
399 interp.run_event_loop();
400 self.out.push_str(&interp.out);
401 r
402 }
403
404 pub fn take_pending_reset(&mut self) -> Option<usize> {
407 let g = self.global.clone();
408 let mut gb = g.borrow_mut();
409 let v = match gb.vars.get("__pending_reset") {
410 Some(Value::Number(n)) if *n >= 1.0 => *n as usize - 1,
411 _ => return None,
412 };
413 gb.vars.insert("__pending_reset".into(), Value::Number(0.0));
414 Some(v)
415 }
416
417 pub fn take_pending_nav(&mut self) -> i64 {
420 let history = match self.global.borrow().vars.get("history") {
421 Some(Value::Object(h)) => h.clone(),
422 _ => return 0,
423 };
424 let mut hb = history.borrow_mut();
425 let n = match hb.props.get("_pending_nav") {
426 Some(Value::Number(n)) => *n as i64,
427 _ => 0,
428 };
429 if n != 0 {
430 hb.props.insert("_pending_nav".into(), Value::Number(0.0));
431 }
432 n
433 }
434
435 pub fn take_pending_location(&mut self) -> Option<(String, String)> {
440 let location = match self.global.borrow().vars.get("location") {
441 Some(Value::Object(l)) => l.clone(),
442 _ => return None,
443 };
444 let mut lb = location.borrow_mut();
445 let url = match lb.props.get("_pending_location") {
446 Some(v) => v.to_js_string(),
447 _ => return None,
448 };
449 let mode = lb
450 .props
451 .get("_pending_location_mode")
452 .map(|v| v.to_js_string())
453 .unwrap_or_else(|| String::from("assign"));
454 lb.props.shift_remove("_pending_location");
455 lb.props.shift_remove("_pending_location_mode");
456 Some((url, mode))
457 }
458
459 fn window_listeners(&self, key: &str) -> Vec<Value> {
466 let window = match self.global.borrow().vars.get("window") {
467 Some(Value::Object(w)) => w.clone(),
468 _ => return Vec::new(),
469 };
470 let entries = match window.borrow().props.get(key) {
471 Some(Value::Object(arr)) => match &arr.borrow().kind {
472 ObjKind::Array(items) => items.clone(),
473 _ => Vec::new(),
474 },
475 _ => Vec::new(),
476 };
477 entries
478 .iter()
479 .filter_map(|entry| {
480 let Value::Object(o) = entry else {
481 return Some(entry.clone());
482 };
483 let ObjKind::Array(items) = &o.borrow().kind else {
484 return Some(entry.clone());
485 };
486 if items.get(1).is_some_and(super::super::dom_bridge::is_signal_aborted) {
487 return None;
488 }
489 items.first().cloned()
490 })
491 .collect()
492 }
493
494 fn fire_window_listeners(
496 &mut self,
497 listeners: &[Value],
498 event_type: &str,
499 extra: &[(String, Value)],
500 ) {
501 if listeners.is_empty() {
502 return;
503 }
504 let ev = Obj::plain();
505 {
506 let mut e = ev.borrow_mut();
507 e.props.insert(String::from("type").into(), Value::str(event_type));
508 for (k, v) in extra {
509 e.props.insert(k.clone().into(), v.clone());
510 }
511 }
512 for cb in listeners {
513 let mut interp = self.new_interp();
514 let ctx = alloc::format!("{} listener (window)", event_type);
515 interp.call_listener(cb, Value::Undefined, &[Value::Object(ev.clone())], &ctx);
516 interp.run_event_loop();
517 self.out.push_str(&interp.out);
518 }
519 }
520
521 pub fn fire_popstate(&mut self) {
524 let listeners = self.window_listeners("_popstate_listeners");
525 let state = match self.global.borrow().vars.get("history") {
527 Some(Value::Object(h)) => h
528 .borrow()
529 .props
530 .get("state")
531 .cloned()
532 .unwrap_or(Value::Null),
533 _ => Value::Null,
534 };
535 if !listeners.is_empty() {
536 self.fire_window_listeners(&listeners, "popstate", &[(String::from("state"), state)]);
537 }
538 }
539
540 pub fn has_spa_back(&self) -> bool {
542 let history = match self.global.borrow().vars.get("history") {
543 Some(Value::Object(h)) => h.clone(),
544 _ => return false,
545 };
546 let history_borrow = history.borrow();
547 match history_borrow.props.get("_spa_back_stack") {
548 Some(Value::Object(arr)) => {
549 let arr_borrow = arr.borrow();
550 match &arr_borrow.kind {
551 ObjKind::Array(items) => !items.is_empty(),
552 _ => false,
553 }
554 }
555 _ => false,
556 }
557 }
558
559 pub fn spa_go_back(&mut self) -> Option<String> {
562 let history = match self.global.borrow().vars.get("history") {
563 Some(Value::Object(h)) => h.clone(),
564 _ => return None,
565 };
566 {
568 let cur_url = super::super::builtins::location_href(&self.global).unwrap_or_default();
569 let cur_state = history.borrow().props.get("state").cloned().unwrap_or(Value::Null);
570 let fwd_stack_val = history.borrow().props.get("_spa_fwd_stack").cloned();
571 let fwd_stack = match fwd_stack_val {
572 Some(Value::Object(arr)) => arr,
573 _ => Obj::array(alloc::vec![]),
574 };
575 let entry = Obj::plain();
576 {
577 let mut eb = entry.borrow_mut();
578 eb.props.insert("url".into(), Value::str(cur_url));
579 eb.props.insert("state".into(), cur_state);
580 }
581 if let ObjKind::Array(items) = &mut fwd_stack.borrow_mut().kind {
582 items.push(Value::Object(entry));
583 }
584 history.borrow_mut().props.insert("_spa_fwd_stack".into(), Value::Object(fwd_stack));
585 }
586 let (prev_url, prev_state) = {
588 let back_stack_val = history.borrow().props.get("_spa_back_stack").cloned();
589 let back_stack = match back_stack_val {
590 Some(Value::Object(arr)) => arr,
591 _ => return None,
592 };
593 let entry = match &mut back_stack.borrow_mut().kind {
594 ObjKind::Array(items) => items.pop(),
595 _ => None,
596 }?;
597 let eb = match entry { Value::Object(o) => o, _ => return None };
598 let url = eb.borrow().props.get("url").cloned().unwrap_or(Value::Undefined).to_js_string();
599 let state = eb.borrow().props.get("state").cloned().unwrap_or(Value::Null);
600 (url, state)
601 };
602 history.borrow_mut().props.insert("state".into(), prev_state);
604 super::super::builtins::update_location(&self.global, &prev_url);
605 self.base_url = prev_url.to_string();
606 self.fire_popstate();
607 Some(prev_url.to_string())
608 }
609
610 pub fn spa_go_forward(&mut self) -> Option<String> {
612 let history = match self.global.borrow().vars.get("history") {
613 Some(Value::Object(h)) => h.clone(),
614 _ => return None,
615 };
616 {
618 let cur_url = super::super::builtins::location_href(&self.global).unwrap_or_default();
619 let cur_state = history.borrow().props.get("state").cloned().unwrap_or(Value::Null);
620 let back_stack_val = history.borrow().props.get("_spa_back_stack").cloned();
621 let back_stack = match back_stack_val {
622 Some(Value::Object(arr)) => arr,
623 _ => Obj::array(alloc::vec![]),
624 };
625 let entry = Obj::plain();
626 {
627 let mut eb = entry.borrow_mut();
628 eb.props.insert("url".into(), Value::str(cur_url));
629 eb.props.insert("state".into(), cur_state);
630 }
631 if let ObjKind::Array(items) = &mut back_stack.borrow_mut().kind {
632 items.push(Value::Object(entry));
633 }
634 history.borrow_mut().props.insert("_spa_back_stack".into(), Value::Object(back_stack));
635 }
636 let (next_url, next_state) = {
638 let fwd_stack_val = history.borrow().props.get("_spa_fwd_stack").cloned();
639 let fwd_stack = match fwd_stack_val {
640 Some(Value::Object(arr)) => arr,
641 _ => return None,
642 };
643 let entry = match &mut fwd_stack.borrow_mut().kind {
644 ObjKind::Array(items) => items.pop(),
645 _ => None,
646 }?;
647 let eb = match entry { Value::Object(o) => o, _ => return None };
648 let url = eb.borrow().props.get("url").cloned().unwrap_or(Value::Undefined).to_js_string();
649 let state = eb.borrow().props.get("state").cloned().unwrap_or(Value::Null);
650 (url, state)
651 };
652 history.borrow_mut().props.insert("state".into(), next_state);
653 super::super::builtins::update_location(&self.global, &next_url);
654 self.base_url = next_url.to_string();
655 self.fire_popstate();
656 Some(next_url.to_string())
657 }
658
659 pub fn has_spa_forward(&self) -> bool {
661 let history = match self.global.borrow().vars.get("history") {
662 Some(Value::Object(h)) => h.clone(),
663 _ => return false,
664 };
665 let history_borrow = history.borrow();
666 match history_borrow.props.get("_spa_fwd_stack") {
667 Some(Value::Object(arr)) => {
668 let arr_borrow = arr.borrow();
669 match &arr_borrow.kind {
670 ObjKind::Array(items) => !items.is_empty(),
671 _ => false,
672 }
673 }
674 _ => false,
675 }
676 }
677
678 pub fn fire_scroll(&mut self, scroll_y: i32) {
681 {
684 let g = self.global.borrow();
685 if let Some(Value::Object(w)) = g.vars.get("window") {
686 let mut wb = w.borrow_mut();
687 wb.props
688 .insert("scrollY".into(), Value::Number(scroll_y as f64));
689 wb.props
690 .insert("pageYOffset".into(), Value::Number(scroll_y as f64));
691 }
692 }
693 {
694 let mut g = self.global.borrow_mut();
695 g.vars
696 .insert("scrollY".into(), Value::Number(scroll_y as f64));
697 g.vars
698 .insert("pageYOffset".into(), Value::Number(scroll_y as f64));
699 }
700 let listeners = self.window_listeners("_scroll_listeners");
701 self.fire_window_listeners(
702 &listeners,
703 "scroll",
704 &[(String::from("scrollY"), Value::Number(scroll_y as f64))],
705 );
706 }
707
708 pub fn fire_hashchange(&mut self, old_url: &str, new_url: &str) {
711 let new_hash = match new_url.split_once('#') {
713 Some((_, frag)) => alloc::format!("#{}", frag),
714 None => String::new(),
715 };
716 {
717 let g = self.global.borrow();
718 if let Some(Value::Object(loc)) = g.vars.get("location") {
719 loc.borrow_mut()
720 .props
721 .insert("hash".into(), Value::str(&new_hash));
722 }
723 }
724 let listeners = self.window_listeners("_hashchange_listeners");
725 self.fire_window_listeners(
726 &listeners,
727 "hashchange",
728 &[
729 (String::from("oldURL"), Value::str(old_url)),
730 (String::from("newURL"), Value::str(new_url)),
731 ],
732 );
733 }
734
735 pub fn set_viewport_size(&mut self, width: i32, height: i32) {
739 {
740 let g = self.global.borrow();
741 if let Some(Value::Object(w)) = g.vars.get("window") {
742 let mut wb = w.borrow_mut();
743 for k in ["innerWidth", "outerWidth"] {
744 wb.props.insert(k.into(), Value::Number(width as f64));
745 }
746 for k in ["innerHeight", "outerHeight"] {
747 wb.props.insert(k.into(), Value::Number(height as f64));
748 }
749 }
750 }
751 let mut g = self.global.borrow_mut();
752 g.vars.insert("innerWidth".into(), Value::Number(width as f64));
753 g.vars.insert("innerHeight".into(), Value::Number(height as f64));
754 }
755
756 pub fn notify_layout_settled(&mut self) {
764 #[cfg(target_os = "none")]
765 let t0 = crate::os_lib::platform::now_ms();
766 let mut interp = self.new_interp();
767 super::super::builtins::fire_resize_observers(&mut interp);
768 interp.run_event_loop();
769 self.out.push_str(&interp.out);
770 #[cfg(target_os = "none")]
771 let t_ro = crate::os_lib::platform::now_ms().saturating_sub(t0);
772 let stale = self.dom().borrow_mut().take_stale_measurements();
774 #[cfg(target_os = "none")]
775 let log_time = |what: &str, t_resize: u64| {
776 if t_ro + t_resize >= 200 {
777 crate::warn!(
778 "[PERF][SETTLED] ResizeObserver+イベントループ={}ms resize={}ms 理由={} steps={}",
779 t_ro,
780 t_resize,
781 what,
782 interp.steps
783 );
784 }
785 };
786 if !stale {
787 #[cfg(target_os = "none")]
788 log_time("なし", 0);
789 return;
790 }
791 #[cfg(target_os = "none")]
792 let t1 = crate::os_lib::platform::now_ms();
793 let num = |k: &str| -> i32 {
794 match self.global.borrow().vars.get(k) {
795 Some(Value::Number(n)) => *n as i32,
796 _ => 0,
797 }
798 };
799 let (w, h) = (num("innerWidth"), num("innerHeight"));
800 if w > 0 && h > 0 {
801 self.fire_resize(w, h);
802 }
803 #[cfg(target_os = "none")]
804 log_time(
805 "寸法が古い",
806 crate::os_lib::platform::now_ms().saturating_sub(t1),
807 );
808 }
809
810 pub fn fire_resize(&mut self, width: i32, height: i32) {
813 {
814 let g = self.global.borrow();
815 if let Some(Value::Object(w)) = g.vars.get("window") {
816 let mut wb = w.borrow_mut();
817 wb.props
818 .insert("innerWidth".into(), Value::Number(width as f64));
819 wb.props
820 .insert("innerHeight".into(), Value::Number(height as f64));
821 }
822 }
823 {
824 let mut g = self.global.borrow_mut();
826 g.vars
827 .insert("innerWidth".into(), Value::Number(width as f64));
828 g.vars
829 .insert("innerHeight".into(), Value::Number(height as f64));
830 }
831 let listeners = self.window_listeners("_resize_listeners");
832 self.fire_window_listeners(
833 &listeners,
834 "resize",
835 &[
836 (String::from("innerWidth"), Value::Number(width as f64)),
837 (String::from("innerHeight"), Value::Number(height as f64)),
838 ],
839 );
840 }
841
842 pub fn sync_window_frames(&mut self) {
844 let iframes: Vec<usize> = {
845 let dom = self.dom().borrow();
846 dom.tree_order()
847 .into_iter()
848 .filter(|&i| dom.nodes.get(i).is_some_and(|n| !n.is_text && n.tag == "iframe") && dom.is_attached(i))
849 .collect()
850 };
851 let mut wins: Vec<Value> = Vec::with_capacity(iframes.len());
852 {
853 let mut it = self.new_interp();
854 for fi in iframes {
855 wins.push(it.get_iframe_content_window(fi));
856 }
857 }
858 if let Some(Value::Object(w)) = scope_get(&self.global, "window") {
859 let mut wb = w.borrow_mut();
860 let prev_len = wb.props.get("length").map(|v| v.to_number() as usize).unwrap_or(0);
861 for i in wins.len()..prev_len {
862 wb.props.shift_remove(i.to_string().as_str());
863 }
864 for (i, cw) in wins.iter().enumerate() {
865 wb.props.insert(i.to_string().into(), cw.clone());
866 }
867 wb.props.insert("length".into(), Value::Number(wins.len() as f64));
868 }
869 }
870}
871
872const PRELUDE_GROUPS: &[(&str, &[&str])] = &[
874 (
875 "webaudio",
876 &[
877 "AudioParam", "AudioNode", "AudioScheduledSourceNode", "OscillatorNode", "PeriodicWave", "GainNode", "DelayNode",
878 "BiquadFilterNode", "DynamicsCompressorNode", "AnalyserNode", "StereoPannerNode", "ChannelSplitterNode",
879 "ChannelMergerNode", "WaveShaperNode", "ConvolverNode", "PannerNode", "AudioBuffer", "AudioBufferSourceNode",
880 "MediaElementAudioSourceNode", "MediaStreamAudioSourceNode", "ScriptProcessorNode", "AudioDestinationNode",
881 "AudioListener", "BaseAudioContext", "AudioContext", "OfflineAudioContext",
882 ],
883 ),
884 ("trustedtypes", &["TrustedHTML", "TrustedScript", "TrustedScriptURL", "TrustedTypePolicy", "TrustedTypePolicyFactory", "trustedTypes"]),
885 ("wasm", &["WebAssembly"]),
886 ("storage", &["IDBRequest", "IDBOpenDBRequest", "IDBFactory", "indexedDB", "IDBDatabase", "IDBTransaction", "IDBObjectStore", "IDBIndex", "IDBCursor", "IDBCursorWithValue", "IDBKeyRange", "IDBVersionChangeEvent", "Cache", "CacheStorage", "caches"]),
887];
888
889fn prelude_install(it: &mut Interp, _this: Value, a: &[Value]) -> Result<Value, Value> {
891 const WEBAUDIO: &str = include_str!("../prelude/webaudio.js");
892 const TRUSTED_TYPES: &str = include_str!("../prelude/trustedtypes.js");
893 const WASM: &str = include_str!("../prelude/wasm.js");
894 const STORAGE: &str = include_str!("../prelude/storage.js");
895 let grp = a.first().map(|v| v.to_js_string()).unwrap_or_default();
896 let r = match grp.as_str() {
897 "webaudio" => it.eval_source(WEBAUDIO).map(|_| ()),
898 "trustedtypes" => it.eval_source(TRUSTED_TYPES).map(|_| ()),
899 "storage" => it.eval_source(STORAGE).map(|_| ()),
900 "wasm" => {
901 let window = it.global.borrow().vars.get("window").cloned().unwrap_or(Value::Undefined);
902 let natives = super::super::builtins::wasm_api::make_wasm_natives();
903 it.eval_source(WASM).and_then(|f| it.call_value(&f, Value::Undefined, &[window, natives]).map(|_| ()))
904 }
905 _ => Ok(()),
906 };
907 if let Err(e) = r {
908 crate::warn!("[JS] prelude {} の評価に失敗: {}", grp, e.to_js_string().chars().take(160).collect::<String>());
909 }
910 Ok(Value::Undefined)
911}