From a7ec9b97ab6a335a29336e398a7ea64421ec80f9 Mon Sep 17 00:00:00 2001 From: Tienson Qin Date: Fri, 4 Dec 2026 23:39:21 +0800 Subject: [PATCH 1/4] Fix mobile Recent navigation and Android surfaces --- .../logseq/AndroidFeedbackRecordingTest.kt | 105 ++++++++++++- .../logseq/ui/extensions/LiquidGlass.kt | 32 +++- .../logseq/ui/extensions/LogseqExtensions.kt | 4 +- shared/src/logseq/core/graph_read.ml | 4 +- shared/src/logseq/core/graph_read.mli | 2 + shared/src/logseq/core/mobile_session.ml | 28 ++-- shared/src/logseq/core/rpc_session.ml | 11 +- shared/src/logseq/core/session_outliner.ml | 66 +++++++- shared/src/logseq/core/session_outliner.mli | 2 + shared/src/logseq/core/session_types.ml | 8 + shared/src/logseq/core/session_types.mli | 4 + shared/src/logseq/view_screens.ml | 16 +- shared/src/logseq/view_screens.mli | 2 +- shared/src/logseq/view_settings.ml | 148 +++++------------- shared/src/logseq/view_settings.mli | 4 +- shared/test/logseq/mobile_session_test.ml | 50 ++++++ 16 files changed, 332 insertions(+), 154 deletions(-) diff --git a/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidFeedbackRecordingTest.kt b/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidFeedbackRecordingTest.kt index ab6d76509..5229f41a8 100644 --- a/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidFeedbackRecordingTest.kt +++ b/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidFeedbackRecordingTest.kt @@ -110,6 +110,12 @@ class AndroidFeedbackRecordingTest(private val scenario: String) { private fun pause() { drain(); captureFrame() } + private fun waitForSearchResult(uuid: String) { + ui.waitUntil(10_000) { + drain() + ui.onAllNodesWithTag("search.result.$uuid").fetchSemanticsNodes().isNotEmpty() + } + } private fun pauseWithoutDrain() = captureFrame() private fun captureFrame() { ui.waitForIdle(); Thread.sleep(1800) @@ -129,7 +135,7 @@ class AndroidFeedbackRecordingTest(private val scenario: String) { ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED) .first().window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING) } - private fun mount(page: Int, dark: Boolean = false) { + private fun mount(page: Int, dark: Boolean = false, darkTheme: String? = null) { val directory = File(context.cacheDir, "feedback-recording").apply { deleteRecursively(); mkdirs() } graph = File(directory, "graphs/feedback").apply { mkdirs() } if (scenario == "notifications") notificationFixture = recentNotifications(directory) @@ -159,8 +165,8 @@ class AndroidFeedbackRecordingTest(private val scenario: String) { apply(opened); apply(selected) host("local-graph-ids", """["feedback"]""") host("graph-loading", "false") - if (dark) host("settings", """{"appearance":"dark","language":"system","systemLanguage":"en-US","spellCheck":true,"autoCorrection":true,"sidebarTabs":[],"baseURL":"http://127.0.0.1:1","version":"QA","revision":"feedback"}""") - ui.setContent { MaterialExpressiveTheme(colorScheme = if (dark) LogseqTheme.darkScheme else LogseqTheme.lightScheme, typography = LogseqTheme.typography) { + if (dark) host("settings", """{"appearance":"dark","darkTheme":"${darkTheme ?: "black"}","language":"system","systemLanguage":"en-US","spellCheck":true,"autoCorrection":true,"sidebarTabs":[],"baseURL":"http://127.0.0.1:1","version":"QA","revision":"feedback"}""") + ui.setContent { MaterialExpressiveTheme(colorScheme = LogseqTheme.colorScheme(dark, darkTheme ?: "solarized"), typography = LogseqTheme.typography) { CompositionLocalProvider(dev.lui.LocalLuiThemeDark provides dark, LocalContentColor provides androidx.compose.material3.MaterialTheme.colorScheme.onBackground, dev.lui.LocalLuiSemanticColors provides LogseqTheme.semanticColors(androidx.compose.material3.MaterialTheme.colorScheme)) { @@ -195,20 +201,21 @@ class AndroidFeedbackRecordingTest(private val scenario: String) { } return inbox } - private fun mountProjection(projection: JSONObject) { + private fun mountProjection(projection: JSONObject, authenticationCode: Int = 3) { lateinit var native: LogseqNativeBridge val backend = LuiBackend(onEvent = { dispatchFixtureEvent(it, native) }, extensions = logseqExtensionRegistry { it }, icons = logseqIconResolver) filter = LuiPatchFilter(backend) native = LogseqNativeBridge(onPatch = { if (it.isNotEmpty()) filter.applyJson(it) }) bridge = native - val root = native.initialize(authenticationCode = 3) + val root = native.initialize(authenticationCode = authenticationCode) val result = JSONObject().put("graphName", "Recording graph") .put("selectedGraphId", "recording").put("isGraphUnlocked", true) .put("syncConnected", false).put("selectedPage", JSONObject.NULL) .put("nodeRoutes", JSONArray()).put("outlinerRows", JSONArray()) projection.keys().forEach { result.put(it, projection.get(it)) } - filter.applyJson(native.applySnapshot(JSONObject().put("ok", true).put("result", result).toString())) + native.applySnapshot(JSONObject().put("ok", true).put("result", result).toString()) + .takeIf { it.isNotEmpty() }?.let(filter::applyJson) ui.setContent { MaterialExpressiveTheme(colorScheme = LogseqTheme.lightScheme, typography = LogseqTheme.typography) { Box(Modifier.fillMaxSize().background(androidx.compose.material3.MaterialTheme.colorScheme.background) .logseqContentHostInsets()) { backend.Content(root) } @@ -231,6 +238,92 @@ class AndroidFeedbackRecordingTest(private val scenario: String) { } private fun recordCase() { when (scenario) { + "login-progress" -> { + mountProjection(JSONObject().put("selectedGraphId", JSONObject.NULL), authenticationCode = 1) + ui.onNodeWithTag("button.sign-in").performClick() + ui.onNodeWithTag("field.auth.email").performTextInput("tester@example.com") + ui.onNodeWithTag("field.auth.password").performTextInput("fixture-password") + instrumentation.runOnMainSync { + val activity = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED).first() + androidx.core.view.WindowCompat.getInsetsController(activity.window, activity.window.decorView) + .hide(androidx.core.view.WindowInsetsCompat.Type.ime()) + } + ui.onNodeWithTag("button.auth.submit").performClick() + pauseWithoutDrain() + ui.onNodeWithTag("auth.loading", useUnmergedTree = true).assertIsDisplayed() + if (verify) ui.onNodeWithTag("sign-in.loading", useUnmergedTree = true).assertDoesNotExist() + } + "search-empty-alignment" -> { + mount(1, dark = true) + ui.onNodeWithTag("button.search").performClick() + pause() + val screen = ui.onNodeWithTag("native-search-presentation", useUnmergedTree = true) + .getUnclippedBoundsInRoot() + val icon = ui.onNodeWithTag("search.empty.icon", useUnmergedTree = true) + .assertIsDisplayed().getUnclippedBoundsInRoot() + if (verify) assertEquals("Center the empty state across the search viewport", + (screen.left + screen.right).value / 2, (icon.left + icon.right).value / 2, 1f) + } + "confirmation-spacing" -> { + mount(1, dark = true) + fun checkDialog(dialogTag: String, actionTag: String) { + pause() + val dialog = ui.onNodeWithTag(dialogTag, useUnmergedTree = true) + .assertIsDisplayed().getUnclippedBoundsInRoot() + val action = ui.onNodeWithTag(actionTag, useUnmergedTree = true) + .assertIsDisplayed().getUnclippedBoundsInRoot() + if (verify) assertTrue("Use standard alert padding below the buttons", + dialog.bottom - action.bottom <= 32.dp) + } + ui.onNodeWithTag("button.overflow-menu").performClick() + ui.onNodeWithText("Delete", ignoreCase = true).performClick() + checkDialog("dialog.page-delete", "button.page-delete.confirm") + ui.onNodeWithTag("button.page-delete.cancel").performClick() + ui.onNodeWithTag("button.search").performClick() + ui.onNodeWithTag("field.search").performTextInput("print") + waitForSearchResult(uuid(12)) + pause() + ui.onNodeWithTag("search.result." + uuid(12)).performClick() + pause() + ui.onNodeWithTag("button.overflow-menu").performClick() + ui.onNodeWithText("Delete", ignoreCase = true).performClick() + checkDialog("dialog.page-delete", "button.page-delete.confirm") + ui.onNodeWithTag("button.page-delete.cancel").performClick() + ui.onNodeWithTag("button.search.close").performClick() + ui.onNodeWithTag("button.sidebar").performClick() + ui.onNodeWithTag("button.sidebar.settings").performClick() + ui.onNodeWithTag("button.sign-out").performScrollTo().performClick() + checkDialog("dialog.sign-out", "button.sign-out.confirm") + ui.onNodeWithTag("button.sign-out.cancel").performClick() + } + "recent-navigation" -> { + mount(1, dark = true) + apply(request("loadSidebar")) + ui.onNodeWithTag("button.search").performClick() + ui.onNodeWithTag("field.search").performTextInput("Formula") + val hits = JSONObject(request("searchNodes", "Formula")).getJSONObject("result").getJSONArray("searchResults") + val page = (0 until hits.length()).map(hits::getJSONObject).single { it.getBoolean("isPage") } + val target = page.getString("uuid") + waitForSearchResult(target) + pause() + ui.onNodeWithTag("search.result.$target").performClick() + pause() + ui.onNodeWithTag("button.search.close").performClick() + ui.onNodeWithTag("button.sidebar").performClick() + pause() + if (verify) { + val result = JSONObject(request("loadSidebar")).getJSONObject("result") + assertEquals(target, result.getJSONArray("recentPages").getJSONObject(0).getString("uuid")) + ui.onNodeWithTag("link.sidebar.page.$target").assertIsDisplayed() + } + } + "liquid-chrome" -> { + mount(1, dark = true, darkTheme = "black") + ui.onNodeWithTag("button.search").assertIsDisplayed() + ui.onNodeWithTag("button.overflow-menu").assertIsDisplayed() + ui.onNodeWithTag("tab.bottom.tasks").performClick() + pause() + } "slash-template" -> { mount(1) ignoreAdjustResize() diff --git a/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/LiquidGlass.kt b/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/LiquidGlass.kt index 10415dc9f..28d5b3bdd 100644 --- a/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/LiquidGlass.kt +++ b/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/LiquidGlass.kt @@ -1,6 +1,8 @@ package com.logseq.logseq.ui.extensions import android.os.Build +import androidx.compose.foundation.border +import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.shape.RoundedCornerShape @@ -19,6 +21,7 @@ import dev.chrisbanes.haze.HazeState import dev.chrisbanes.haze.glass.GlassStyle import dev.chrisbanes.haze.glass.hazeGlass import dev.chrisbanes.haze.rememberHazeState +import dev.lui.LocalLuiThemeDark /** Shared capture state for the small floating chrome surfaces. */ val LocalLogseqHazeState = compositionLocalOf { null } @@ -32,21 +35,37 @@ val LocalLogseqHazeState = compositionLocalOf { null } fun Modifier.logseqLiquidGlass( shape: RoundedCornerShape, elevation: Dp = 8.dp, + showOutline: Boolean = true, ): Modifier { val state = LocalLogseqHazeState.current ?: rememberHazeState() - // Haze's non-shader Glass fallback (Android 12L and below) does not - // synthesize Regular's base fill, so give only that path a theme tint. - val fallbackTint = MaterialTheme.colorScheme.surface.copy(alpha = 0.82f) - val style = remember(shape, fallbackTint) { + val colors = MaterialTheme.colorScheme + val dark = LocalLuiThemeDark.current ?: isSystemInDarkTheme() + val tint = when { + Build.VERSION.SDK_INT < 33 -> (if (dark) Color(0xff242424) else colors.surface).copy(alpha = 0.82f) + dark -> Color(0xff3f3f3f).copy(alpha = 0.48f) + else -> Color.Unspecified + } + val style = remember(shape, dark, tint) { GlassStyle.regular.then { shape(shape) // Centered light reads as a white dot inside small circular chrome. lightPosition(Alignment.TopCenter) - if (Build.VERSION.SDK_INT < 33) { - tint(fallbackTint) + if (dark) { + // Regular follows the system appearance. Use its dark optics + // when Logseq's own appearance setting selects dark mode. + specularIntensity(0.38f) + edgeShadow(Color.Black.copy(alpha = 0.32f)) + ambientResponse(0.08f) + contrast(0.08f) + whitePoint(-0.22f) + chromaMultiplier(1.1f) } + if (tint != Color.Unspecified) tint(tint) } } + val outline = if (showOutline && dark) { + Modifier.border(1.dp, colors.onSurface.copy(alpha = 0.12f), shape) + } else Modifier return this .shadow( elevation = elevation, @@ -55,6 +74,7 @@ fun Modifier.logseqLiquidGlass( ambientColor = Color.Black.copy(alpha = 0.16f), spotColor = Color.Black.copy(alpha = 0.20f), ) + .then(outline) .hazeGlass( input = HazeInput.Backdrop(state), style = style, diff --git a/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/LogseqExtensions.kt b/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/LogseqExtensions.kt index 80ffeaa32..0f5380731 100644 --- a/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/LogseqExtensions.kt +++ b/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/LogseqExtensions.kt @@ -379,7 +379,9 @@ fun logseqExtensionRegistry( .clip(CircleShape) .background(selection) if (dragPosition != null) { - indicatorModifier = indicatorModifier.logseqLiquidGlass(CircleShape, elevation = 0.dp) + indicatorModifier = indicatorModifier.logseqLiquidGlass( + CircleShape, elevation = 0.dp, showOutline = false, + ) } Box(indicatorModifier) } diff --git a/shared/src/logseq/core/graph_read.ml b/shared/src/logseq/core/graph_read.ml index ed600023c..76468db18 100644 --- a/shared/src/logseq/core/graph_read.ml +++ b/shared/src/logseq/core/graph_read.ml @@ -488,6 +488,8 @@ let built_in_class db eid = | Some (Ds.Keyword ident) -> S.starts_with ~prefix:"logseq.class/" ident | _ -> false +let recent_page_limit = 15 + let sidebar_pages decrypt_title db = let favorites = match favorite_page_eid db with @@ -615,7 +617,7 @@ let sidebar_pages decrypt_title db = | Seq.Nil -> Seq.Nil | Seq.Cons (x, rest) -> Seq.Cons (x, take (n - 1) rest) in - { favorites; recent_pages = List.of_seq (take 15 recent_seq) } + { favorites; recent_pages = List.of_seq (take recent_page_limit recent_seq) } let page_block decrypt_title db eid = match page_summary decrypt_title db eid with diff --git a/shared/src/logseq/core/graph_read.mli b/shared/src/logseq/core/graph_read.mli index 7b0630b9e..914412750 100644 --- a/shared/src/logseq/core/graph_read.mli +++ b/shared/src/logseq/core/graph_read.mli @@ -6,6 +6,8 @@ type sidebar_pages = ; recent_pages : Cache_model.entity_summary list } +val recent_page_limit : int + val value : Datascript.db -> int -> string -> Datascript.value option val latest_code_language : Datascript.db -> string option val display_type_for_eid : Datascript.db -> int -> string option diff --git a/shared/src/logseq/core/mobile_session.ml b/shared/src/logseq/core/mobile_session.ml index 87550b4f8..5a13e564f 100644 --- a/shared/src/logseq/core/mobile_session.ml +++ b/shared/src/logseq/core/mobile_session.ml @@ -25,6 +25,19 @@ let discard_value result = | Ok _ -> Ok () | Error message -> Error message +let load_page_uuids prefix catalog graph_id = + match Sqlite.restore_string catalog (prefix ^ graph_id) with + | None -> [] + | Some body -> + (try match Yojson.Basic.from_string body with + | `List values -> List.filter_map (function `String uuid -> Some uuid | _ -> None) values + | _ -> [] + with Yojson.Json_error _ -> []) + +let save_page_uuids prefix catalog graph_id uuids = + Sqlite.store_string catalog (prefix ^ graph_id) + (Yojson.Basic.to_string (`List (List.map (fun uuid -> `String uuid) uuids))) + let host_options ?journal_tasks ?show_journal_tasks (database : Database.mobile_database) ring catalog = let graph = database.graph in let visible_agenda () = @@ -40,17 +53,10 @@ let host_options ?journal_tasks ?show_journal_tasks (database : Database.mobile_ Some (fun () -> Sqlite.restore_string catalog graph_catalog_address) | None -> None); - load_collapsed_nodes = Option.map (fun catalog graph_id -> - match Sqlite.restore_string catalog ("logseq/collapsed-nodes/v1/" ^ graph_id) with - | None -> [] - | Some body -> - (try match Yojson.Basic.from_string body with - | `List values -> List.filter_map (function `String uuid -> Some uuid | _ -> None) values - | _ -> [] - with Yojson.Json_error _ -> [])) catalog; - save_collapsed_nodes = Option.map (fun catalog graph_id uuids -> - Sqlite.store_string catalog ("logseq/collapsed-nodes/v1/" ^ graph_id) - (Yojson.Basic.to_string (`List (List.map (fun uuid -> `String uuid) uuids)))) catalog; + load_collapsed_nodes = Option.map (load_page_uuids "logseq/collapsed-nodes/v1/") catalog; + save_collapsed_nodes = Option.map (save_page_uuids "logseq/collapsed-nodes/v1/") catalog; + load_recent_pages = Option.map (load_page_uuids "logseq/recent-pages/v1/") catalog; + save_recent_pages = Option.map (save_page_uuids "logseq/recent-pages/v1/") catalog; save_graph_catalog = (match catalog with | Some catalog -> diff --git a/shared/src/logseq/core/rpc_session.ml b/shared/src/logseq/core/rpc_session.ml index ddaef0213..9b628d108 100644 --- a/shared/src/logseq/core/rpc_session.ml +++ b/shared/src/logseq/core/rpc_session.ml @@ -1501,12 +1501,7 @@ let set_journal_title_format session fields = | Error message -> Rpc.failure "date_format_failed" message let select_page session payload = - match - ( payload - , match (host session).Types.graph_sidebar_pages with - | Some load -> load () - | None -> None ) - with + match payload, So.load_sidebar_pages session with | Some uuid, Some pages -> (match List.find_opt @@ -1515,8 +1510,9 @@ let select_page session payload = with | Some page -> clear_node_navigation session; - let _, zoom = So.sidebar_node_destination session page in + let destination, zoom = So.sidebar_node_destination session page in set_sidebar_page session page ~zoom; + So.record_page_visit session destination.uuid; snapshot_visible session | None -> Rpc.failure "unknown_page" "The selected page is not available") @@ -1554,6 +1550,7 @@ let open_node_with_route ~replace session fields = let open_route () = if replace then clear_node_navigation session; push_node_route session route; + So.record_page_visit session page.uuid; snapshot_visible session in if replace then after_finishing_outliner_edit session open_route else open_route () diff --git a/shared/src/logseq/core/session_outliner.ml b/shared/src/logseq/core/session_outliner.ml index d10ce3d7c..c4dbba405 100644 --- a/shared/src/logseq/core/session_outliner.ml +++ b/shared/src/logseq/core/session_outliner.ml @@ -4,15 +4,71 @@ module Model = Cache_model module Ops = Pending_ops module Outliner = Outliner_state +let recent_graph_id (session : Types.session) = + let state = Types.state session in + match state.active_graph_id, state.config with + | Some _ as graph_id, _ -> graph_id + | None, Some config when config.Api.graph_id <> "" -> Some config.graph_id + | None, _ -> None + +let recent_page_visits (session : Types.session) graph_id = + match Hashtbl.find_opt session.recent_page_visits graph_id with + | Some visits -> visits + | None -> + let visits = match session.host.load_recent_pages with + | Some load -> List.take Graph_read.recent_page_limit (load graph_id) + | None -> [] in + Hashtbl.replace session.recent_page_visits graph_id visits; + visits + +let record_page_visit (session : Types.session) uuid = + Option.iter (fun graph_id -> + let previous = recent_page_visits session graph_id in + match previous with + | first :: _ when first = uuid -> () + | _ -> + let visits = List.take Graph_read.recent_page_limit (uuid :: List.filter ((<>) uuid) previous) in + Hashtbl.replace session.recent_page_visits graph_id visits; + Option.iter (fun save -> + try save graph_id visits with + | Failure message | Sqlite3.Error message -> Types.debug ("Could not save recent pages: " ^ message)) + session.host.save_recent_pages) + (recent_graph_id session) + +let merge_recent_pages (session : Types.session) (sidebar : Graph_read.sidebar_pages) visits resolve = + match !(session.recent_pages_cache) with + | Some (base, cached_visits, result) when base == sidebar && cached_visits == visits -> result + | _ -> + let seen = Hashtbl.create Graph_read.recent_page_limit in + let newly_seen (page : Model.entity_summary) = + if Hashtbl.mem seen page.uuid then false + else (Hashtbl.add seen page.uuid (); true) in + let opened = List.filter_map (fun uuid -> match resolve uuid with + | Some ((page : Model.entity_summary), false) when + not (List.exists (fun (favorite : Model.entity_summary) -> favorite.uuid = page.uuid) sidebar.favorites) + && newly_seen page -> Some page + | _ -> None) visits in + let recent_pages = List.take Graph_read.recent_page_limit + (opened @ List.filter newly_seen sidebar.recent_pages) in + let result = { sidebar with recent_pages } in + session.recent_pages_cache := Some (sidebar, visits, result); + result + +let load_sidebar_pages (session : Types.session) = + Option.map (fun sidebar -> + match recent_graph_id session, session.host.graph_node_destination with + | Some graph_id, Some resolve -> + (match recent_page_visits session graph_id with + | [] -> sidebar + | visits -> merge_recent_pages session sidebar visits resolve) + | _ -> sidebar) + (Option.bind session.host.graph_sidebar_pages (fun load -> load ())) + let sidebar_pages (session : Types.session) = (* While deferred, snapshots ship an empty sidebar so the scan stays off the launch path; the "loadSidebar" dispatch disarms this. *) if (Types.state session).sidebar_deferred then Types.empty_sidebar - else - match (Types.host session).graph_sidebar_pages with - | Some load -> - (match load () with Some sidebar -> sidebar | None -> Types.empty_sidebar) - | None -> Types.empty_sidebar + else Option.value (load_sidebar_pages session) ~default:Types.empty_sidebar let summary_candidate (page : Model.entity_summary) = { Outliner.label = page.title; value = page.uuid } diff --git a/shared/src/logseq/core/session_outliner.mli b/shared/src/logseq/core/session_outliner.mli index 00e5bcaf7..02d4f406e 100644 --- a/shared/src/logseq/core/session_outliner.mli +++ b/shared/src/logseq/core/session_outliner.mli @@ -1,6 +1,8 @@ (** Outliner context/state helpers layered over session state. *) +val load_sidebar_pages : Session_types.session -> Graph_read.sidebar_pages option val sidebar_pages : Session_types.session -> Graph_read.sidebar_pages +val record_page_visit : Session_types.session -> string -> unit val uses_paged_tag_objects : Session_types.session -> bool val outliner_context_with_blocks : diff --git a/shared/src/logseq/core/session_types.ml b/shared/src/logseq/core/session_types.ml index c12b042c4..4125317d3 100644 --- a/shared/src/logseq/core/session_types.ml +++ b/shared/src/logseq/core/session_types.ml @@ -146,6 +146,8 @@ type host_options = ; load_graph_catalog : (unit -> string option) option ; load_collapsed_nodes : (string -> string list) option ; save_collapsed_nodes : (string -> string list -> unit) option + ; load_recent_pages : (string -> string list) option + ; save_recent_pages : (string -> string list -> unit) option ; save_graph_catalog : (string -> unit) option } @@ -187,6 +189,8 @@ type session = { host : host_options ; state : session_state ref ; collapsed_nodes : (string, Outliner_state.Sset.t) Hashtbl.t + ; recent_page_visits : (string, string list) Hashtbl.t + ; recent_pages_cache : (Graph.sidebar_pages * string list * Graph.sidebar_pages) option ref ; reference_cache : (string, Model.block list) Hashtbl.t ; reference_collapsed : (string option * string, bool) Hashtbl.t ; result_view_cache : Result_view.cache @@ -262,6 +266,8 @@ let default_options = save_graph_catalog = None; load_collapsed_nodes = None; save_collapsed_nodes = None; + load_recent_pages = None; + save_recent_pages = None; } let state session = !(session.state) @@ -321,6 +327,8 @@ let create_session ?(journal_tasks = Journal_task_dates.create_cache ()) options { host = options; collapsed_nodes = Hashtbl.create 4; + recent_page_visits = Hashtbl.create 4; + recent_pages_cache = ref None; reference_cache = Hashtbl.create 8; reference_collapsed = Hashtbl.create 32; result_view_cache = Result_view.create_cache (); diff --git a/shared/src/logseq/core/session_types.mli b/shared/src/logseq/core/session_types.mli index 1a73bd644..054c61471 100644 --- a/shared/src/logseq/core/session_types.mli +++ b/shared/src/logseq/core/session_types.mli @@ -139,6 +139,8 @@ type host_options = ; load_graph_catalog : (unit -> string option) option ; load_collapsed_nodes : (string -> string list) option ; save_collapsed_nodes : (string -> string list -> unit) option + ; load_recent_pages : (string -> string list) option + ; save_recent_pages : (string -> string list -> unit) option ; save_graph_catalog : (string -> unit) option } @@ -180,6 +182,8 @@ type session = { host : host_options ; state : session_state ref ; collapsed_nodes : (string, Outliner_state.Sset.t) Hashtbl.t + ; recent_page_visits : (string, string list) Hashtbl.t + ; recent_pages_cache : (Graph_read.sidebar_pages * string list * Graph_read.sidebar_pages) option ref ; reference_cache : (string, Cache_model.block list) Hashtbl.t ; reference_collapsed : (string option * string, bool) Hashtbl.t ; result_view_cache : Result_view.cache diff --git a/shared/src/logseq/view_screens.ml b/shared/src/logseq/view_screens.ml index ca31cb09e..c1412affa 100644 --- a/shared/src/logseq/view_screens.ml +++ b/shared/src/logseq/view_screens.ml @@ -150,8 +150,8 @@ let search_result_list model_source send : t = | _ -> ()) [search_result_entries model_source send]) -let search_screen model_source send : t = - column ~grow:1.0 ~accessibility_identifier:"screen.search" +let search_screen ?cross model_source send : t = + column ~grow:1.0 ?cross ~accessibility_identifier:"screen.search" [ if_ ~test:(Signal.map View_base.search_empty_state_present_ @@ -1022,8 +1022,8 @@ let native_search_view ?base (_context : Lui_ui.ui_context) model_source send : ~test: (Signal.map View_base.kotlin_search_root_visible_ shell_model) - (column ~grow:1.0 ~background:"background" - [ search_screen shell_model send ]); + (column ~grow:1.0 ~cross:`stretch ~background:"background" + [ search_screen ~cross:`stretch shell_model send ]); native_node_stack context model_source ~source:(Signal.map View_base.search_node_routes shell_model) send; ]) @@ -1319,10 +1319,10 @@ let application_main_content (context : Lui_ui.ui_context) model_source (View_graphs.graph_password_sheet context shell_model send); if_ ~test:(Signal.map View_base.node_deletion_pending_ shell_model) - (View_settings.page_delete_dialog shell_model context send); + (View_settings.page_delete_dialog shell_model send); if_ ~test:(Signal.map View_base.sign_out_pending_ shell_model) - (View_settings.sign_out_dialog shell_model context send); + (View_settings.sign_out_dialog shell_model send); if_ ~test:(Signal.map View_base.model_sync_details_open_ shell_model) @@ -1364,10 +1364,10 @@ let application_main_content (context : Lui_ui.ui_context) model_source (View_graphs.graph_password_sheet context model_source send); if_ ~test:(Signal.map View_base.node_deletion_pending_ model_source) - (View_settings.page_delete_dialog model_source context send); + (View_settings.page_delete_dialog model_source send); if_ ~test:(Signal.map View_base.sign_out_pending_ model_source) - (View_settings.sign_out_dialog model_source context send); + (View_settings.sign_out_dialog model_source send); if_ ~test:(Signal.map View_base.model_sync_details_open_ model_source) diff --git a/shared/src/logseq/view_screens.mli b/shared/src/logseq/view_screens.mli index bce489013..9a0436c03 100644 --- a/shared/src/logseq/view_screens.mli +++ b/shared/src/logseq/view_screens.mli @@ -3,7 +3,7 @@ val search_result_row : Model.search_hit Signal.signal -> (Model.logseq_action -> 'a) -> Lui_elements.t val search_screen : - Model.logseq_model Signal.signal -> + ?cross:Lui_elements.cross_alignment -> Model.logseq_model Signal.signal -> (Model.logseq_action -> 'a) -> Lui_elements.t val capture_and_search_row : Lui_ui.ui_context -> diff --git a/shared/src/logseq/view_settings.ml b/shared/src/logseq/view_settings.ml index 85bb83272..5d8b32060 100644 --- a/shared/src/logseq/view_settings.ml +++ b/shared/src/logseq/view_settings.ml @@ -474,12 +474,15 @@ let settings_sign_out_row model_source (context : Lui_ui.ui_context) send : t = list_item ~foreground:"red" ~accessibility_identifier:id ~on_press ~text:label [] let sign_in_label ?(centered = false) model_source : t = - row ~main:(if centered then `center else `start) ~gap:8 ~cross:`center [ - if_ ~test:(Signal.map View_base.authentication_signing_in_ model_source) - (spinner ~width:16 ~height:16 ~accessibility_identifier:"sign-in.loading" []); - text ~value:(reactive (Signal.map (fun current -> - if View_base.authentication_signing_in_ current then "Signing in…" else "Sign in") model_source)) []; - ] + custom (fun context parent -> + let signing_in = Signal.map (fun current -> + View_base.authentication_signing_in_ current + && (Lui_ui.host context <> KotlinHost || not current.Model.authentication_form.opened)) model_source in + mount context ?parent (row ~main:(if centered then `center else `start) ~gap:8 ~cross:`center [ + if_ ~test:signing_in + (spinner ~width:16 ~height:16 ~accessibility_identifier:"sign-in.loading" []); + text ~value:(reactive (fun busy -> if busy then "Signing in…" else "Sign in") signing_in) []; + ])) let settings_account_row model_source send : t = let signed_out = Signal.map View_base.authentication_required_ model_source in @@ -494,59 +497,24 @@ let settings_account_row model_source send : t = ~text:(View_base.tr (Signal.sample model_source) "Edit Profile") []); ] -let sign_out_dialog model_source (context : Lui_ui.ui_context) send : t = - if Lui_ui.host context = KotlinHost then - dialog ~text:(View_base.tr (Signal.sample model_source) "Sign out?") ~height:280 - ~accessibility_identifier:"dialog.sign-out" - ~on_dismiss:(press send Model.CancelSignOut) - [ - column ~gap:16 ~cross:`stretch - [ - text - ~value: - "Sync will pause. Downloaded graphs remain available on this device." - ~grow:1.0 []; - spacer ~grow:1.0 []; - row ~main:`end_ - [ - toolbar ~orientation:`horizontal ~toolbar_gap:12 - ~label:(View_base.tr (Signal.sample model_source) "Sign out actions") - ~accessibility_identifier:"toolbar.sign-out" - [ - Lui_elements.toolbar_button ~variant:`ghost ~style_class:"cancellation-action" - ~accessibility_identifier: - "button.sign-out.cancel" - ~on_press:(press send Model.CancelSignOut) - ~text:(View_base.tr (Signal.sample model_source) "Cancel") []; - Lui_elements.toolbar_button ~variant:`destructive - ~accessibility_identifier: - "button.sign-out.confirm" - ~on_press:(press send Model.SignOut) - ~text:(View_base.tr (Signal.sample model_source) "Sign Out") []; - ]; - ]; - ]; - ] - else - (* Text-and-buttons-only children keep the dialog on the native alert - path (rich children fall back to a custom sheet). *) - dialog ~text:(View_base.tr (Signal.sample model_source) "Sign out?") ~style_class:"alert" - ~accessibility_identifier:"dialog.sign-out" - ~on_dismiss:(press send Model.CancelSignOut) - [ - text - ~value: - "Sync will pause. Downloaded graphs remain available on this device." - []; - button ~style_class:"cancellation-action" - ~accessibility_identifier:"button.sign-out.cancel" - ~on_press:(press send Model.CancelSignOut) - ~text:(View_base.tr (Signal.sample model_source) "Cancel") []; - button ~variant:`destructive - ~accessibility_identifier:"button.sign-out.confirm" - ~on_press:(press send Model.SignOut) - ~text:(View_base.tr (Signal.sample model_source) "Sign Out") []; - ] +let sign_out_dialog model_source send : t = + dialog ~text:(View_base.tr (Signal.sample model_source) "Sign out?") ~style_class:"alert" + ~accessibility_identifier:"dialog.sign-out" + ~on_dismiss:(press send Model.CancelSignOut) + [ + text + ~value: + "Sync will pause. Downloaded graphs remain available on this device." + []; + button ~style_class:"cancellation-action" + ~accessibility_identifier:"button.sign-out.cancel" + ~on_press:(press send Model.CancelSignOut) + ~text:(View_base.tr (Signal.sample model_source) "Cancel") []; + button ~variant:`destructive + ~accessibility_identifier:"button.sign-out.confirm" + ~on_press:(press send Model.SignOut) + ~text:(View_base.tr (Signal.sample model_source) "Sign Out") []; + ] let settings_kotlin_screen (context : Lui_ui.ui_context) model_source send : t = @@ -911,58 +879,26 @@ let settings_sheet (context : Lui_ui.ui_context) model_source send : t = node) else settings_main_sheet context model_source send -let page_delete_dialog model_source (context : Lui_ui.ui_context) send : t = +let page_delete_dialog model_source send : t = let label page block = Signal.map (fun (model : Model.logseq_model) -> View_base.tr model (match model.pending_node_deletion with | Some (Model.BlockToDelete _) -> block | _ -> page)) model_source in let title = label "Delete page?" "Delete block?" in let description = label "The page will be moved to Recycle." "The block and its children will be deleted." in - if Lui_ui.host context = KotlinHost then - dialog ~text_signal:title ~height:280 - ~accessibility_identifier:"dialog.page-delete" - ~on_dismiss:(press send Model.CancelDeleteActiveNode) - [ - column ~gap:16 ~cross:`stretch - [ - text ~value:(reactive description) ~grow:1.0 []; - spacer ~grow:1.0 []; - row ~main:`end_ - [ - toolbar ~orientation:`horizontal ~toolbar_gap:12 - ~label:(View_base.tr (Signal.sample model_source) "Page deletion actions") - ~accessibility_identifier:"toolbar.page-delete" - [ - Lui_elements.toolbar_button ~variant:`ghost ~style_class:"cancellation-action" - ~accessibility_identifier: - "button.page-delete.cancel" - ~on_press:(press send Model.CancelDeleteActiveNode) - ~text:(View_base.tr (Signal.sample model_source) "Cancel") []; - Lui_elements.toolbar_button ~variant:`destructive - ~accessibility_identifier: - "button.page-delete.confirm" - ~on_press:(press send Model.ConfirmDeleteActiveNode) - ~text:(View_base.tr (Signal.sample model_source) "Delete") []; - ]; - ]; - ]; - ] - else - (* Text-and-buttons-only children keep the dialog on the native alert - path (rich children fall back to a custom sheet). *) - dialog ~text_signal:title ~style_class:"alert" - ~accessibility_identifier:"dialog.page-delete" - ~on_dismiss:(press send Model.CancelDeleteActiveNode) - [ - text ~value:(reactive description) []; - button ~style_class:"cancellation-action" - ~accessibility_identifier:"button.page-delete.cancel" - ~on_press:(press send Model.CancelDeleteActiveNode) - ~text:(View_base.tr (Signal.sample model_source) "Cancel") []; - button ~variant:`destructive - ~accessibility_identifier:"button.page-delete.confirm" - ~on_press:(press send Model.ConfirmDeleteActiveNode) - ~text:(View_base.tr (Signal.sample model_source) "Delete") []; - ] + dialog ~text_signal:title ~style_class:"alert" + ~accessibility_identifier:"dialog.page-delete" + ~on_dismiss:(press send Model.CancelDeleteActiveNode) + [ + text ~value:(reactive description) []; + button ~style_class:"cancellation-action" + ~accessibility_identifier:"button.page-delete.cancel" + ~on_press:(press send Model.CancelDeleteActiveNode) + ~text:(View_base.tr (Signal.sample model_source) "Cancel") []; + button ~variant:`destructive + ~accessibility_identifier:"button.page-delete.confirm" + ~on_press:(press send Model.ConfirmDeleteActiveNode) + ~text:(View_base.tr (Signal.sample model_source) "Delete") []; + ] let sync_status_sheet (context : Lui_ui.ui_context) model_source send : t = let sync_now ?variant () = diff --git a/shared/src/logseq/view_settings.mli b/shared/src/logseq/view_settings.mli index 8318d2b9e..30cea1dd6 100644 --- a/shared/src/logseq/view_settings.mli +++ b/shared/src/logseq/view_settings.mli @@ -61,8 +61,8 @@ val settings_sheet : Lui_ui.ui_context -> Model.logseq_model Signal.signal -> (Model.logseq_action -> bool) -> Lui_elements.t -val page_delete_dialog : Model.logseq_model Signal.signal -> Lui_ui.ui_context -> (Model.logseq_action -> bool) -> Lui_elements.t -val sign_out_dialog : Model.logseq_model Signal.signal -> Lui_ui.ui_context -> (Model.logseq_action -> bool) -> Lui_elements.t +val page_delete_dialog : Model.logseq_model Signal.signal -> (Model.logseq_action -> bool) -> Lui_elements.t +val sign_out_dialog : Model.logseq_model Signal.signal -> (Model.logseq_action -> bool) -> Lui_elements.t val sync_status_sheet : Lui_ui.ui_context -> Model.logseq_model Signal.signal -> diff --git a/shared/test/logseq/mobile_session_test.ml b/shared/test/logseq/mobile_session_test.ml index 3e651e232..901d92453 100644 --- a/shared/test/logseq/mobile_session_test.ml +++ b/shared/test/logseq/mobile_session_test.ml @@ -465,6 +465,55 @@ let cold_launch_defers_sidebar_but_switching_graphs_loads_it () = check_eq ~msg:"switching back replaces favorites with the selected graph" (favorite_ids (call "bootstrapGraph" (fields "graph-a"))) ["graph-a-page"]) +let recent_pages_follow_navigation_and_survive_offline_restart () = + with_favorite_graphs (fun host call fields cache _ -> + let module Ds = Datascript in + let module U = Yojson.Basic.Util in + let page index = "recent-page-" ^ string_of_int index in + let path id = List.assoc "activePath" (fields id) |> U.to_string in + let cap = Graph_read.recent_page_limit in + let prepare id = + cache id; + let db = match Graph_store.restore_db (path id) with + | Ok db -> db | Error message -> fail message in + let pages = List.init (cap + 1) (fun index -> + let eid = Ds.Entity_id (10 + index) in + [ Ds.Add (eid, "block/uuid", Ds.Uuid (page index)); + Ds.Add (eid, "block/name", Ds.String (page index)); + Ds.Add (eid, "block/title", Ds.String (page index)); + Ds.Add (eid, "block/updated-at", Ds.Int64 (Int64.of_int index)) ]) in + ignore (Ds.store (Ds.db_with (List.flatten pages) db)) in + let recent result = result |> U.member "recentPages" |> U.to_list + |> List.map (fun value -> U.member "uuid" value |> U.to_string) in + let select_graph id = + ignore (call "configure" ["graphId", `String id; "baseUrl", `String "https://example.com"; + "token", `String ""]); + call "bootstrapGraph" (("allowSnapshotDownload", `Bool false) :: fields id) in + let open_page kind uuid = recent (call "executeEffect" ["kind", `String kind; "text", `String uuid]) in + prepare "graph-a"; + prepare "graph-b"; + let initial = recent (select_graph "graph-a") in + check_eq (List.length initial) cap; + check (not (List.mem (page 0) initial)); + let from_link = open_page "open-node" (page 0) in + check_eq ~msg:"journal links promote pages outside the original Recent list" + (List.hd from_link) (page 0); + let from_search = open_page "open-search-result" (page 1) in + let expected = List.take cap (page 1 :: page 0 :: List.filter ((<>) (page 1)) initial) in + Alcotest.(check (list string)) "search results promote pages without duplicates" expected from_search; + check_eq (List.length from_search) cap; + check_eq ~msg:"opening a favorite keeps it in the Favorites section" + (open_page "open-node" "graph-a-page") from_search; + let from_sidebar = open_page "select-sidebar-page" (page 0) in + check_eq ~msg:"a page added to Recent can be reopened from the sidebar" + (List.take 2 from_sidebar) [page 0; page 1]; + check_eq ~msg:"visits are isolated between graphs that share page UUIDs" + (recent (select_graph "graph-b")) initial; + let catalog_path = Filename.concat (Filename.dirname (path "graph-a")) "catalog.sqlite" in + ignore (Mobile_session.call host (open_request catalog_path)); + check_eq ~msg:"the local catalog retains Recent across a restart without credentials" + (recent (select_graph "graph-a")) from_sidebar) + let collapsed_nodes_survive_navigation_restart_and_graph_switches () = with_host (fun host dir -> let path = Filename.concat dir "catalog.sqlite" in @@ -931,6 +980,7 @@ let cases = case "sync errors follow operations through other acceptances and lost replies" sync_errors_follow_their_operations_through_other_acceptances_and_lost_replies; case "server rejections survive restart and stay graph scoped" server_rejections_survive_restart_and_remain_scoped_to_the_graph; case "collapsed nodes survive navigation restart and graph switches" collapsed_nodes_survive_navigation_restart_and_graph_switches; + case "recent pages follow navigation and survive an offline restart" recent_pages_follow_navigation_and_survive_offline_restart; case "first cached graph bootstrap loads favorites" first_cached_graph_bootstrap_loads_favorites; case "first download import loads favorites" first_download_import_loads_favorites; case "cold launch defers sidebar but switching graphs loads it" cold_launch_defers_sidebar_but_switching_graphs_loads_it; case "assets are stored inside the open graph" assets_are_stored_inside_the_open_graph; case "configured identity authors new nodes and survives reopen" configured_identity_authors_new_nodes_and_survives_reopen; From 9f82ef727d067986bfba5a31292e32efaad4b174 Mon Sep 17 00:00:00 2001 From: Tienson Qin Date: Fri, 4 Dec 2026 23:43:52 +0800 Subject: [PATCH 2/4] Exercise the block confirmation in the Android comparison --- .../logseq/AndroidFeedbackRecordingTest.kt | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidFeedbackRecordingTest.kt b/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidFeedbackRecordingTest.kt index 5229f41a8..94cd095dd 100644 --- a/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidFeedbackRecordingTest.kt +++ b/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidFeedbackRecordingTest.kt @@ -266,8 +266,9 @@ class AndroidFeedbackRecordingTest(private val scenario: String) { } "confirmation-spacing" -> { mount(1, dark = true) - fun checkDialog(dialogTag: String, actionTag: String) { + fun checkDialog(title: String, dialogTag: String, actionTag: String) { pause() + ui.onNodeWithText(title).assertIsDisplayed() val dialog = ui.onNodeWithTag(dialogTag, useUnmergedTree = true) .assertIsDisplayed().getUnclippedBoundsInRoot() val action = ui.onNodeWithTag(actionTag, useUnmergedTree = true) @@ -276,24 +277,21 @@ class AndroidFeedbackRecordingTest(private val scenario: String) { dialog.bottom - action.bottom <= 32.dp) } ui.onNodeWithTag("button.overflow-menu").performClick() - ui.onNodeWithText("Delete", ignoreCase = true).performClick() - checkDialog("dialog.page-delete", "button.page-delete.confirm") + ui.onNodeWithTag("button.page.delete").performClick() + checkDialog("Delete page?", "dialog.page-delete", "button.page-delete.confirm") ui.onNodeWithTag("button.page-delete.cancel").performClick() - ui.onNodeWithTag("button.search").performClick() - ui.onNodeWithTag("field.search").performTextInput("print") - waitForSearchResult(uuid(12)) - pause() - ui.onNodeWithTag("search.result." + uuid(12)).performClick() + ui.onNodeWithTag("button.outliner.zoom.${uuid(11)}.Journal content").performClick() pause() ui.onNodeWithTag("button.overflow-menu").performClick() - ui.onNodeWithText("Delete", ignoreCase = true).performClick() - checkDialog("dialog.page-delete", "button.page-delete.confirm") + ui.onNodeWithTag("button.block.delete").performClick() + checkDialog("Delete block?", "dialog.page-delete", "button.page-delete.confirm") ui.onNodeWithTag("button.page-delete.cancel").performClick() - ui.onNodeWithTag("button.search.close").performClick() + ui.onNodeWithTag("button.navigation.back").performClick() + drain() ui.onNodeWithTag("button.sidebar").performClick() ui.onNodeWithTag("button.sidebar.settings").performClick() ui.onNodeWithTag("button.sign-out").performScrollTo().performClick() - checkDialog("dialog.sign-out", "button.sign-out.confirm") + checkDialog("Sign out?", "dialog.sign-out", "button.sign-out.confirm") ui.onNodeWithTag("button.sign-out.cancel").performClick() } "recent-navigation" -> { From f90dbc13ec83fcb5ebc1f482db0dd08764e5a410 Mon Sep 17 00:00:00 2001 From: Tienson Qin Date: Sat, 5 Dec 2026 21:24:56 +0800 Subject: [PATCH 3/4] Preserve Recent order when opening favorites or reselecting pages --- apple/Sources/Logseq/LGRuntime.swift | 10 ++++-- shared/src/logseq/core/core_effect.ml | 1 + shared/src/logseq/core/rpc_session.ml | 23 +++++++++++++ shared/src/logseq/core/session_outliner.ml | 29 +++++++++++----- shared/src/logseq/core/session_outliner.mli | 1 + shared/src/logseq/model.ml | 15 +++++++-- shared/src/logseq/model.mli | 2 ++ shared/src/logseq/native_bridge.ml | 4 +++ shared/src/logseq/response_snapshot.ml | 4 ++- shared/test/logseq/app_test.ml | 20 ++++++++++- shared/test/logseq/mobile_session_test.ml | 37 +++++++++++++++++---- 11 files changed, 125 insertions(+), 21 deletions(-) diff --git a/apple/Sources/Logseq/LGRuntime.swift b/apple/Sources/Logseq/LGRuntime.swift index d660f6e22..8e47c8306 100644 --- a/apple/Sources/Logseq/LGRuntime.swift +++ b/apple/Sources/Logseq/LGRuntime.swift @@ -44,12 +44,18 @@ private struct LGCoreResponseEnvelope: Decodable, Sendable { let isSearchPatch: Bool? let isReferencePatch: Bool? let isQueryPatch: Bool? + let isRecentPagesPatch: Bool? let graphName: String? let outlinerCommandRevision: Int? let outlinerCommands: [LogseqOutlinerCommand]? let hasPendingSemanticOperations: Bool? let pendingSyncRequest: PendingSyncRequest? let pendingSyncError: String? + + var isContentPatch: Bool { + isOutlinerPatch == true || isOutlinerContentPatch == true || isSearchPatch == true + || isReferencePatch == true || isQueryPatch == true || isRecentPagesPatch == true + } } struct PendingSyncRequest: Decodable, Sendable {} @@ -234,7 +240,7 @@ public final class LGRuntime { if result.isPendingSyncPatch == true { return syncProjection(result) != lastCoreSyncProjection } - if result.isOutlinerPatch == true || result.isOutlinerContentPatch == true || result.isSearchPatch == true || result.isReferencePatch == true || result.isQueryPatch == true { + if result.isContentPatch { return true } return response != lastAuthoritativeCoreResponse @@ -252,7 +258,7 @@ public final class LGRuntime { if result.isPendingSyncPatch == true { lastCoreSyncProjection = syncProjection(result) authoritativeCoreResponseInvalidated = true - } else if result.isOutlinerPatch == true || result.isOutlinerContentPatch == true || result.isSearchPatch == true || result.isReferencePatch == true || result.isQueryPatch == true { + } else if result.isContentPatch { if result.isOutlinerPatch == true { lastCoreSyncProjection = syncProjection(result) } diff --git a/shared/src/logseq/core/core_effect.ml b/shared/src/logseq/core/core_effect.ml index d55cb3e3a..184865e87 100644 --- a/shared/src/logseq/core/core_effect.ml +++ b/shared/src/logseq/core/core_effect.ml @@ -62,6 +62,7 @@ let request ~now ~fresh_id payload = json "openNode" ["uuid", `String uuid; "reveal", `Bool (kind = "open-search-result")] | "close-node" -> empty "closeNode" | "select-sidebar-page" -> raw "selectPage" + | "record-sidebar-page-visit" -> raw "recordSidebarPageVisit" | "clear-selected-page" -> empty "clearSelectedPage" | "load-older-journals" -> empty "loadOlderJournals" | "load-flashcards" -> Ok ("loadFlashcards", Some (string_of_int (now ()))) diff --git a/shared/src/logseq/core/rpc_session.ml b/shared/src/logseq/core/rpc_session.ml index 9b628d108..8e17b21e7 100644 --- a/shared/src/logseq/core/rpc_session.ml +++ b/shared/src/logseq/core/rpc_session.ml @@ -1518,6 +1518,26 @@ let select_page session payload = Rpc.failure "unknown_page" "The selected page is not available") | _ -> Rpc.failure "invalid_params" "selectPage requires a page id" +let record_sidebar_page_visit session fields = + match Rpc.required_string fields "graphId", Rpc.required_string fields "uuid" with + | Ok graph_id, Ok uuid -> + let graph, recent = + match (state session).selected_sidebar_page with + | Some (page : Model.entity_summary) when page.uuid = uuid && So.recent_graph_id session = Some graph_id -> + let destination, _ = So.sidebar_node_destination session page in + So.record_page_visit session destination.uuid; + let recent = match So.load_sidebar_pages session with + | Some sidebar -> sidebar.Graph_read.recent_pages + | None -> [] in + `String graph_id, recent + | _ -> `Null, [] in + Rpc.success (Rpc.json_object [ + "isRecentPagesPatch", `Bool true; + "recentPagesGraphId", graph; + "recentPages", Rpc.json_list (List.map (summary_json session) recent); + ]) + | Error message, _ | _, Error message -> Rpc.failure "invalid_params" message + let after_finishing_outliner_edit session navigate = match Outliner.editing_uuid (state session).outliner_state with | None -> navigate () @@ -2670,6 +2690,9 @@ let rec dispatch session action payload = with_object "setJournalTitleFormat" payload "A date format is required" (fun _ fields -> set_journal_title_format session fields) | "selectPage" -> select_page session payload + | "recordSidebarPageVisit" -> + with_object action payload "A graph and page ID are required" + (fun _ fields -> record_sidebar_page_visit session fields) | "hydrateOutlinerRows" -> hydrate_outliner_rows session payload | "queryBlock" -> (match payload, query_db session with diff --git a/shared/src/logseq/core/session_outliner.ml b/shared/src/logseq/core/session_outliner.ml index c4dbba405..5fe6f6ffd 100644 --- a/shared/src/logseq/core/session_outliner.ml +++ b/shared/src/logseq/core/session_outliner.ml @@ -21,18 +21,32 @@ let recent_page_visits (session : Types.session) graph_id = Hashtbl.replace session.recent_page_visits graph_id visits; visits +let favorite_member (sidebar : Graph_read.sidebar_pages) uuid = + List.exists (fun (page : Model.entity_summary) -> page.uuid = uuid) sidebar.favorites + let record_page_visit (session : Types.session) uuid = Option.iter (fun graph_id -> let previous = recent_page_visits session graph_id in match previous with | first :: _ when first = uuid -> () | _ -> - let visits = List.take Graph_read.recent_page_limit (uuid :: List.filter ((<>) uuid) previous) in - Hashtbl.replace session.recent_page_visits graph_id visits; - Option.iter (fun save -> - try save graph_id visits with - | Failure message | Sqlite3.Error message -> Types.debug ("Could not save recent pages: " ^ message)) - session.host.save_recent_pages) + let is_favorite = + let db = if (Types.state session).sidebar_deferred then + Option.bind session.host.graph_db (fun load -> load ()) else None in + match db with + | Some db -> Graph_read.page_is_favorite db + | None -> + let sidebar = Option.bind session.host.graph_sidebar_pages (fun load -> load ()) in + fun uuid -> Option.exists (fun sidebar -> favorite_member sidebar uuid) sidebar in + if not (is_favorite uuid) then begin + let previous = List.filter (fun page -> page <> uuid && not (is_favorite page)) previous in + let visits = List.take Graph_read.recent_page_limit (uuid :: previous) in + Hashtbl.replace session.recent_page_visits graph_id visits; + Option.iter (fun save -> + try save graph_id visits with + | Failure message | Sqlite3.Error message -> Types.debug ("Could not save recent pages: " ^ message)) + session.host.save_recent_pages + end) (recent_graph_id session) let merge_recent_pages (session : Types.session) (sidebar : Graph_read.sidebar_pages) visits resolve = @@ -45,8 +59,7 @@ let merge_recent_pages (session : Types.session) (sidebar : Graph_read.sidebar_p else (Hashtbl.add seen page.uuid (); true) in let opened = List.filter_map (fun uuid -> match resolve uuid with | Some ((page : Model.entity_summary), false) when - not (List.exists (fun (favorite : Model.entity_summary) -> favorite.uuid = page.uuid) sidebar.favorites) - && newly_seen page -> Some page + not (favorite_member sidebar page.uuid) && newly_seen page -> Some page | _ -> None) visits in let recent_pages = List.take Graph_read.recent_page_limit (opened @ List.filter newly_seen sidebar.recent_pages) in diff --git a/shared/src/logseq/core/session_outliner.mli b/shared/src/logseq/core/session_outliner.mli index 02d4f406e..8ce41fb66 100644 --- a/shared/src/logseq/core/session_outliner.mli +++ b/shared/src/logseq/core/session_outliner.mli @@ -2,6 +2,7 @@ val load_sidebar_pages : Session_types.session -> Graph_read.sidebar_pages option val sidebar_pages : Session_types.session -> Graph_read.sidebar_pages +val recent_graph_id : Session_types.session -> string option val record_page_visit : Session_types.session -> string -> unit val uses_paged_tag_objects : Session_types.session -> bool diff --git a/shared/src/logseq/model.ml b/shared/src/logseq/model.ml index e01eaa531..d923b3b6a 100644 --- a/shared/src/logseq/model.ml +++ b/shared/src/logseq/model.ml @@ -297,6 +297,7 @@ type core_projection = ; is_pending_sync_patch : bool ; is_pending_sync_projection : bool ; is_graph_catalog_patch : bool + ; is_recent_pages_patch : bool ; is_graph_snapshot_recovery : bool ; projection_search_query : string ; search_offset : int @@ -394,6 +395,7 @@ type logseq_effect = | CloseSearchNodeEffect of int * string | AddRootBlockEffect of int * string | SelectSidebarPageEffect of int * string + | RecordSidebarPageVisitEffect of int * string * string | ClearSelectedPageEffect of int | LoadOlderJournalsEffect of int | FlashcardDeckEffect of int * string @@ -1082,6 +1084,7 @@ let effect_id eff = | CloseSearchNodeEffect (id, _) -> id | AddRootBlockEffect (id, _) -> id | SelectSidebarPageEffect (id, _) -> id + | RecordSidebarPageVisitEffect (id, _, _) -> id | ClearSelectedPageEffect id -> id | LoadOlderJournalsEffect id -> id | LoadFlashcardsEffect id | FlashcardDeckEffect (id, _) -> id @@ -2639,6 +2642,7 @@ let rec update (current : logseq_model) action = (* Uploads need the existing subscription to receive acknowledgements. *) let updated = if not projection.is_pending_sync_patch && not projection.is_pending_sync_projection + && not projection.is_recent_pages_patch && (applied.has_pending_semantic_operations || applied.has_pending_sync_request) && not (List.exists (function SyncNowEffect _ | SyncPendingEffect _ -> true | _ -> false) (applied.pending_effects @ applied.in_flight_effects)) @@ -3268,8 +3272,10 @@ let rec update (current : logseq_model) action = } uuid in - if reusable then updated - else enqueue_effect updated (SelectSidebarPageEffect (updated.next_effect_id, uuid)) + if not reusable then enqueue_effect updated (SelectSidebarPageEffect (updated.next_effect_id, uuid)) + else (match updated.selected_graph_id with + | Some graph_id -> enqueue_effect updated (RecordSidebarPageVisitEffect (updated.next_effect_id, graph_id, uuid)) + | None -> updated) | OpenQuickAction kind -> if not (List.mem kind ["capture"; "audio"; "camera"; "journal"; "task"]) then current @@ -3862,7 +3868,10 @@ and apply_core_snapshot (current : logseq_model) Journal_task_dates.apply_delta (if same_graph then current.journal_tasks else `Null) tasks | _ when same_graph -> current.journal_tasks | _ -> `Null in - if Option.is_some projection.reference_candidates_update then + if projection.is_recent_pages_patch then + if same_graph && Option.is_some graph_id then {current with recent_pages = projection.sidebar.recent_pages} + else current + else if Option.is_some projection.reference_candidates_update then match projection.reference_candidates_update with | Some (query, candidates) when projection.selected_graph_id = current.selected_graph_id && current.composer_reference_query = Some query -> diff --git a/shared/src/logseq/model.mli b/shared/src/logseq/model.mli index 7214fa08c..5e72c8e9c 100644 --- a/shared/src/logseq/model.mli +++ b/shared/src/logseq/model.mli @@ -282,6 +282,7 @@ type core_projection = ; is_pending_sync_patch : bool ; is_pending_sync_projection : bool ; is_graph_catalog_patch : bool + ; is_recent_pages_patch : bool ; is_graph_snapshot_recovery : bool ; projection_search_query : string ; search_offset : int @@ -379,6 +380,7 @@ type logseq_effect = | CloseSearchNodeEffect of int * string | AddRootBlockEffect of int * string | SelectSidebarPageEffect of int * string + | RecordSidebarPageVisitEffect of int * string * string | ClearSelectedPageEffect of int | LoadOlderJournalsEffect of int | FlashcardDeckEffect of int * string diff --git a/shared/src/logseq/native_bridge.ml b/shared/src/logseq/native_bridge.ml index 6e1ba9911..738018c2b 100644 --- a/shared/src/logseq/native_bridge.ml +++ b/shared/src/logseq/native_bridge.ml @@ -532,6 +532,10 @@ let encode_effect ?(model : Model.logseq_model option) (eff : Model.logseq_effec "{\"id\":" ^ string_of_int id ^ ",\"kind\":\"select-sidebar-page\",\"text\":" ^ Lui_wire.quoted uuid ^ "}" + | RecordSidebarPageVisitEffect (id, graph_id, uuid) -> + let payload = Yojson.Basic.to_string (`Assoc ["graphId", `String graph_id; "uuid", `String uuid]) in + "{\"id\":" ^ string_of_int id + ^ ",\"kind\":\"record-sidebar-page-visit\",\"text\":" ^ Lui_wire.quoted payload ^ "}" | ClearSelectedPageEffect id -> "{\"id\":" ^ string_of_int id ^ ",\"kind\":\"clear-selected-page\",\"text\":\"\"}" diff --git a/shared/src/logseq/response_snapshot.ml b/shared/src/logseq/response_snapshot.ml index 02ad2e86c..0d94a4117 100644 --- a/shared/src/logseq/response_snapshot.ml +++ b/shared/src/logseq/response_snapshot.ml @@ -491,7 +491,8 @@ let core_projection fields = (string_member "query" fields) | _ -> None); graph_name = string_member "graphName" fields; - selected_graph_id = string_member "selectedGraphId" fields; + selected_graph_id = string_member + (if bool_member "isRecentPagesPatch" fields then "recentPagesGraphId" else "selectedGraphId") fields; journal_title_format = string_member "journalTitleFormat" fields; graphs = List.filter_map graph (list_member "graphs" fields); is_graph_encrypted = bool_member "isGraphEncrypted" fields; @@ -582,6 +583,7 @@ let core_projection fields = is_pending_sync_patch = bool_member "isPendingSyncPatch" fields; is_pending_sync_projection = bool_member "isPendingSyncProjection" fields; is_graph_catalog_patch = bool_member "isGraphCatalogPatch" fields; + is_recent_pages_patch = bool_member "isRecentPagesPatch" fields; is_graph_snapshot_recovery = bool_member "isGraphSnapshotRecovery" fields } let error_message fields = diff --git a/shared/test/logseq/app_test.ml b/shared/test/logseq/app_test.ml index 023118f64..e96f38dc6 100644 --- a/shared/test/logseq/app_test.ml +++ b/shared/test/logseq/app_test.ml @@ -364,6 +364,7 @@ let empty_core_projection () = is_pending_sync_projection = false; is_graph_snapshot_recovery = false; is_graph_catalog_patch = false; + is_recent_pages_patch = false; projection_search_query = ""; search_offset = 0; search_has_more = false; @@ -9613,8 +9614,9 @@ let reselecting_the_current_page_preserves_loaded_rows () = let application = App.create (ios_backend ()) in let page = { Model.uuid = "page-a"; title = "Project"; page_journal_day = None} in let rows = thousand_nested_rows () in + let other = { page with Model.uuid = "page-b"; title = "Searched page" } in let sidebar = { (empty_sidebar_projection ()) with - Model.favorites = [ page ]; selected_page = Some page; + Model.recent_pages = [ other; page ]; selected_page = Some page; selected_page_is_tag = is_tag; related_rows = if is_tag then rows else [] } in start application; @@ -9635,6 +9637,22 @@ let reselecting_the_current_page_preserves_loaded_rows () = check ~msg:"reselecting the already loaded root does not request another full snapshot" (not (List.exists (function Model.SelectSidebarPageEffect _ -> true | _ -> false) (App.model application).pending_effects)); + check ~msg:"reselecting the already loaded root records a graph-scoped visit" + (List.exists (function Model.RecordSidebarPageVisitEffect (_, "test-graph", "page-a") -> true | _ -> false) + (App.model application).pending_effects); + let patch graph = Response_snapshot.decode_json_response (`Assoc ["ok", `Bool true; "result", `Assoc [ + "isRecentPagesPatch", `Bool true; "recentPagesGraphId", `String graph; + "recentPages", `List [`Assoc ["uuid", `String page.uuid; "title", `String page.title]; + `Assoc ["uuid", `String other.uuid; "title", `String other.title]]]]) in + let apply_patch graph = match patch graph with + | Ok projection -> send application (Model.ApplyCoreSnapshot projection); flush application + | Error message -> fail message in + apply_patch "another-graph"; + check_eq (App.model application).recent_pages [other; page]; + apply_patch "test-graph"; + check_eq (App.model application).recent_pages [page; other]; + check_eq ~msg:"a Recent patch keeps the open outline mounted" + (descendant_with_identifier renderer (main_root renderer application) "outliner.block.large-0") first; check_eq ~msg:"a loaded page never returns to a loading placeholder" (descendant_with_identifier renderer (main_root renderer application) "status.page-loading") (-1) diff --git a/shared/test/logseq/mobile_session_test.ml b/shared/test/logseq/mobile_session_test.ml index 901d92453..fcf449553 100644 --- a/shared/test/logseq/mobile_session_test.ml +++ b/shared/test/logseq/mobile_session_test.ml @@ -502,17 +502,42 @@ let recent_pages_follow_navigation_and_survive_offline_restart () = let expected = List.take cap (page 1 :: page 0 :: List.filter ((<>) (page 1)) initial) in Alcotest.(check (list string)) "search results promote pages without duplicates" expected from_search; check_eq (List.length from_search) cap; - check_eq ~msg:"opening a favorite keeps it in the Favorites section" - (open_page "open-node" "graph-a-page") from_search; + let full_history = List.init cap (fun i -> page (cap - 1 - i)) in + List.iter (fun uuid -> ignore (open_page "open-node" uuid)) (List.rev full_history); + check_eq ~msg:"opening a favorite from the sidebar keeps all visited pages" + (open_page "select-sidebar-page" "graph-a-page") full_history; + check_eq ~msg:"opening a favorite via a node link keeps all visited pages" + (open_page "open-node" "graph-a-page") full_history; + let catalog_path = Filename.concat (Filename.dirname (path "graph-a")) "catalog.sqlite" in + let restart () = ignore (Mobile_session.call host (open_request catalog_path)) in + restart (); + check_eq ~msg:"a favorite leaves the visit order intact after restart" + (recent (select_graph "graph-a")) full_history; let from_sidebar = open_page "select-sidebar-page" (page 0) in check_eq ~msg:"a page added to Recent can be reopened from the sidebar" - (List.take 2 from_sidebar) [page 0; page 1]; + (List.take 2 from_sidebar) [page 0; page (cap - 1)]; + ignore (open_page "open-search-result" (page cap)); + let session () = !(host.Mobile_session.session) in + ignore (Rpc_test.response_result (Rpc_test.dispatch_json (session ()) "closeNode" "")); + let state = (Session_types.state (session ())).outliner_state in + let record graph_id = call "executeEffect" ["kind", `String "record-sidebar-page-visit"; + "text", `String (Yojson.Basic.to_string (`Assoc ["graphId", `String graph_id; "uuid", `String (page 0)]))] in + let stale = record "graph-b" in + check_eq ~msg:"a visit for a different graph does not publish a recent list" + (U.member "recentPagesGraphId" stale) `Null; + let reselected = record "graph-a" in + check_eq ~msg:"a repeat tap returns only a graph-scoped Recent patch" + (U.member "isRecentPagesPatch" reselected, U.member "recentPagesGraphId" reselected, + U.member "selectedGraphId" reselected, U.member "outlinerRows" reselected) + (`Bool true, `String "graph-a", `Null, `Null); + check ~msg:"reselecting keeps the core outliner state" ((Session_types.state (session ())).outliner_state == state); + check_eq ~msg:"reselecting the open page promotes it after search" + (List.take 2 (recent reselected)) [page 0; page cap]; check_eq ~msg:"visits are isolated between graphs that share page UUIDs" (recent (select_graph "graph-b")) initial; - let catalog_path = Filename.concat (Filename.dirname (path "graph-a")) "catalog.sqlite" in - ignore (Mobile_session.call host (open_request catalog_path)); + restart (); check_eq ~msg:"the local catalog retains Recent across a restart without credentials" - (recent (select_graph "graph-a")) from_sidebar) + (recent (select_graph "graph-a")) (recent reselected)) let collapsed_nodes_survive_navigation_restart_and_graph_switches () = with_host (fun host dir -> From 2d0ee9f25320a339cd8942d9a4c24eccbf2ef175 Mon Sep 17 00:00:00 2001 From: Tienson Qin Date: Sat, 5 Dec 2026 21:35:01 +0800 Subject: [PATCH 4/4] Keep Recent order stable when reopening pages --- .../logseq/AndroidFeedbackRecordingTest.kt | 7 ++- apple/Sources/Logseq/LGRuntime.swift | 10 +--- shared/src/logseq/core/core_effect.ml | 1 - shared/src/logseq/core/rpc_session.ml | 25 +-------- shared/src/logseq/core/session_outliner.ml | 55 +++++++++---------- shared/src/logseq/core/session_outliner.mli | 3 +- shared/src/logseq/model.ml | 15 +---- shared/src/logseq/model.mli | 2 - shared/src/logseq/native_bridge.ml | 4 -- shared/src/logseq/response_snapshot.ml | 4 +- shared/test/logseq/app_test.ml | 21 +------ shared/test/logseq/mobile_session_test.ml | 49 +++++++---------- 12 files changed, 64 insertions(+), 132 deletions(-) diff --git a/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidFeedbackRecordingTest.kt b/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidFeedbackRecordingTest.kt index 94cd095dd..272162b1b 100644 --- a/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidFeedbackRecordingTest.kt +++ b/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidFeedbackRecordingTest.kt @@ -296,7 +296,9 @@ class AndroidFeedbackRecordingTest(private val scenario: String) { } "recent-navigation" -> { mount(1, dark = true) - apply(request("loadSidebar")) + val sidebar = request("loadSidebar") + val before = JSONObject(sidebar).getJSONObject("result").getJSONArray("recentPages") + apply(sidebar) ui.onNodeWithTag("button.search").performClick() ui.onNodeWithTag("field.search").performTextInput("Formula") val hits = JSONObject(request("searchNodes", "Formula")).getJSONObject("result").getJSONArray("searchResults") @@ -311,7 +313,8 @@ class AndroidFeedbackRecordingTest(private val scenario: String) { pause() if (verify) { val result = JSONObject(request("loadSidebar")).getJSONObject("result") - assertEquals(target, result.getJSONArray("recentPages").getJSONObject(0).getString("uuid")) + assertTrue((0 until before.length()).any { before.getJSONObject(it).getString("uuid") == target }) + assertEquals(before.toString(), result.getJSONArray("recentPages").toString()) ui.onNodeWithTag("link.sidebar.page.$target").assertIsDisplayed() } } diff --git a/apple/Sources/Logseq/LGRuntime.swift b/apple/Sources/Logseq/LGRuntime.swift index 8e47c8306..d660f6e22 100644 --- a/apple/Sources/Logseq/LGRuntime.swift +++ b/apple/Sources/Logseq/LGRuntime.swift @@ -44,18 +44,12 @@ private struct LGCoreResponseEnvelope: Decodable, Sendable { let isSearchPatch: Bool? let isReferencePatch: Bool? let isQueryPatch: Bool? - let isRecentPagesPatch: Bool? let graphName: String? let outlinerCommandRevision: Int? let outlinerCommands: [LogseqOutlinerCommand]? let hasPendingSemanticOperations: Bool? let pendingSyncRequest: PendingSyncRequest? let pendingSyncError: String? - - var isContentPatch: Bool { - isOutlinerPatch == true || isOutlinerContentPatch == true || isSearchPatch == true - || isReferencePatch == true || isQueryPatch == true || isRecentPagesPatch == true - } } struct PendingSyncRequest: Decodable, Sendable {} @@ -240,7 +234,7 @@ public final class LGRuntime { if result.isPendingSyncPatch == true { return syncProjection(result) != lastCoreSyncProjection } - if result.isContentPatch { + if result.isOutlinerPatch == true || result.isOutlinerContentPatch == true || result.isSearchPatch == true || result.isReferencePatch == true || result.isQueryPatch == true { return true } return response != lastAuthoritativeCoreResponse @@ -258,7 +252,7 @@ public final class LGRuntime { if result.isPendingSyncPatch == true { lastCoreSyncProjection = syncProjection(result) authoritativeCoreResponseInvalidated = true - } else if result.isContentPatch { + } else if result.isOutlinerPatch == true || result.isOutlinerContentPatch == true || result.isSearchPatch == true || result.isReferencePatch == true || result.isQueryPatch == true { if result.isOutlinerPatch == true { lastCoreSyncProjection = syncProjection(result) } diff --git a/shared/src/logseq/core/core_effect.ml b/shared/src/logseq/core/core_effect.ml index 184865e87..d55cb3e3a 100644 --- a/shared/src/logseq/core/core_effect.ml +++ b/shared/src/logseq/core/core_effect.ml @@ -62,7 +62,6 @@ let request ~now ~fresh_id payload = json "openNode" ["uuid", `String uuid; "reveal", `Bool (kind = "open-search-result")] | "close-node" -> empty "closeNode" | "select-sidebar-page" -> raw "selectPage" - | "record-sidebar-page-visit" -> raw "recordSidebarPageVisit" | "clear-selected-page" -> empty "clearSelectedPage" | "load-older-journals" -> empty "loadOlderJournals" | "load-flashcards" -> Ok ("loadFlashcards", Some (string_of_int (now ()))) diff --git a/shared/src/logseq/core/rpc_session.ml b/shared/src/logseq/core/rpc_session.ml index 8e17b21e7..02e5b0286 100644 --- a/shared/src/logseq/core/rpc_session.ml +++ b/shared/src/logseq/core/rpc_session.ml @@ -1512,32 +1512,12 @@ let select_page session payload = clear_node_navigation session; let destination, zoom = So.sidebar_node_destination session page in set_sidebar_page session page ~zoom; - So.record_page_visit session destination.uuid; + So.record_page_visit ~sidebar:pages session destination.uuid; snapshot_visible session | None -> Rpc.failure "unknown_page" "The selected page is not available") | _ -> Rpc.failure "invalid_params" "selectPage requires a page id" -let record_sidebar_page_visit session fields = - match Rpc.required_string fields "graphId", Rpc.required_string fields "uuid" with - | Ok graph_id, Ok uuid -> - let graph, recent = - match (state session).selected_sidebar_page with - | Some (page : Model.entity_summary) when page.uuid = uuid && So.recent_graph_id session = Some graph_id -> - let destination, _ = So.sidebar_node_destination session page in - So.record_page_visit session destination.uuid; - let recent = match So.load_sidebar_pages session with - | Some sidebar -> sidebar.Graph_read.recent_pages - | None -> [] in - `String graph_id, recent - | _ -> `Null, [] in - Rpc.success (Rpc.json_object [ - "isRecentPagesPatch", `Bool true; - "recentPagesGraphId", graph; - "recentPages", Rpc.json_list (List.map (summary_json session) recent); - ]) - | Error message, _ | _, Error message -> Rpc.failure "invalid_params" message - let after_finishing_outliner_edit session navigate = match Outliner.editing_uuid (state session).outliner_state with | None -> navigate () @@ -2690,9 +2670,6 @@ let rec dispatch session action payload = with_object "setJournalTitleFormat" payload "A date format is required" (fun _ fields -> set_journal_title_format session fields) | "selectPage" -> select_page session payload - | "recordSidebarPageVisit" -> - with_object action payload "A graph and page ID are required" - (fun _ fields -> record_sidebar_page_visit session fields) | "hydrateOutlinerRows" -> hydrate_outliner_rows session payload | "queryBlock" -> (match payload, query_db session with diff --git a/shared/src/logseq/core/session_outliner.ml b/shared/src/logseq/core/session_outliner.ml index 5fe6f6ffd..442b2e8de 100644 --- a/shared/src/logseq/core/session_outliner.ml +++ b/shared/src/logseq/core/session_outliner.ml @@ -21,33 +21,8 @@ let recent_page_visits (session : Types.session) graph_id = Hashtbl.replace session.recent_page_visits graph_id visits; visits -let favorite_member (sidebar : Graph_read.sidebar_pages) uuid = - List.exists (fun (page : Model.entity_summary) -> page.uuid = uuid) sidebar.favorites - -let record_page_visit (session : Types.session) uuid = - Option.iter (fun graph_id -> - let previous = recent_page_visits session graph_id in - match previous with - | first :: _ when first = uuid -> () - | _ -> - let is_favorite = - let db = if (Types.state session).sidebar_deferred then - Option.bind session.host.graph_db (fun load -> load ()) else None in - match db with - | Some db -> Graph_read.page_is_favorite db - | None -> - let sidebar = Option.bind session.host.graph_sidebar_pages (fun load -> load ()) in - fun uuid -> Option.exists (fun sidebar -> favorite_member sidebar uuid) sidebar in - if not (is_favorite uuid) then begin - let previous = List.filter (fun page -> page <> uuid && not (is_favorite page)) previous in - let visits = List.take Graph_read.recent_page_limit (uuid :: previous) in - Hashtbl.replace session.recent_page_visits graph_id visits; - Option.iter (fun save -> - try save graph_id visits with - | Failure message | Sqlite3.Error message -> Types.debug ("Could not save recent pages: " ^ message)) - session.host.save_recent_pages - end) - (recent_graph_id session) +let page_member pages uuid = + List.exists (fun (page : Model.entity_summary) -> page.uuid = uuid) pages let merge_recent_pages (session : Types.session) (sidebar : Graph_read.sidebar_pages) visits resolve = match !(session.recent_pages_cache) with @@ -59,7 +34,7 @@ let merge_recent_pages (session : Types.session) (sidebar : Graph_read.sidebar_p else (Hashtbl.add seen page.uuid (); true) in let opened = List.filter_map (fun uuid -> match resolve uuid with | Some ((page : Model.entity_summary), false) when - not (favorite_member sidebar page.uuid) && newly_seen page -> Some page + not (page_member sidebar.favorites page.uuid) && newly_seen page -> Some page | _ -> None) visits in let recent_pages = List.take Graph_read.recent_page_limit (opened @ List.filter newly_seen sidebar.recent_pages) in @@ -83,6 +58,30 @@ let sidebar_pages (session : Types.session) = if (Types.state session).sidebar_deferred then Types.empty_sidebar else Option.value (load_sidebar_pages session) ~default:Types.empty_sidebar +let record_page_visit ?sidebar (session : Types.session) uuid = + Option.iter (fun graph_id -> + let previous = recent_page_visits session graph_id in + if not (List.mem uuid previous) then begin + let pages = match sidebar with Some pages -> pages | None -> sidebar_pages session in + let is_favorite = + if Option.is_none sidebar && (Types.state session).sidebar_deferred then + match Option.bind session.host.graph_db (fun load -> load ()) with + | Some db -> Graph_read.page_is_favorite db + | None -> + let loaded = Option.bind session.host.graph_sidebar_pages (fun load -> load ()) in + fun uuid -> Option.exists (fun (pages : Graph_read.sidebar_pages) -> page_member pages.favorites uuid) loaded + else page_member pages.favorites in + if not (page_member pages.recent_pages uuid || is_favorite uuid) then begin + let visits = List.take Graph_read.recent_page_limit (uuid :: List.filter (fun page -> not (is_favorite page)) previous) in + Hashtbl.replace session.recent_page_visits graph_id visits; + Option.iter (fun save -> + try save graph_id visits with + | Failure message | Sqlite3.Error message -> Types.debug ("Could not save recent pages: " ^ message)) + session.host.save_recent_pages + end + end) + (recent_graph_id session) + let summary_candidate (page : Model.entity_summary) = { Outliner.label = page.title; value = page.uuid } diff --git a/shared/src/logseq/core/session_outliner.mli b/shared/src/logseq/core/session_outliner.mli index 8ce41fb66..8c81d055a 100644 --- a/shared/src/logseq/core/session_outliner.mli +++ b/shared/src/logseq/core/session_outliner.mli @@ -2,8 +2,7 @@ val load_sidebar_pages : Session_types.session -> Graph_read.sidebar_pages option val sidebar_pages : Session_types.session -> Graph_read.sidebar_pages -val recent_graph_id : Session_types.session -> string option -val record_page_visit : Session_types.session -> string -> unit +val record_page_visit : ?sidebar:Graph_read.sidebar_pages -> Session_types.session -> string -> unit val uses_paged_tag_objects : Session_types.session -> bool val outliner_context_with_blocks : diff --git a/shared/src/logseq/model.ml b/shared/src/logseq/model.ml index d923b3b6a..e01eaa531 100644 --- a/shared/src/logseq/model.ml +++ b/shared/src/logseq/model.ml @@ -297,7 +297,6 @@ type core_projection = ; is_pending_sync_patch : bool ; is_pending_sync_projection : bool ; is_graph_catalog_patch : bool - ; is_recent_pages_patch : bool ; is_graph_snapshot_recovery : bool ; projection_search_query : string ; search_offset : int @@ -395,7 +394,6 @@ type logseq_effect = | CloseSearchNodeEffect of int * string | AddRootBlockEffect of int * string | SelectSidebarPageEffect of int * string - | RecordSidebarPageVisitEffect of int * string * string | ClearSelectedPageEffect of int | LoadOlderJournalsEffect of int | FlashcardDeckEffect of int * string @@ -1084,7 +1082,6 @@ let effect_id eff = | CloseSearchNodeEffect (id, _) -> id | AddRootBlockEffect (id, _) -> id | SelectSidebarPageEffect (id, _) -> id - | RecordSidebarPageVisitEffect (id, _, _) -> id | ClearSelectedPageEffect id -> id | LoadOlderJournalsEffect id -> id | LoadFlashcardsEffect id | FlashcardDeckEffect (id, _) -> id @@ -2642,7 +2639,6 @@ let rec update (current : logseq_model) action = (* Uploads need the existing subscription to receive acknowledgements. *) let updated = if not projection.is_pending_sync_patch && not projection.is_pending_sync_projection - && not projection.is_recent_pages_patch && (applied.has_pending_semantic_operations || applied.has_pending_sync_request) && not (List.exists (function SyncNowEffect _ | SyncPendingEffect _ -> true | _ -> false) (applied.pending_effects @ applied.in_flight_effects)) @@ -3272,10 +3268,8 @@ let rec update (current : logseq_model) action = } uuid in - if not reusable then enqueue_effect updated (SelectSidebarPageEffect (updated.next_effect_id, uuid)) - else (match updated.selected_graph_id with - | Some graph_id -> enqueue_effect updated (RecordSidebarPageVisitEffect (updated.next_effect_id, graph_id, uuid)) - | None -> updated) + if reusable then updated + else enqueue_effect updated (SelectSidebarPageEffect (updated.next_effect_id, uuid)) | OpenQuickAction kind -> if not (List.mem kind ["capture"; "audio"; "camera"; "journal"; "task"]) then current @@ -3868,10 +3862,7 @@ and apply_core_snapshot (current : logseq_model) Journal_task_dates.apply_delta (if same_graph then current.journal_tasks else `Null) tasks | _ when same_graph -> current.journal_tasks | _ -> `Null in - if projection.is_recent_pages_patch then - if same_graph && Option.is_some graph_id then {current with recent_pages = projection.sidebar.recent_pages} - else current - else if Option.is_some projection.reference_candidates_update then + if Option.is_some projection.reference_candidates_update then match projection.reference_candidates_update with | Some (query, candidates) when projection.selected_graph_id = current.selected_graph_id && current.composer_reference_query = Some query -> diff --git a/shared/src/logseq/model.mli b/shared/src/logseq/model.mli index 5e72c8e9c..7214fa08c 100644 --- a/shared/src/logseq/model.mli +++ b/shared/src/logseq/model.mli @@ -282,7 +282,6 @@ type core_projection = ; is_pending_sync_patch : bool ; is_pending_sync_projection : bool ; is_graph_catalog_patch : bool - ; is_recent_pages_patch : bool ; is_graph_snapshot_recovery : bool ; projection_search_query : string ; search_offset : int @@ -380,7 +379,6 @@ type logseq_effect = | CloseSearchNodeEffect of int * string | AddRootBlockEffect of int * string | SelectSidebarPageEffect of int * string - | RecordSidebarPageVisitEffect of int * string * string | ClearSelectedPageEffect of int | LoadOlderJournalsEffect of int | FlashcardDeckEffect of int * string diff --git a/shared/src/logseq/native_bridge.ml b/shared/src/logseq/native_bridge.ml index 738018c2b..6e1ba9911 100644 --- a/shared/src/logseq/native_bridge.ml +++ b/shared/src/logseq/native_bridge.ml @@ -532,10 +532,6 @@ let encode_effect ?(model : Model.logseq_model option) (eff : Model.logseq_effec "{\"id\":" ^ string_of_int id ^ ",\"kind\":\"select-sidebar-page\",\"text\":" ^ Lui_wire.quoted uuid ^ "}" - | RecordSidebarPageVisitEffect (id, graph_id, uuid) -> - let payload = Yojson.Basic.to_string (`Assoc ["graphId", `String graph_id; "uuid", `String uuid]) in - "{\"id\":" ^ string_of_int id - ^ ",\"kind\":\"record-sidebar-page-visit\",\"text\":" ^ Lui_wire.quoted payload ^ "}" | ClearSelectedPageEffect id -> "{\"id\":" ^ string_of_int id ^ ",\"kind\":\"clear-selected-page\",\"text\":\"\"}" diff --git a/shared/src/logseq/response_snapshot.ml b/shared/src/logseq/response_snapshot.ml index 0d94a4117..02ad2e86c 100644 --- a/shared/src/logseq/response_snapshot.ml +++ b/shared/src/logseq/response_snapshot.ml @@ -491,8 +491,7 @@ let core_projection fields = (string_member "query" fields) | _ -> None); graph_name = string_member "graphName" fields; - selected_graph_id = string_member - (if bool_member "isRecentPagesPatch" fields then "recentPagesGraphId" else "selectedGraphId") fields; + selected_graph_id = string_member "selectedGraphId" fields; journal_title_format = string_member "journalTitleFormat" fields; graphs = List.filter_map graph (list_member "graphs" fields); is_graph_encrypted = bool_member "isGraphEncrypted" fields; @@ -583,7 +582,6 @@ let core_projection fields = is_pending_sync_patch = bool_member "isPendingSyncPatch" fields; is_pending_sync_projection = bool_member "isPendingSyncProjection" fields; is_graph_catalog_patch = bool_member "isGraphCatalogPatch" fields; - is_recent_pages_patch = bool_member "isRecentPagesPatch" fields; is_graph_snapshot_recovery = bool_member "isGraphSnapshotRecovery" fields } let error_message fields = diff --git a/shared/test/logseq/app_test.ml b/shared/test/logseq/app_test.ml index e96f38dc6..34582ed77 100644 --- a/shared/test/logseq/app_test.ml +++ b/shared/test/logseq/app_test.ml @@ -364,7 +364,6 @@ let empty_core_projection () = is_pending_sync_projection = false; is_graph_snapshot_recovery = false; is_graph_catalog_patch = false; - is_recent_pages_patch = false; projection_search_query = ""; search_offset = 0; search_has_more = false; @@ -9613,8 +9612,8 @@ let reselecting_the_current_page_preserves_loaded_rows () = List.iter (fun is_tag -> let application = App.create (ios_backend ()) in let page = { Model.uuid = "page-a"; title = "Project"; page_journal_day = None} in + let other = {page with Model.uuid = "page-b"; title = "Other project"} in let rows = thousand_nested_rows () in - let other = { page with Model.uuid = "page-b"; title = "Searched page" } in let sidebar = { (empty_sidebar_projection ()) with Model.recent_pages = [ other; page ]; selected_page = Some page; selected_page_is_tag = is_tag; @@ -9637,22 +9636,8 @@ let reselecting_the_current_page_preserves_loaded_rows () = check ~msg:"reselecting the already loaded root does not request another full snapshot" (not (List.exists (function Model.SelectSidebarPageEffect _ -> true | _ -> false) (App.model application).pending_effects)); - check ~msg:"reselecting the already loaded root records a graph-scoped visit" - (List.exists (function Model.RecordSidebarPageVisitEffect (_, "test-graph", "page-a") -> true | _ -> false) - (App.model application).pending_effects); - let patch graph = Response_snapshot.decode_json_response (`Assoc ["ok", `Bool true; "result", `Assoc [ - "isRecentPagesPatch", `Bool true; "recentPagesGraphId", `String graph; - "recentPages", `List [`Assoc ["uuid", `String page.uuid; "title", `String page.title]; - `Assoc ["uuid", `String other.uuid; "title", `String other.title]]]]) in - let apply_patch graph = match patch graph with - | Ok projection -> send application (Model.ApplyCoreSnapshot projection); flush application - | Error message -> fail message in - apply_patch "another-graph"; - check_eq (App.model application).recent_pages [other; page]; - apply_patch "test-graph"; - check_eq (App.model application).recent_pages [page; other]; - check_eq ~msg:"a Recent patch keeps the open outline mounted" - (descendant_with_identifier renderer (main_root renderer application) "outliner.block.large-0") first; + check_eq ~msg:"reselecting a loaded page keeps its position in Recent" + (App.model application).recent_pages [other; page]; check_eq ~msg:"a loaded page never returns to a loading placeholder" (descendant_with_identifier renderer (main_root renderer application) "status.page-loading") (-1) diff --git a/shared/test/logseq/mobile_session_test.ml b/shared/test/logseq/mobile_session_test.ml index fcf449553..b9d66f20a 100644 --- a/shared/test/logseq/mobile_session_test.ml +++ b/shared/test/logseq/mobile_session_test.ml @@ -476,7 +476,7 @@ let recent_pages_follow_navigation_and_survive_offline_restart () = cache id; let db = match Graph_store.restore_db (path id) with | Ok db -> db | Error message -> fail message in - let pages = List.init (cap + 1) (fun index -> + let pages = List.init (2 * cap) (fun index -> let eid = Ds.Entity_id (10 + index) in [ Ds.Add (eid, "block/uuid", Ds.Uuid (page index)); Ds.Add (eid, "block/name", Ds.String (page index)); @@ -494,14 +494,19 @@ let recent_pages_follow_navigation_and_survive_offline_restart () = prepare "graph-b"; let initial = recent (select_graph "graph-a") in check_eq (List.length initial) cap; - check (not (List.mem (page 0) initial)); + check (not (List.mem (page 0) initial || List.mem (page 1) initial)); + check_eq ~msg:"opening a page already listed in the edited-page fallback keeps its position" + (open_page "select-sidebar-page" (List.hd (List.rev initial))) initial; let from_link = open_page "open-node" (page 0) in - check_eq ~msg:"journal links promote pages outside the original Recent list" - (List.hd from_link) (page 0); + check_eq ~msg:"journal links add pages absent from Recent" + from_link (page 0 :: List.take (cap - 1) initial); let from_search = open_page "open-search-result" (page 1) in - let expected = List.take cap (page 1 :: page 0 :: List.filter ((<>) (page 1)) initial) in - Alcotest.(check (list string)) "search results promote pages without duplicates" expected from_search; - check_eq (List.length from_search) cap; + check_eq ~msg:"search adds new pages at the top" + from_search (page 1 :: List.take (cap - 1) from_link); + check_eq ~msg:"searching for a listed page retains its position" + (open_page "open-search-result" (page 0)) from_search; + check_eq ~msg:"following a link to a listed page retains its position" + (open_page "open-node" (page 0)) from_search; let full_history = List.init cap (fun i -> page (cap - 1 - i)) in List.iter (fun uuid -> ignore (open_page "open-node" uuid)) (List.rev full_history); check_eq ~msg:"opening a favorite from the sidebar keeps all visited pages" @@ -513,31 +518,19 @@ let recent_pages_follow_navigation_and_survive_offline_restart () = restart (); check_eq ~msg:"a favorite leaves the visit order intact after restart" (recent (select_graph "graph-a")) full_history; - let from_sidebar = open_page "select-sidebar-page" (page 0) in - check_eq ~msg:"a page added to Recent can be reopened from the sidebar" - (List.take 2 from_sidebar) [page 0; page (cap - 1)]; - ignore (open_page "open-search-result" (page cap)); - let session () = !(host.Mobile_session.session) in - ignore (Rpc_test.response_result (Rpc_test.dispatch_json (session ()) "closeNode" "")); - let state = (Session_types.state (session ())).outliner_state in - let record graph_id = call "executeEffect" ["kind", `String "record-sidebar-page-visit"; - "text", `String (Yojson.Basic.to_string (`Assoc ["graphId", `String graph_id; "uuid", `String (page 0)]))] in - let stale = record "graph-b" in - check_eq ~msg:"a visit for a different graph does not publish a recent list" - (U.member "recentPagesGraphId" stale) `Null; - let reselected = record "graph-a" in - check_eq ~msg:"a repeat tap returns only a graph-scoped Recent patch" - (U.member "isRecentPagesPatch" reselected, U.member "recentPagesGraphId" reselected, - U.member "selectedGraphId" reselected, U.member "outlinerRows" reselected) - (`Bool true, `String "graph-a", `Null, `Null); - check ~msg:"reselecting keeps the core outliner state" ((Session_types.state (session ())).outliner_state == state); - check_eq ~msg:"reselecting the open page promotes it after search" - (List.take 2 (recent reselected)) [page 0; page cap]; + check_eq ~msg:"reopening a page from the sidebar after restart keeps its position" + (open_page "select-sidebar-page" (page 0)) full_history; + let after_new_page = open_page "open-search-result" (page cap) in + check_eq ~msg:"adding another page evicts only the oldest entry" + after_new_page (page cap :: List.take (cap - 1) full_history); + ignore (Rpc_test.response_result (Rpc_test.dispatch_json !(host.Mobile_session.session) "closeNode" "")); + check_eq ~msg:"opening a listed page after closing search keeps the new order" + (open_page "select-sidebar-page" (page 1)) after_new_page; check_eq ~msg:"visits are isolated between graphs that share page UUIDs" (recent (select_graph "graph-b")) initial; restart (); check_eq ~msg:"the local catalog retains Recent across a restart without credentials" - (recent (select_graph "graph-a")) (recent reselected)) + (recent (select_graph "graph-a")) after_new_page) let collapsed_nodes_survive_navigation_restart_and_graph_switches () = with_host (fun host dir ->