lingxia-lxapp 0.18.0

LxApp (lightweight application) container and runtime for LingXia framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
use crate::PageLifecycleEvent;
use crate::lifecycle::AppServiceEvent;
use crate::lxapp::LxAppSessionStatus;
use crate::page::NavigationType;
use crate::update::UpdateManager;
use crate::{LxApp, debug, error, info, lxapp, warn};
use lingxia_platform::traits::app_runtime::AppRuntime;
use lingxia_platform::traits::pull_to_refresh::PullToRefresh;
use lingxia_platform::traits::ui::UIUpdate;
use std::sync::Arc;
use std::time::Instant;

/// lxapp-scoped UI event types (page/app runtime events).
#[derive(Debug, Clone, PartialEq)]
pub enum LxAppUiEventType {
    /// TabBar item clicked
    TabBarClick = 0,
    /// Capsule button clicked (close, minimize, more)
    CapsuleClick = 1,
    /// Navigation bar button clicked (back, home, title)
    NavigationClick = 2,
    /// System back button pressed
    BackPress = 3,
    /// Pull-to-refresh triggered by user
    PullDownRefresh = 4,
}

pub trait LxAppDelegate {
    /// Called when lxapp is opened
    /// Returns the resolved path that should be used
    fn on_lxapp_opened(self: Arc<Self>, path: String, session_id: u64) -> String;

    /// Called when lxapp is closed
    fn on_lxapp_closed(self: &Arc<Self>, session_id: u64);

    /// Called when the page showed in the view
    fn on_page_show(self: &Arc<Self>, path: String);

    /// Handle UI events
    /// Returns true if the event was handled, false to allow default behavior
    fn on_lxapp_event(self: &Arc<Self>, event_type: LxAppUiEventType, data: String) -> bool;
}

fn finalize_lxapp_close(app: &Arc<LxApp>, session_id: u64) -> bool {
    if session_id != app.session_id() || app.status() == LxAppSessionStatus::Closed {
        return false;
    }

    app.set_status(LxAppSessionStatus::Closed);
    app.clear_open_region();
    app.clear_transient_files();
    app.runtime.clear_lxapp_appearance(&app.appid);
    app.state
        .lock()
        .unwrap_or_else(|error| {
            warn!("Recovered poisoned lxapp state mutex during close")
                .with_appid(app.appid.clone());
            error.into_inner()
        })
        .last_active_time = Instant::now();

    if let Some(manager) = lxapp::get_lxapps_manager() {
        manager.remove_from_stack(&app.appid);
        // A retired instance is never recalled, so no timer may outlive it.
        if !app.session.is_retired() {
            manager.schedule_delayed_destroy(app.appid.clone());
        }
    }
    true
}

fn notify_lxapp_close(app: &Arc<LxApp>) {
    let args = crate::lifecycle::AppServiceEventArgs {
        source: crate::lifecycle::AppServiceEventSource::Lxapp,
        reason: crate::lifecycle::AppServiceEventReason::Close,
    }
    .to_json_string();
    if let Err(error) = app.appservice_notify(AppServiceEvent::OnHide, Some(args)) {
        error!("Failed to trigger onHide service: {}", error).with_appid(app.appid.clone());
    }
}

impl LxApp {
    /// Queue the close lifecycle before programmatic shutdown terminates Logic.
    pub(crate) fn begin_programmatic_close(self: &Arc<Self>, session_id: u64) -> bool {
        if session_id != self.session_id()
            || matches!(
                self.status(),
                LxAppSessionStatus::Closing | LxAppSessionStatus::Closed
            )
        {
            return false;
        }
        notify_lxapp_close(self);
        true
    }

    /// Finish close bookkeeping after AppService shutdown has already begun.
    pub(crate) fn complete_programmatic_close(self: &Arc<Self>, session_id: u64) {
        if finalize_lxapp_close(self, session_id) {
            self.sync_host_ui();
        }
    }
}

