1mod navigate;
8
9use core::any::Any;
10use core::cell::RefCell;
11use std::rc::Rc;
12
13use egui::Ui;
14
15use crate::extract::{NavAction, NavState};
16use crate::history::{EntryKey, History, HistoryEntry};
17use crate::load::{Invalidation, Job};
18use crate::navigation::{Direction, GotoOptions, Navigation};
19use crate::render::{self, Mounted, Transition};
20use crate::request::Request;
21use crate::router::RouteTable;
22use crate::session::Session;
23use navigate::{Blocked, NavKind, Pending, Resume};
24
25const MAX_PRELOADS: usize = 8;
27
28type AfterNavigate<S> = Box<dyn Fn(&Navigation, &S)>;
29
30pub struct RouterApp<S> {
34 table: RouteTable<S>,
35 state: S,
36 history: Box<dyn History>,
37 session: Session,
38 nav: NavState,
40
41 mounted: Option<Mounted<S>>,
42 transition: Option<Transition<S>>,
43 pending: Option<Pending<S>>,
44 preloads: Vec<Job<S>>,
45 deferred: Invalidation,
47
48 key: EntryKey,
50 shown_key: EntryKey,
52 next_page_id: u64,
53
54 blocking: bool,
56 blocked: Option<Blocked>,
57 unblock_next: bool,
59 title: Option<String>,
61 close_confirmed: bool,
63 ignored_pops: usize,
65
66 after_navigate: Vec<AfterNavigate<S>>,
67}
68
69impl<S: Clone + 'static> RouterApp<S> {
70 pub(crate) fn new(table: RouteTable<S>, state: S, history: Box<dyn History>) -> Self {
71 let initial = history.current();
72 let mut app = Self {
73 table,
74 state,
75 history,
76 session: Session::default(),
77 nav: NavState {
78 preload_on_hover: true,
79 ..NavState::default()
80 },
81 mounted: None,
82 transition: None,
83 pending: None,
84 preloads: Vec::new(),
85 deferred: Invalidation::None,
86 key: initial.key,
87 shown_key: initial.key,
88 next_page_id: 0,
89 blocking: false,
90 blocked: None,
91 unblock_next: false,
92 title: None,
93 close_confirmed: false,
94 ignored_pops: 0,
95 after_navigate: Vec::new(),
96 };
97 app.navigate(&initial.url, NavKind::Silent, GotoOptions::default());
98 app
99 }
100
101 pub fn preload_on_hover(mut self, enabled: bool) -> Self {
103 self.nav.preload_on_hover = enabled;
104 self
105 }
106
107 pub fn after_navigate(mut self, callback: impl Fn(&Navigation, &S) + 'static) -> Self {
110 self.after_navigate.push(Box::new(callback));
111 self
112 }
113
114 pub fn state(&self) -> &S {
115 &self.state
116 }
117
118 pub fn matches(&self, url: &str) -> Option<&str> {
135 self.table.page_route(url)
136 }
137
138 pub fn request(&self) -> Option<&Request> {
140 self.mounted.as_ref().map(|mounted| &mounted.request)
141 }
142
143 pub fn url(&self) -> Option<&str> {
145 self.mounted.as_ref().map(|mounted| mounted.url.as_str())
146 }
147
148 pub fn title(&self) -> Option<&str> {
151 self.title.as_deref()
152 }
153
154 pub fn is_loading(&self) -> bool {
155 self.pending.is_some()
156 }
157
158 pub fn goto(&mut self, url: &str) {
162 self.goto_with(url, GotoOptions::default());
163 }
164
165 pub fn goto_with(&mut self, url: &str, options: GotoOptions) {
167 self.request_goto(url, options);
168 }
169
170 pub fn back(&mut self) {
171 self.history.back();
172 }
173
174 pub fn forward(&mut self) {
175 self.history.forward();
176 }
177
178 pub fn invalidate(&mut self, key: impl Into<String>) {
180 self.invalidate_with(Invalidation::Keys(vec![key.into()]));
181 }
182
183 pub fn invalidate_all(&mut self) {
185 self.invalidate_with(Invalidation::All);
186 }
187
188 pub fn preload(&mut self, url: &str) {
190 let (entry, request) = self.table.resolve(url);
191 let url = request.untracked_url();
192 let busy = |job: &Job<S>| job.request.untracked_url() == url;
193 if self
194 .pending
195 .as_ref()
196 .is_some_and(|pending| busy(&pending.job))
197 || self.preloads.iter().any(busy)
198 {
199 return;
200 }
201 let previous: Vec<_> = self.mounted.iter().flat_map(Mounted::loaded).collect();
202 let job = Job::start(entry, request, &self.state, &previous, &Invalidation::None);
203 if self.preloads.len() == MAX_PRELOADS {
204 self.preloads.remove(0);
205 }
206 self.preloads.push(job);
207 }
208
209 pub fn ui(&mut self, ui: &mut Ui) {
211 let ctx = ui.ctx().clone();
212 #[cfg(feature = "remote")]
213 let _runtime = crate::remote::enter();
214 #[cfg(feature = "remote")]
215 crate::remote::set_context(&ctx);
216
217 #[cfg(not(target_arch = "wasm32"))]
218 self.handle_back_forward_input(ui);
219 #[cfg(not(target_arch = "wasm32"))]
220 self.handle_close_request(&ctx);
221 if let Some(entry) = self.history.poll(&ctx) {
222 self.traverse(entry);
223 }
224 self.poll(&ctx);
225
226 self.nav.shows_links = self.history.shows_links();
227 self.nav.can_go_back = self.history.can_go_back();
228 self.nav.can_go_forward = self.history.can_go_forward();
229 self.nav.blocked = self
230 .blocked
231 .as_ref()
232 .map(|blocked| blocked.navigation.clone());
233 let nav = RefCell::new(core::mem::take(&mut self.nav));
234 match &mut self.mounted {
235 Some(mounted) => {
236 render::render(ui, mounted, self.transition.as_mut(), &self.state, &nav);
237 }
238 None => {
239 ui.centered_and_justified(|ui| ui.spinner());
240 }
241 }
242 self.nav = nav.into_inner();
243 let was_blocking = self.blocking;
244 self.blocking = core::mem::take(&mut self.nav.blocking);
245 if self.blocking != was_blocking {
246 self.history.set_blocking(self.blocking);
247 }
248 if let Some((_, title)) = self.nav.title.take()
249 && self.title.as_ref() != Some(&title)
250 {
251 set_title(&ctx, &title);
252 self.title = Some(title);
253 }
254 let hovered_link = self.nav.hovered_link.take();
255 if !ctx.input(|i| i.pointer.any_down()) {
257 self.history.hover_link(hovered_link.as_deref());
258 }
259 if let Some(transition) = &self.transition
260 && (transition.state.done.get() || !transition.state.claimed.get())
261 {
262 self.transition = None;
263 }
264
265 #[cfg(feature = "remote")]
266 crate::remote::end_frame();
267
268 let actions = core::mem::take(&mut self.nav.actions);
269 if !actions.is_empty() {
270 for action in actions {
271 self.apply(action);
272 }
273 ctx.request_repaint();
274 }
275 if core::mem::take(&mut self.close_confirmed) {
276 ctx.send_viewport_cmd(egui::ViewportCommand::Close);
277 }
278 self.poll(&ctx);
279 }
280
281 #[cfg(not(target_arch = "wasm32"))]
283 fn handle_back_forward_input(&mut self, ui: &Ui) {
284 use egui::{Key, Modifiers, PointerButton};
285
286 let (back, forward) = ui.input_mut(|i| {
287 let back = i.pointer.button_pressed(PointerButton::Extra1)
288 | i.consume_key(Modifiers::ALT, Key::ArrowLeft);
289 let forward = i.pointer.button_pressed(PointerButton::Extra2)
290 | i.consume_key(Modifiers::ALT, Key::ArrowRight);
291 (back, forward)
292 });
293 if back {
294 self.history.back();
295 }
296 if forward {
297 self.history.forward();
298 }
299 }
300
301 #[cfg(not(target_arch = "wasm32"))]
304 fn handle_close_request(&mut self, ctx: &egui::Context) {
305 if ctx.input(|i| i.viewport().close_requested()) && self.should_block() {
306 ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
307 self.block(Resume::Close, String::new(), Direction::None);
308 }
309 }
310
311 fn apply(&mut self, action: NavAction) {
312 match action {
313 NavAction::Goto(url, options) => self.request_goto(&url, options),
314 NavAction::Back => self.history.back(),
315 NavAction::Forward => self.history.forward(),
316 NavAction::Invalidate(invalidation) => self.invalidate_with(invalidation),
317 NavAction::Preload(url) => self.preload(&url),
318 NavAction::PushState(url, state) => self.shallow(url, state, true),
319 NavAction::ReplaceState(url, state) => self.shallow(url, state, false),
320 NavAction::ReplaceUrl(url) => {
321 let state = self.mounted.as_ref().and_then(|m| m.history_state.clone());
322 self.shallow(url, state, false);
323 }
324 NavAction::ConfirmNavigation => self.confirm_blocked(),
325 NavAction::CancelNavigation => self.blocked = None,
326 }
327 }
328
329 fn poll(&mut self, ctx: &egui::Context) {
333 #[cfg(feature = "remote")]
334 {
335 let invalidated = crate::remote::take_invalidated();
336 if !invalidated.is_empty() {
337 self.invalidate_with(Invalidation::Keys(invalidated));
338 ctx.request_repaint();
339 }
340 }
341 for job in &mut self.preloads {
342 job.poll(ctx);
343 }
344 while let Some(pending) = &mut self.pending {
345 if !pending.job.poll(ctx) {
346 return;
347 }
348 let mut pending = self.pending.take().expect("checked above");
349 let outcome = pending.job.take_outcome().expect("the job is done");
350 self.nav.loading = None;
351 self.commit(pending, outcome);
352 }
353 }
354
355 fn shallow(&mut self, url: String, state: Option<Rc<dyn Any>>, push: bool) {
357 let Some(mounted) = &mut self.mounted else {
358 return;
359 };
360 if !url.is_empty() {
361 mounted.url = url;
362 }
363 if push {
364 self.key = self.history.push(&mounted.url);
365 } else {
366 self.history.replace(&mounted.url);
367 }
368 self.shown_key = self.key;
369 mounted.history_state = state.clone();
370 self.session.record(self.key, mounted.id, state);
371 }
372
373 fn traverse(&mut self, entry: HistoryEntry) {
376 if self.ignored_pops > 0 {
377 self.ignored_pops -= 1;
378 return;
379 }
380 if let Some(mounted) = &mut self.mounted {
381 let state = match self.session.get(entry.key) {
382 Some(meta) if meta.page == mounted.id => Some(meta.state.clone()),
383 Some(_) => None,
384 None => (Request::new(&entry.url).untracked_url()
386 == Request::new(&mounted.url).untracked_url())
387 .then(|| {
388 self.session.record(entry.key, mounted.id, None);
389 None
390 }),
391 };
392 if let Some(state) = state {
393 self.pending = None;
394 self.nav.loading = None;
395 self.key = entry.key;
396 self.shown_key = entry.key;
397 mounted.url = entry.url;
398 mounted.history_state = state;
399 return;
400 }
401 }
402
403 let direction = self.session.direction(self.shown_key, entry.key);
404 if direction != Direction::None && self.should_block() {
405 match direction {
407 Direction::Back => self.history.forward(),
408 _ => self.history.back(),
409 }
410 self.ignored_pops += 1;
411 self.block(Resume::Traverse(direction), entry.url, direction);
412 return;
413 }
414 self.key = entry.key;
415 self.navigate(&entry.url, NavKind::Silent, GotoOptions::default());
416 }
417
418 fn invalidate_with(&mut self, invalidation: Invalidation) {
420 #[cfg(feature = "remote")]
421 crate::remote::invalidate_queries(&invalidation);
422 self.reload(invalidation);
423 }
424
425 fn reload(&mut self, invalidation: Invalidation) {
427 self.preloads.clear();
428 if self.pending.is_some() {
429 self.deferred = core::mem::take(&mut self.deferred).merge(invalidation);
430 return;
431 }
432 if let Some(mounted) = &self.mounted {
433 let (url, id) = (mounted.request.untracked_url(), mounted.id);
434 self.start(
435 &url,
436 NavKind::Silent,
437 GotoOptions::default(),
438 0,
439 Some(id),
440 invalidation,
441 );
442 }
443 }
444}
445
446fn set_title(ctx: &egui::Context, title: &str) {
448 #[cfg(target_arch = "wasm32")]
449 {
450 let _ = ctx;
451 if let Some(document) = web_sys::window().and_then(|window| window.document()) {
452 document.set_title(title);
453 }
454 }
455 #[cfg(not(target_arch = "wasm32"))]
456 ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.to_owned()));
457}