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 ignored_pops: usize,
61
62 after_navigate: Vec<AfterNavigate<S>>,
63}
64
65impl<S: Clone + 'static> RouterApp<S> {
66 pub(crate) fn new(table: RouteTable<S>, state: S, history: Box<dyn History>) -> Self {
67 let initial = history.current();
68 let mut app = Self {
69 table,
70 state,
71 history,
72 session: Session::default(),
73 nav: NavState {
74 preload_on_hover: true,
75 ..NavState::default()
76 },
77 mounted: None,
78 transition: None,
79 pending: None,
80 preloads: Vec::new(),
81 deferred: Invalidation::None,
82 key: initial.key,
83 shown_key: initial.key,
84 next_page_id: 0,
85 blocking: false,
86 blocked: None,
87 unblock_next: false,
88 ignored_pops: 0,
89 after_navigate: Vec::new(),
90 };
91 app.navigate(&initial.url, NavKind::Silent, GotoOptions::default());
92 app
93 }
94
95 pub fn preload_on_hover(mut self, enabled: bool) -> Self {
97 self.nav.preload_on_hover = enabled;
98 self
99 }
100
101 pub fn after_navigate(mut self, callback: impl Fn(&Navigation, &S) + 'static) -> Self {
104 self.after_navigate.push(Box::new(callback));
105 self
106 }
107
108 pub fn state(&self) -> &S {
109 &self.state
110 }
111
112 pub fn matches(&self, url: &str) -> Option<&str> {
129 self.table.page_route(url)
130 }
131
132 pub fn request(&self) -> Option<&Request> {
134 self.mounted.as_ref().map(|mounted| &mounted.request)
135 }
136
137 pub fn url(&self) -> Option<&str> {
139 self.mounted.as_ref().map(|mounted| mounted.url.as_str())
140 }
141
142 pub fn is_loading(&self) -> bool {
143 self.pending.is_some()
144 }
145
146 pub fn goto(&mut self, url: &str) {
150 self.goto_with(url, GotoOptions::default());
151 }
152
153 pub fn goto_with(&mut self, url: &str, options: GotoOptions) {
155 self.request_goto(url, options);
156 }
157
158 pub fn back(&mut self) {
159 self.history.back();
160 }
161
162 pub fn forward(&mut self) {
163 self.history.forward();
164 }
165
166 pub fn invalidate(&mut self, key: impl Into<String>) {
168 self.invalidate_with(Invalidation::Keys(vec![key.into()]));
169 }
170
171 pub fn invalidate_all(&mut self) {
173 self.invalidate_with(Invalidation::All);
174 }
175
176 pub fn preload(&mut self, url: &str) {
178 let (entry, request) = self.table.resolve(url);
179 let url = request.untracked_url();
180 let busy = |job: &Job<S>| job.request.untracked_url() == url;
181 if self
182 .pending
183 .as_ref()
184 .is_some_and(|pending| busy(&pending.job))
185 || self.preloads.iter().any(busy)
186 {
187 return;
188 }
189 let previous: Vec<_> = self.mounted.iter().flat_map(Mounted::loaded).collect();
190 let job = Job::start(entry, request, &self.state, &previous, &Invalidation::None);
191 if self.preloads.len() == MAX_PRELOADS {
192 self.preloads.remove(0);
193 }
194 self.preloads.push(job);
195 }
196
197 pub fn ui(&mut self, ui: &mut Ui) {
199 let ctx = ui.ctx().clone();
200 #[cfg(feature = "remote")]
201 let _runtime = crate::remote::enter();
202 #[cfg(feature = "remote")]
203 crate::remote::begin_frame(&ctx);
204
205 #[cfg(not(target_arch = "wasm32"))]
206 self.handle_back_forward_input(ui);
207 if let Some(entry) = self.history.poll(&ctx) {
208 self.traverse(entry);
209 }
210 self.poll(&ctx);
211
212 self.nav.shows_links = self.history.shows_links();
213 self.nav.can_go_back = self.history.can_go_back();
214 self.nav.can_go_forward = self.history.can_go_forward();
215 self.nav.blocked = self
216 .blocked
217 .as_ref()
218 .map(|blocked| blocked.navigation.clone());
219 let nav = RefCell::new(core::mem::take(&mut self.nav));
220 match &mut self.mounted {
221 Some(mounted) => {
222 render::render(ui, mounted, self.transition.as_mut(), &self.state, &nav);
223 }
224 None => {
225 ui.centered_and_justified(|ui| ui.spinner());
226 }
227 }
228 self.nav = nav.into_inner();
229 self.blocking = core::mem::take(&mut self.nav.blocking);
230 let hovered_link = self.nav.hovered_link.take();
231 if !ctx.input(|i| i.pointer.any_down()) {
233 self.history.hover_link(hovered_link.as_deref());
234 }
235 if let Some(transition) = &self.transition
236 && (transition.state.done.get() || !transition.state.claimed.get())
237 {
238 self.transition = None;
239 }
240
241 #[cfg(feature = "remote")]
242 crate::remote::end_frame();
243
244 let actions = core::mem::take(&mut self.nav.actions);
245 if !actions.is_empty() {
246 for action in actions {
247 self.apply(action);
248 }
249 ctx.request_repaint();
250 }
251 self.poll(&ctx);
252 }
253
254 #[cfg(not(target_arch = "wasm32"))]
256 fn handle_back_forward_input(&mut self, ui: &Ui) {
257 use egui::{Key, Modifiers, PointerButton};
258
259 let (back, forward) = ui.input_mut(|i| {
260 let back = i.pointer.button_pressed(PointerButton::Extra1)
261 | i.consume_key(Modifiers::ALT, Key::ArrowLeft);
262 let forward = i.pointer.button_pressed(PointerButton::Extra2)
263 | i.consume_key(Modifiers::ALT, Key::ArrowRight);
264 (back, forward)
265 });
266 if back {
267 self.history.back();
268 }
269 if forward {
270 self.history.forward();
271 }
272 }
273
274 fn apply(&mut self, action: NavAction) {
275 match action {
276 NavAction::Goto(url, options) => self.request_goto(&url, options),
277 NavAction::Back => self.history.back(),
278 NavAction::Forward => self.history.forward(),
279 NavAction::Invalidate(invalidation) => self.invalidate_with(invalidation),
280 NavAction::Preload(url) => self.preload(&url),
281 NavAction::PushState(url, state) => self.shallow(url, state, true),
282 NavAction::ReplaceState(url, state) => self.shallow(url, state, false),
283 NavAction::ReplaceUrl(url) => {
284 let state = self.mounted.as_ref().and_then(|m| m.history_state.clone());
285 self.shallow(url, state, false);
286 }
287 NavAction::ConfirmNavigation => self.confirm_blocked(),
288 NavAction::CancelNavigation => self.blocked = None,
289 }
290 }
291
292 fn poll(&mut self, ctx: &egui::Context) {
296 #[cfg(feature = "remote")]
297 {
298 let invalidated = crate::remote::take_invalidated();
299 if !invalidated.is_empty() {
300 self.invalidate_with(Invalidation::Keys(invalidated));
301 ctx.request_repaint();
302 }
303 }
304 for job in &mut self.preloads {
305 job.poll(ctx);
306 }
307 while let Some(pending) = &mut self.pending {
308 if !pending.job.poll(ctx) {
309 return;
310 }
311 let mut pending = self.pending.take().expect("checked above");
312 let outcome = pending.job.take_outcome().expect("the job is done");
313 self.nav.loading = None;
314 self.commit(pending, outcome);
315 }
316 }
317
318 fn shallow(&mut self, url: String, state: Option<Rc<dyn Any>>, push: bool) {
320 let Some(mounted) = &mut self.mounted else {
321 return;
322 };
323 if !url.is_empty() {
324 mounted.url = url;
325 }
326 if push {
327 self.key = self.history.push(&mounted.url);
328 } else {
329 self.history.replace(&mounted.url);
330 }
331 self.shown_key = self.key;
332 mounted.history_state = state.clone();
333 self.session.record(self.key, mounted.id, state);
334 }
335
336 fn traverse(&mut self, entry: HistoryEntry) {
339 if self.ignored_pops > 0 {
340 self.ignored_pops -= 1;
341 return;
342 }
343 let meta = self.session.get(entry.key);
344 if let (Some(mounted), Some(meta)) = (&mut self.mounted, meta)
345 && meta.page == mounted.id
346 {
347 self.pending = None;
348 self.nav.loading = None;
349 self.key = entry.key;
350 self.shown_key = entry.key;
351 mounted.url = entry.url;
352 mounted.history_state = meta.state.clone();
353 return;
354 }
355
356 let direction = self.session.direction(self.shown_key, entry.key);
357 if direction != Direction::None && self.should_block() {
358 match direction {
360 Direction::Back => self.history.forward(),
361 _ => self.history.back(),
362 }
363 self.ignored_pops += 1;
364 self.block(Resume::Traverse(direction), entry.url, direction);
365 return;
366 }
367 self.key = entry.key;
368 self.navigate(&entry.url, NavKind::Silent, GotoOptions::default());
369 }
370
371 fn invalidate_with(&mut self, invalidation: Invalidation) {
373 #[cfg(feature = "remote")]
374 crate::remote::invalidate_queries(&invalidation);
375 self.reload(invalidation);
376 }
377
378 fn reload(&mut self, invalidation: Invalidation) {
380 self.preloads.clear();
381 if self.pending.is_some() {
382 self.deferred = core::mem::take(&mut self.deferred).merge(invalidation);
383 return;
384 }
385 if let Some(mounted) = &self.mounted {
386 let (url, id) = (mounted.request.untracked_url(), mounted.id);
387 self.start(
388 &url,
389 NavKind::Silent,
390 GotoOptions::default(),
391 0,
392 Some(id),
393 invalidation,
394 );
395 }
396 }
397}