impl LxAppDelegate for LxApp {
    fn on_lxapp_opened(self: Arc<Self>, path: String, session_id: u64) -> String {
        let current_session = self.session_id();
        if session_id != current_session || self.session.is_cancelled() {
            return String::new();
        }

        let previous_appid = lxapp::get_current_lxapp().0;

        let raw_url = if path.is_empty() {
            self.config().get_initial_route()
        } else {
            path
        };

        let resolved = crate::route::resolve_route(&self, &raw_url).unwrap_or_else(|e| {
            error!("Failed to resolve page url '{}': {}", raw_url, e)
                .with_appid(self.appid.clone());
            crate::route::ResolvedRoute {
                original: raw_url.clone(),
                query: None,
                target: crate::route::RouteTarget::Normal {
                    path: raw_url.clone(),
                },
            }
        });

        let resolved_path = resolved.internal_path();
        let was_already_opened = self.is_opened();

        // An aside (panel) opens BESIDE the main: it neither hides the
        // previously active app nor becomes the current one on the
        // navigation stack — the main keeps selection, and app-targeted
        // APIs (tabbar, eval) keep resolving to the main.
        let opened_as_panel = matches!(
            self.state.lock().unwrap().startup_options.open_mode,
            lingxia_platform::traits::app_runtime::LxAppOpenMode::Panel
        );

        // When switching to this app, hide the previously active app (if any).
        if !opened_as_panel
            && !previous_appid.is_empty()
            && previous_appid != self.appid
            && let Some(previous) = lxapp::try_get(&previous_appid)
        {
            let args = crate::lifecycle::AppServiceEventArgs {
                source: crate::lifecycle::AppServiceEventSource::Lxapp,
                reason: crate::lifecycle::AppServiceEventReason::SwitchAway,
            }
            .to_json_string();
            let _ = previous.appservice_notify(AppServiceEvent::OnHide, Some(args));
        }

        // Move this app to the top of the navigation stack.
        if !opened_as_panel && let Some(manager) = lxapp::get_lxapps_manager() {
            manager.remove_from_stack(&self.appid);
            manager.push_lxapp_stack(self.appid.clone());
        }

        if !was_already_opened {
            let page = self.get_or_create_page(&resolved_path);
            if let Some(query) = resolved.query.clone() {
                page.set_query(query);
            }
            if page.is_tabbar_page() {
                // Ensure TabBar is visible and selected index matches the resolved path.
                self.with_tabbar_mut(|t| {
                    t.set_visible(true);
                    if let Some(index) = t.find_index_by_path(&resolved_path) {
                        t.set_selected_index(index);
                    }
                });
            }
            let _ = self.push_to_page_stack(&page);
            // The landing page is the first entry. Handshake used to auto-boot
            // onLoad for every Idle page, which also fired it on preloaded
            // tabs the user had never opened.
            page.dispatch_lifecycle_event(PageLifecycleEvent::OnLoad);
            // Pre-create tab pages (synchronously enqueue); FIFO ordering ensures CreateAppSvc precedes these.
            // Harmony's NWeb spawn process is SIGKILL'd when several Web
            // components are created in one burst (home tabs + guest tabs).
            // Overflow tabs already load on first pick; on Harmony the strip
            // tabs do too.
            if !cfg!(target_env = "ohos")
                && let Some(tab_pages) = self.get_tabbar().map(|t| t.preload_page_paths())
            {
                for tab_path in tab_pages {
                    if tab_path == resolved_path {
                        continue;
                    }
                    let _ = self.get_or_create_page(&tab_path);
                }
            }
            self.set_status(LxAppSessionStatus::Opening);
            if let Err(e) = self.ensure_app_launch_dispatched() {
                error!("Failed to trigger onLaunch service: {}", e).with_appid(self.appid.clone());
            }
            self.set_status(LxAppSessionStatus::Opened);

            // Update last_open_at in metadata for this installed app
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs() as i64)
                .unwrap_or_default();
            let _ = lxapp::metadata::touch_last_open(&self.appid, self.release_type, now);
        } else if self.peek_current_page_path().as_deref() != Some(resolved_path.as_str()) {
            // Reopening a live instance *at a named page* — a notification
            // target, an App Link, a host route. A reopen that names no page
            // never reaches here (it returns through `reenter_from_link`), so
            // the landing page has to join the stack the way a push does.
            // Without this the page renders while `getCurrentPages()` still
            // reports the old top, and back leaves from the wrong entry.
            let page = self.get_or_create_page(&resolved_path);
            // The query rides the startup options for a named page; only a
            // link-shaped target carries its own on the resolved route.
            let query = resolved
                .query
                .clone()
                .unwrap_or_else(|| self.state.lock().unwrap().startup_options.query.clone());
            page.set_query(query);
            let _ = self.push_to_page_stack(&page);
            // Entering the page is what starts it. Without this the instance
            // sits `unstarted` behind an attached but empty WebView — onLoad
            // is allowed to repeat for a re-navigation carrying new params.
            page.dispatch_lifecycle_event(PageLifecycleEvent::OnLoad);
        }

        // Ensure status reflects opened (both first open and reopen)
        self.set_status(LxAppSessionStatus::Opened);

        // Cancel any pending delayed-destroy now that the app is reopened.
        if let Some(manager) = lxapp::get_lxapps_manager() {
            manager.cancel_delayed_destroy(&self.appid);
        }

        // App-level onShow still fires here (app layer), independent of page service readiness.
        // Cold AppLink already went out on onLaunch (`scene` consumed). Replay
        // query/scene only on re-entry so a `scene === 8003` handler does not hop twice.
        let options = self.state.lock().unwrap().startup_options.clone();
        let mut args = if was_already_opened {
            options.launch_options_value()
        } else {
            serde_json::json!({})
        };
        if let serde_json::Value::Object(map) = &mut args {
            map.insert(
                "source".to_string(),
                serde_json::to_value(crate::lifecycle::AppServiceEventSource::Lxapp)
                    .unwrap_or_else(|_| serde_json::Value::String("lxapp".to_string())),
            );
            map.insert(
                "reason".to_string(),
                serde_json::to_value(if was_already_opened {
                    crate::lifecycle::AppServiceEventReason::SwitchBack
                } else {
                    crate::lifecycle::AppServiceEventReason::Open
                })
                .unwrap_or_else(|_| serde_json::Value::String("unknown".to_string())),
            );
        }
        let args_str = serde_json::to_string(&args).ok();
        let _ = self.appservice_notify(AppServiceEvent::OnShow, args_str);
        self.consume_app_link_scene();
        self.trigger_home_update_check_once();

        if self.has_pending_restart_request()
            && let Err(e) = self.restart()
        {
            error!("Deferred restart after open failed: {}", e).with_appid(self.appid.clone());
        }

        self.sync_host_ui();

        // After the incoming app is shown: budgeting on the outgoing app's
        // onHide would see both hidden and reclaim the one being entered.
        lxapp::page_discard::enforce_page_webview_budget();

        resolved_path
    }

    fn on_lxapp_closed(self: &Arc<Self>, session_id: u64) {
        if !finalize_lxapp_close(self, session_id) {
            return;
        }

        // Native close callbacks arrive while Logic is still alive.
        notify_lxapp_close(self);
        self.sync_host_ui();
    }

    fn on_page_show(self: &Arc<Self>, path: String) {
        // Platform containers report either a bare route path or the
        // webview's tag-derived identity (`path#instance[#session]`). When
        // the instance segment is present, resolve by it — a route can have
        // several live instances.
        let reported = path;
        let mut segments = reported
            .split('?')
            .next()
            .unwrap_or(reported.as_str())
            .split('#');
        let path = segments.next().unwrap_or(reported.as_str()).to_string();
        let instance_id = segments.next().filter(|segment| !segment.is_empty());
        let page = match instance_id
            .and_then(|id| self.get_page_by_instance_id_str(id))
            .or_else(|| self.get_page(&path))
        {
            Some(page) => page,
            None if instance_id.is_none() && self.has_isolated_page(&path) => {
                // A surface's page container reports the bare route it was
                // asked to present, which cannot name the isolated instance it
                // actually holds. Its visibility already arrives through
                // `notify_page_instance`, so there is nothing to do here.
                debug!("Path-keyed show for an isolated instance: {}", reported)
                    .with_appid(self.appid.clone())
                    .with_path(path.clone());
                return;
            }
            None => {
                debug!(
                    "Dropping show callback for departed PageInstance: {}",
                    reported
                )
                .with_appid(self.appid.clone())
                .with_path(path.clone());
                return;
            }
        };

        page.dispatch_lifecycle_event(PageLifecycleEvent::OnShow);

        // Mark the page as active for LRU tracking
        page.mark_active();

        // Re-resolve Auto against the product, then re-stamp the document.
        // A backgrounded (paused) webview can drop the broadcast of a host
        // pin, and a reused session may still hold the previous scheme.
        self.adopt_host_appearance();
        self.republish_page_scheme(&page);

        self.sync_host_ui();
    }

    fn on_lxapp_event(self: &Arc<Self>, event_type: LxAppUiEventType, data: String) -> bool {
        info!("UI event received: {:?}, data: {}", event_type, data).with_appid(self.appid.clone());

        let handled = match event_type {
            LxAppUiEventType::TabBarClick => self.handle_tabbar_click(data),
            LxAppUiEventType::CapsuleClick => self.handle_capsule_click(data),
            LxAppUiEventType::NavigationClick => self.handle_navigation_click(data),
            LxAppUiEventType::BackPress => self.handle_back_press(),
            LxAppUiEventType::PullDownRefresh => self.handle_pull_down_refresh(data),
        };

        self.sync_host_ui();

        handled
    }
}

impl LxApp {
    /// Handle TabBar item click
    fn handle_tabbar_click(self: &Arc<Self>, data: String) -> bool {
        if let Ok(index) = data.parse::<usize>() {
            info!("TabBar item {} clicked", index).with_appid(self.appid.clone());

            if let Some(tabbar) = self.get_tabbar()
                && tabbar.get_selected_index() == index as i32
            {
                return true; // Already selected, do nothing
            }

            // Let page.navigate own the committed selection; Windows may mirror it early
            // to keep native chrome responsive while the target WebView finishes loading.
            // `index` is the declaration index in `lxapp.json`, not the host's
            // visible-slot position (`showOn` can drop items from the strip).
            let tab_pages = self
                .get_tabbar()
                .map(|t| t.get_tabbar_pages())
                .unwrap_or_default();
            let Some(tab_path) = tab_pages.get(index).cloned() else {
                error!("Invalid tab index: {}", index).with_appid(self.appid.clone());
                return false;
            };
            // A just-opened guest can race the first page onto the stack. Fall
            // back to the initial route so the click still SwitchTabs instead
            // of no-oping while the user is looking at the app.
            let current_page_path = self
                .peek_current_page_path()
                .unwrap_or_else(|| self.initial_route());
            if current_page_path.is_empty() {
                error!("Could not get current page to perform navigation")
                    .with_appid(self.appid.clone());
                return false;
            }
            let current_page = self
                .get_page(&current_page_path)
                .unwrap_or_else(|| self.get_or_create_page(&current_page_path));
            let target_page = self.get_or_create_page(&tab_path);
            if current_page
                .navigate_to(target_page, NavigationType::SwitchTab)
                .is_ok()
            {
                return true;
            }
            error!("Could not switch to tab index {}", index).with_appid(self.appid.clone());
        } else {
            error!("Invalid tab index format: {}", data).with_appid(self.appid.clone());
        }
        false
    }

    /// Handle capsule button click
    fn handle_capsule_click(self: &Arc<Self>, data: String) -> bool {
        info!("Capsule button '{}' clicked", data).with_appid(self.appid.clone());

        if let Some((generation, index)) = parse_more_action_token(&data) {
            return self.activate_more_action(generation, index);
        }

        match data.as_str() {
            "close" => {
                // Home has nothing beneath it to reveal: reset it to the entry
                // page in-session instead of closing — a session close/reopen
                // tears down live webviews and repaints on the way back.
                if self.is_home_lxapp {
                    return self.navigate_to_initial_route();
                }

                // Clear page stack when closing app
                if let Err(e) = self.clear_page_stack() {
                    error!("Failed to clear page stack: {}", e).with_appid(self.appid.clone());
                }
                if let Some(manager) = lxapp::get_lxapps_manager() {
                    manager.remove_from_stack(&self.appid);
                }

                // after SDK hides it, SDK should call get_current_lxapp to show another lxapp
                let _ = self
                    .runtime
                    .hide_lxapp(self.appid.clone(), self.session_id());
                return true;
            }
            "minimize" => {
                // Minimize the app (platform-specific behavior)
                info!("LxApp minimize requested").with_appid(self.appid.clone());
                return true;
            }
            "clean_cache_restart" => {
                // Clear cache directory and restart the LxApp
                info!("Clean cache & restart requested").with_appid(self.appid.clone());

                if let Err(e) = self.clear_user_cache() {
                    error!("Failed to clear user cache: {}", e).with_appid(self.appid.clone());
                }

                if let Err(e) = self.restart() {
                    error!("Failed to restart app after cache cleanup: {}", e)
                        .with_appid(self.appid.clone());
                    return false;
                }
                return true;
            }
            "clean_cache_restart_in_place" => {
                info!("Clean cache & in-place restart requested").with_appid(self.appid.clone());
                if let Err(e) = self.clear_user_cache() {
                    error!("Failed to clear user cache: {}", e).with_appid(self.appid.clone());
                }
                if let Err(e) = self.restart_in_place() {
                    error!("Failed to restart app in place after cache cleanup: {}", e)
                        .with_appid(self.appid.clone());
                    return false;
                }
                return true;
            }
            "restart" => {
                info!("Restart requested").with_appid(self.appid.clone());
                if let Err(e) = self.restart() {
                    error!("Failed to restart app: {}", e).with_appid(self.appid.clone());
                    return false;
                }
                return true;
            }
            "restart_in_place" => {
                info!("In-place restart requested").with_appid(self.appid.clone());
                if let Err(e) = self.restart_in_place() {
                    error!("Failed to restart app in place: {}", e).with_appid(self.appid.clone());
                    return false;
                }
                return true;
            }
            "uninstall" => {
                info!("Uninstall requested").with_appid(self.appid.clone());

                // Fully shutdown first so uninstall precondition (`!is_lxapp_open`) is satisfied.
                if let Err(e) = self.shutdown() {
                    error!("Failed to shutdown app before uninstall: {}", e)
                        .with_appid(self.appid.clone());
                    return false;
                }

                let appid = self.appid.clone();
                let lxapp = self.clone();
                std::mem::drop(crate::executor::spawn(async move {
                    let updater = UpdateManager::new(lxapp);
                    if let Err(e) = updater.uninstall_all(&appid) {
                        error!("Failed to uninstall app: {}", e).with_appid(appid);
                    }
                }));
                return true;
            }
            _ => {
                error!("Unknown capsule action: {}", data).with_appid(self.appid.clone());
            }
        }
        false
    }

    /// Reset to the entry page in-session: SwitchTab when the initial route is
    /// a tab page, reLaunch otherwise. Clears the page stack either way.
    fn navigate_to_initial_route(self: &Arc<Self>) -> bool {
        let home_route = self.config().get_initial_route();
        if self
            .peek_current_page_path()
            .is_some_and(|path| path == home_route)
        {
            return true;
        }

        let navigate_type = if let Some(tabbar) = self.get_tabbar() {
            if tabbar.is_tabbar_page(&home_route) {
                NavigationType::SwitchTab
            } else {
                NavigationType::Launch
            }
        } else {
            NavigationType::Launch
        };

        if let Some(path) = self.peek_current_page_path() {
            let page = self
                .get_page(&path)
                .unwrap_or_else(|| self.get_or_create_page(&path));
            let target_page = self.get_or_create_page(&home_route);
            let _ = page.navigate_to(target_page, navigate_type);
        }
        true
    }

    /// Handle navigation bar button click
    fn handle_navigation_click(self: &Arc<Self>, data: String) -> bool {
        info!("Navigation button '{}' clicked", data).with_appid(self.appid.clone());

        match data.as_str() {
            "back" => {
                if let Some(path) = self.peek_current_page_path()
                    && let Some(page) = self.get_page(path.as_str())
                {
                    let _ = page.navigate_back(1);
                    return true;
                }
                false
            }
            "home" => self.navigate_to_initial_route(),
            _ => {
                error!("Unknown navigation action: {}", data).with_appid(self.appid.clone());
                false
            }
        }
    }

    /// Handle back button press (system or navigation)
    fn handle_back_press(self: &Arc<Self>) -> bool {
        let stack_size = self.get_page_stack_size();
        info!("BackPress trigered, page stack size: {}", stack_size).with_appid(self.appid.clone());

        if stack_size <= 1 {
            // If it's the last page, hide this LxApp (except home app)
            if !self.is_home_lxapp {
                if let Some(manager) = lxapp::get_lxapps_manager() {
                    manager.remove_from_stack(&self.appid);
                }
                let _ = self
                    .runtime
                    .hide_lxapp(self.appid.clone(), self.session_id());
            }
            return true;
        }

        if let Some(path) = self.peek_current_page_path()
            && let Some(page) = self.get_page(path.as_str())
        {
            let _ = page.navigate_back(1);
            return true;
        }
        false
    }

    /// Handle pull-to-refresh event
    /// data: page path
    fn handle_pull_down_refresh(self: &Arc<Self>, data: String) -> bool {
        let path = if data.is_empty() {
            match self.peek_current_page_path() {
                Some(p) => p,
                None => return false,
            }
        } else {
            data
        };

        if !self.is_pull_down_refresh_enabled(&path) {
            if let Err(e) = self.runtime.stop_pull_down_refresh(&self.appid, &path) {
                error!("Failed to stop pull-to-refresh: {}", e).with_appid(self.appid.clone());
            }
            return false;
        }

        if let Some(page) = self.get_page(&path) {
            page.dispatch_lifecycle_event(PageLifecycleEvent::OnPullDownRefresh);
            true
        } else {
            error!("PageInstance not found for pull-to-refresh: {}", path)
                .with_appid(self.appid.clone());
            if let Err(e) = self.runtime.stop_pull_down_refresh(&self.appid, &path) {
                error!("Failed to stop pull-to-refresh: {}", e).with_appid(self.appid.clone());
            }
            false
        }
    }
}

fn parse_more_action_token(value: &str) -> Option<(u64, usize)> {
    let mut parts = value.split(':');
    if parts.next()? != "more" {
        return None;
    }
    let generation = parts.next()?.parse().ok()?;
    let index = parts.next()?.parse().ok()?;
    parts.next().is_none().then_some((generation, index))
}

#[cfg(test)]
mod more_action_tests {
    use super::parse_more_action_token;

    #[test]
    fn parses_only_complete_more_action_tokens() {
        assert_eq!(parse_more_action_token("more:42:1"), Some((42, 1)));
        assert_eq!(parse_more_action_token("more:42"), None);
        assert_eq!(parse_more_action_token("more:42:1:extra"), None);
        assert_eq!(parse_more_action_token("restart"), None);
    }
}