From bafb6a23482d9bcd6c9207e5686a7c55c90b9098 Mon Sep 17 00:00:00 2001 From: Tienson Qin Date: Sat, 5 Dec 2026 14:43:21 +0800 Subject: [PATCH 1/2] Fix page hierarchy search and deletion on mobile --- apple/Sources/LogseqModel/Models.swift | 8 +- apple/Tests/UI/search-result-navigation.swift | 45 ++++++- shared/src/logseq/core/graph_read.ml | 69 ++++++++-- shared/src/logseq/core/graph_read.mli | 12 ++ shared/src/logseq/core/graph_sqlite.ml | 4 +- shared/src/logseq/core/node_presentation.ml | 32 +++++ shared/src/logseq/core/node_property.ml | 1 + shared/src/logseq/core/pending_projection.ml | 29 ++++- shared/src/logseq/core/ref_text.ml | 52 +++++--- shared/src/logseq/core/ref_text.mli | 1 + shared/src/logseq/core/rpc_encode.ml | 1 + shared/src/logseq/core/rpc_session.ml | 1 + shared/src/logseq/core/search_index.ml | 122 ++++++++++++------ shared/src/logseq/core/search_index.mli | 1 + shared/src/logseq/model.ml | 60 +++++---- shared/src/logseq/model.mli | 6 +- shared/src/logseq/response_snapshot.ml | 1 + shared/src/logseq/view_screens.ml | 10 +- shared/src/logseq/view_settings.ml | 24 +++- shared/test/logseq/app_test.ml | 32 +++-- shared/test/logseq/background_search_test.ml | 32 +++++ shared/test/logseq/composer_tag_test.ml | 106 +++++++++++++++ shared/test/logseq/drive_host.ml | 4 +- shared/test/logseq/mobile_feedback_test.ml | 8 +- shared/test/logseq/rpc_test.ml | 9 +- shared/test/logseq/search_index_test.ml | 83 ++++++++++++ 26 files changed, 627 insertions(+), 126 deletions(-) diff --git a/apple/Sources/LogseqModel/Models.swift b/apple/Sources/LogseqModel/Models.swift index 8ccb4f2b3..2a18d87b3 100644 --- a/apple/Sources/LogseqModel/Models.swift +++ b/apple/Sources/LogseqModel/Models.swift @@ -335,6 +335,7 @@ public struct LogseqSearchHit: Codable, Hashable, Identifiable, Sendable { public let isPage: Bool public let page: LogseqSidebarPage? public let breadcrumbs: [LogseqEntitySummary] + public let tags: [LogseqEntitySummary] public var id: String { uuid } @@ -343,17 +344,19 @@ public struct LogseqSearchHit: Codable, Hashable, Identifiable, Sendable { title: String, isPage: Bool, page: LogseqSidebarPage? = nil, - breadcrumbs: [LogseqEntitySummary] = [] + breadcrumbs: [LogseqEntitySummary] = [], + tags: [LogseqEntitySummary] = [] ) { self.uuid = uuid self.title = title self.isPage = isPage self.page = page self.breadcrumbs = breadcrumbs + self.tags = tags } private enum CodingKeys: String, CodingKey { - case uuid, title, isPage, page, breadcrumbs + case uuid, title, isPage, page, breadcrumbs, tags } public init(from decoder: Decoder) throws { @@ -363,6 +366,7 @@ public struct LogseqSearchHit: Codable, Hashable, Identifiable, Sendable { isPage = try values.decodeIfPresent(Bool.self, forKey: .isPage) ?? false page = try values.decodeIfPresent(LogseqSidebarPage.self, forKey: .page) breadcrumbs = try values.decodeIfPresent([LogseqEntitySummary].self, forKey: .breadcrumbs) ?? [] + tags = try values.decodeIfPresent([LogseqEntitySummary].self, forKey: .tags) ?? [] } } diff --git a/apple/Tests/UI/search-result-navigation.swift b/apple/Tests/UI/search-result-navigation.swift index c34e19d9b..96434d75b 100644 --- a/apple/Tests/UI/search-result-navigation.swift +++ b/apple/Tests/UI/search-result-navigation.swift @@ -74,8 +74,14 @@ import UIKit var routes: [String] = [] var query = "" let hits: [[String: Any]] = (0..<80).map { index in - ["uuid": "result-\(index)", "title": "Search result \(index)", - "isPage": index < 40] + var hit: [String: Any] = ["uuid": "result-\(index)", "title": "Search result \(index)", + "isPage": index < 40] + if index == 0 { + hit["title"] = "Child Page" + hit["breadcrumbs"] = [["uuid": "parent", "title": "Parent Page"]] + hit["tags"] = [["uuid": "projects", "title": "Projects"]] + } + return hit } func snapshot() -> String { let nodes: [[String: Any]] = routes.map { uuid in @@ -91,6 +97,9 @@ import UIKit "outlinerRows": rows, ] if revealsBlock { node["scrollTarget"] = uuid } + if uuid == "result-0" { + node["nodeProperties"] = ["ownerUuid": uuid, "canDelete": true, "hasChildPages": true] + } return node } let result: [String: Any] = [ @@ -173,6 +182,16 @@ import UIKit try await wait("Search must return page and block results") { query == "Search" && find("search.result.result-0") != nil && find("search.result.result-40") != nil } + func text(_ identifier: String) -> String? { + find(identifier).flatMap { backend.model(id: $0)?.property(.text)?.stringValue } + } + guard text("search.result.title.result-0") == "Child Page", + text("search.result.context.result-0") == "Parent Page", + text("search.result.tags.result-0") == "#Projects", + find("search.result.context.result-1") == nil, + find("search.result.tags.result-1") == nil else { + throw failure("Search rows must display the leaf title, parent page and tags when present") + } try await Task.sleep(for: .milliseconds(200)) let root = window.rootViewController! func searchNavigation() -> UINavigationController? { @@ -256,6 +275,28 @@ import UIKit try await Task.sleep(for: .milliseconds(500)) try sampler.verify("reopening") } + let reopenedField = views(window).compactMap { $0 as? UISearchTextField }.first { $0.isFirstResponder }! + reopenedField.insertText("Parent Child") + try await wait("The child result appears for a namespace query") { + query == "Parent Child" && find("search.result.result-0") != nil + } + try backend.performPress(node: find("search.result.result-0")!) + try await wait("The parent result opens with its page actions") { + navigation.viewControllers.count == 2 && navigation.transitionCoordinator == nil + && find("button.page.delete") != nil + } + try backend.performPress(node: find("button.page.delete")!) + try await wait("Deleting a parent presents a warning without a destructive action") { + find("dialog.page-delete.warning") != nil && find("button.page-delete.confirm") == nil + && (root.presentedViewController != nil || navigation.presentedViewController != nil) + } + try await Task.sleep(for: .milliseconds(250)) + try screenshot("page-deletion-warning.png") + try backend.performPress(node: find("button.page-delete.warning.dismiss")!) + try await wait("Dismissing the warning leaves the parent page open") { + find("dialog.page-delete.warning") == nil && navigation.viewControllers.count == 2 + && routes == ["result-0"] + } guard runtime.lastError == nil else { throw failure(runtime.lastError!) } print("PASS: search keeps a stable topbar through opening, page/block results, Back, Cancel, core dismissal, and reopening") } diff --git a/shared/src/logseq/core/graph_read.ml b/shared/src/logseq/core/graph_read.ml index ed600023c..87cbcb7dd 100644 --- a/shared/src/logseq/core/graph_read.ml +++ b/shared/src/logseq/core/graph_read.ml @@ -194,18 +194,21 @@ let tag_is_visible_in_node db eid = && value db eid "logseq.property.class/hide-from-node" <> Some (Ds.Bool true) -let visible_tag_summaries decrypt_title db eid = +let tag_summaries decrypt_title db eid visible = List.of_seq (Ds.Db.datoms db Ds.Eavt ~e:eid ~a:"block/tags" ()) |> List.filter_map (fun (datom : Ds.datom) -> match Ds_value.ref_eid db "block/tags" datom.v with | Some tag_eid -> if - tag_is_visible_in_node db tag_eid + visible tag_eid && entity_is_instance_of db tag_eid "logseq.class/Tag" then entity_summary decrypt_title db tag_eid else None | None -> None) +let visible_tag_summaries decrypt_title db eid = + tag_summaries decrypt_title db eid (tag_is_visible_in_node db) + let rec breadcrumbs_loop decrypt_title db seen eid ancestors = if List.mem eid seen then ancestors else @@ -402,10 +405,22 @@ let page_is_hidden db eid = in loop [] eid +let namespace_children db eid = + Ds_value.datoms_by_ref db Ds.Aevt "block/parent" eid + |> Seq.filter_map (fun (datom : Ds.datom) -> + match string_value (value db datom.e "block/name") with + | Some _ when value db datom.e "logseq.property/deleted-at" = None -> Some datom.e + | _ -> None) + let library_entity db eid = value db eid "logseq.property/built-in?" = Some (Ds.Bool true) && string_value (value db eid "block/title") = Some "Library" +let namespace_parent db eid = + match ref_eids db eid "block/parent" with + | [parent] when not (library_entity db parent) -> Some parent + | _ -> None + let page_summary decrypt_title db eid = let uuid = uuid_for_eid db eid in let title = entity_title decrypt_title db eid in @@ -425,6 +440,17 @@ let page_summary decrypt_title db eid = else None | _ -> None +let namespace_breadcrumbs decrypt_title db eid = + let rec loop seen eid ancestors = + match namespace_parent db eid with + | Some parent when not (List.mem parent seen) && value db parent "block/name" <> None -> + (match page_summary decrypt_title db parent with + | Some page -> loop (parent :: seen) parent (page :: ancestors) + | None -> ancestors) + | _ -> ancestors + in + loop [eid] eid [] + let favorite_page_eid db = match List.of_seq @@ -672,6 +698,14 @@ let tag_available_for_completion db eid = ]) | _ -> true +let search_page_tags decrypt_title db eid = + if entity_is_instance_of db eid "logseq.class/Tag" then [] + else + tag_summaries decrypt_title db eid (fun tag -> + tag_available_for_completion db tag + && value db tag "logseq.property.class/hide-from-node" <> Some (Ds.Bool true) + && not (page_is_hidden db tag)) + let tag_last_used db eid = List.fold_left (fun latest (datom : Ds.datom) -> max latest datom.tx) @@ -711,26 +745,35 @@ let node_is_property db uuid = let unique_named_uuid require_tag db name = let key = String.lowercase_ascii (S.trim name) in + let index = if Ds.Schema.schema_attr_is_avet_accessible db.Ds.schema "block/name" + then Ds.Avet else Ds.Aevt in + let named name = Ds.Db.datoms db index ~a:"block/name" ~v:(Ds.String name) () in if key = "" then None else if not require_tag && String.contains key '/' then ( let rec resolve parent = function | [] -> Option.bind parent (uuid_for_eid db) - | name :: rest -> - let matches = Ds.Db.datoms db Ds.Avet ~a:"block/name" ~v:(Ds.String name) () + | part :: rest -> + let name = S.trim part in + let matches = named name |> Seq.filter (fun (d : Ds.datom) -> not (page_is_hidden db d.e) - && ref_eids db d.e "block/parent" = Option.to_list parent) + && namespace_parent db d.e = parent) |> List.of_seq in match matches with [d] -> resolve (Some d.Ds.e) rest | _ -> None in resolve None (String.split_on_char '/' key)) else ( let matches = - List.of_seq (Ds.Db.datoms db Ds.Aevt ~a:"block/name" ~v:(Ds.String key) ()) + List.of_seq (named key) |> List.map (fun (datom : Ds.datom) -> datom.e) |> List.filter (fun eid -> - (not require_tag) - || (entity_is_instance_of db eid "logseq.class/Tag" - && tag_available_for_completion db eid)) + not (page_is_hidden db eid) + && (not require_tag || (entity_is_instance_of db eid "logseq.class/Tag" + && tag_available_for_completion db eid))) in + (* Prefer an unqualified page when a namespace also has this leaf name. *) + let matches = if require_tag then matches else + match List.filter (fun eid -> namespace_parent db eid = None) matches with + | [] -> matches + | roots -> roots in match matches with | [ eid ] -> uuid_for_eid db eid | _ -> None) @@ -757,13 +800,17 @@ let normalize_title_text create_tag db uuid title = , entity_summaries (fun value -> Ok value) db eid "block/tags" ) | None -> ([], []) in + let visible = function + | Some uuid as found when Option.exists (fun eid -> not (page_is_hidden db eid)) + (Ds.entid db "block/uuid" (Ds.Uuid uuid)) -> found + | _ -> None in Ref_text.to_ids (fun name -> - match known_title (refs @ tags) name with + match visible (known_title (refs @ tags) name) with | Some uuid -> Some uuid | None -> unique_named_uuid false db name) (fun name -> - match known_title tags name with + match visible (known_title tags name) with | Some uuid -> Some uuid | None -> (match unique_named_uuid true db name with diff --git a/shared/src/logseq/core/graph_read.mli b/shared/src/logseq/core/graph_read.mli index 7b0630b9e..c7cfa0bd8 100644 --- a/shared/src/logseq/core/graph_read.mli +++ b/shared/src/logseq/core/graph_read.mli @@ -39,6 +39,11 @@ val visible_tag_summaries : Datascript.db -> int -> Cache_model.entity_summary list +val search_page_tags : + (string -> (string, string) result) -> + Datascript.db -> + int -> + Cache_model.entity_summary list val breadcrumbs : (string -> (string, string) result) -> Datascript.db -> @@ -56,11 +61,18 @@ val block : int -> Cache_model.block option val page_is_hidden : Datascript.db -> int -> bool +val namespace_children : Datascript.db -> int -> int Seq.t +val namespace_parent : Datascript.db -> int -> int option val page_summary : (string -> (string, string) result) -> Datascript.db -> int -> Cache_model.entity_summary option +val namespace_breadcrumbs : + (string -> (string, string) result) -> + Datascript.db -> + int -> + Cache_model.entity_summary list val favorite_page_eid : Datascript.db -> int option val recycle_page_eid : Datascript.db -> int option val last_order : Datascript.db -> string -> int -> string option diff --git a/shared/src/logseq/core/graph_sqlite.ml b/shared/src/logseq/core/graph_sqlite.ml index 98d9059a2..6b2a1eea1 100644 --- a/shared/src/logseq/core/graph_sqlite.ml +++ b/shared/src/logseq/core/graph_sqlite.ml @@ -419,7 +419,7 @@ let search_query path sql binds = (* Root and tail identify the persisted graph without reading index nodes. Pending intents identify the optimistic projection layered on that graph. - Bump the version when row eligibility changes, even if the schema does not. *) + Bump the version when row contents or eligibility change. *) let search_source_version path = with_app_db path (fun connection -> let roots = query connection @@ -432,7 +432,7 @@ let search_source_version path = (fun row -> (Db.column_text row 0, Db.column_int row 1, Db.column_text row 2, Db.column_text row 3)) in Some (Digest.to_hex (Digest.string - (Marshal.to_string ("search-index-v3", roots, pending) [])))) + (Marshal.to_string ("search-index-v4", roots, pending) [])))) let search_version path = with_search_db path (fun connection -> diff --git a/shared/src/logseq/core/node_presentation.ml b/shared/src/logseq/core/node_presentation.ml index 4fe1e4c39..7430a49d2 100644 --- a/shared/src/logseq/core/node_presentation.ml +++ b/shared/src/logseq/core/node_presentation.ml @@ -88,6 +88,27 @@ let preview ?(on_reference = fun _ -> ()) db = let decorate ?actor ?on_comment_reference db = let preview = preview ?on_reference:on_comment_reference db in + let recycled_refs = Hashtbl.create 16 in + let recycled uuid = + match Hashtbl.find_opt recycled_refs uuid with + | Some result -> result + | None -> + let result = Option.exists (Read.recycled db) + (Ds.entid db "block/uuid" (Ds.Uuid uuid)) in + Hashtbl.add recycled_refs uuid result; + result in + (* References saved before page deletion removed links still carry a UUID. *) + let rec unlink_recycled = function + | `Assoc fields -> + (match List.assoc_opt "type" fields, List.assoc_opt "uuid" fields, + List.assoc_opt "title" fields with + | Some (`String ("nodeReference" | "tagReference" as kind)), + Some (`String uuid), Some (`String title) when recycled uuid -> + let text = if kind = "tagReference" then "#" ^ title else title in + `Assoc ["type", `String "text"; "text", `String text] + | _ -> `Assoc (List.map (fun (key, value) -> key, unlink_recycled value) fields)) + | `List nodes -> `List (List.map unlink_recycled nodes) + | value -> value in let discussions = Hashtbl.create 16 in let discussion eid = match Hashtbl.find_opt discussions eid with | Some fields -> fields @@ -166,6 +187,17 @@ let decorate ?actor ?on_comment_reference db = let fields = if not decorated then fields else let nodes = if resolved = None then [M.Markup_text "Embedded node unavailable"] else markup body in ("markup", M.to_yojson nodes) :: List.remove_assoc "markup" fields in + let has_recycled_summary = function + | Some (`List summaries) -> List.exists (function + | `Assoc fields -> (match List.assoc_opt "uuid" fields with + | Some (`String uuid) -> recycled uuid | _ -> false) + | _ -> false) summaries + | _ -> false in + let fields = + if embedded || has_recycled_summary (List.assoc_opt "references" fields) + || has_recycled_summary (List.assoc_opt "tags" fields) then + List.map (function "markup", nodes -> "markup", unlink_recycled nodes | field -> field) fields + else fields in let fields = match resolved with | Some (source, path) when in_embed || embedded -> (match read_block source with diff --git a/shared/src/logseq/core/node_property.ml b/shared/src/logseq/core/node_property.ml index d9226c754..edc9b72f5 100644 --- a/shared/src/logseq/core/node_property.ml +++ b/shared/src/logseq/core/node_property.ml @@ -52,6 +52,7 @@ let render ?(defer_values = false) db ~owner ~encode_block = List.filter (fun (name, _) -> not (List.mem name ["title"; "filterValues"])) fields) | _ -> `Null in Ok (`Assoc ["ownerUuid", `String owner; "canDelete", `Bool (Node_title.can_delete db id); + "hasChildPages", `Bool (Node_title.is_page db id && not (Seq.is_empty (G.namespace_children db id))); "tagPicker", tag_picker; "canAdd", `Bool (Node_title.can_edit db id); "classSchema", `Bool class_; "availableProperties", `List catalog; "schemaProperties", `List (List.map property schema_attrs); "rename", rename; "properties", `List (List.map (fun attr -> diff --git a/shared/src/logseq/core/pending_projection.ml b/shared/src/logseq/core/pending_projection.ml index abf39e85f..dcc1995cd 100644 --- a/shared/src/logseq/core/pending_projection.ml +++ b/shared/src/logseq/core/pending_projection.ml @@ -348,6 +348,28 @@ let page_entity db eid = || (match Db.datoms db Ds.Eavt ~e:eid ~a:"block/journal-day" () with | seq -> Seq.uncons seq <> None) +let unlink_deleted_page db eid uuid = + let plain title = Ok title in + match Graph_read.entity_summary plain db eid with + | None -> [] + | Some page -> + let ancestors = Graph_read.namespace_breadcrumbs plain db eid in + let label = String.concat "/" (List.map (fun (part : Cache_model.entity_summary) -> + part.title) (ancestors @ [page])) in + Datascript_value.datoms_by_ref db Ds.Aevt "block/refs" eid + |> Seq.filter_map (fun (datom : Ds.datom) -> + let source = datom.e in + if source = eid || has_ref db source "block/page" eid + || List.mem (Graph_read.display_type_for_eid db source) [Some "code"; Some "math"] then None + else + Option.bind (Graph_read.string_value (Graph_read.value db source "block/title")) (fun title -> + let unlinked = Ref_text.unlink uuid label title in + if title = unlinked then None else + let source = Ds.Entity_id source in + Some [Ds.Add (source, "block/title", Ds.String unlinked); + Ds.Retract (source, "block/refs", Some datom.v)])) + |> List.of_seq |> List.concat + let would_create_cycle db moving_eid parent_eid = List.exists (fun eid -> eid = parent_eid) (subtree db [ moving_eid ]) @@ -872,7 +894,7 @@ let rec compile_with_literals literal_blocks updated_at db (intent : Ops.pending | title :: rest -> let existing = Ds.Db.datoms db Ds.Avet ~a:"block/name" ~v:(Ds.String (Node_title.name title)) () |> Seq.filter (fun (d : Ds.datom) -> not (Graph_read.page_is_hidden db d.e) - && Graph_read.ref_eids db d.e "block/parent" = Option.to_list parent) + && Graph_read.namespace_parent db d.e = parent) |> List.of_seq in match existing with | [d] -> create db (Some d.Ds.e) reversed rest @@ -1075,6 +1097,8 @@ let rec compile_with_literals literal_blocks updated_at db (intent : Ops.pending else if not (Node_title.can_delete ~now:value.deleted_at db page_eid) then Error "Protected page cannot be deleted" + else if not (Seq.is_empty (Graph_read.namespace_children db page_eid)) then + Error "This page has child pages. Move or delete them first." else let parent = match one_value db reference "block/parent" with @@ -1114,7 +1138,8 @@ let rec compile_with_literals literal_blocks updated_at db (intent : Ops.pending ] @ parent @ order); - ] @ (subtree db [page_eid] |> List.concat_map (fun target -> + ] @ unlink_deleted_page db page_eid value.page_uuid + @ (subtree db [page_eid] |> List.concat_map (fun target -> List.concat_map (fun (attr, (spec : Ds.schema_attr)) -> if spec.value_type <> Some Ds.RefType || not (String.starts_with ~prefix:"user.property/" attr diff --git a/shared/src/logseq/core/ref_text.ml b/shared/src/logseq/core/ref_text.ml index b2a3231fc..0b12fd0bf 100644 --- a/shared/src/logseq/core/ref_text.ml +++ b/shared/src/logseq/core/ref_text.ml @@ -93,10 +93,10 @@ let hashtag_boundaries source first last = && (first = 0 || source.[first - 1] = '(' || whitespace_at source (previous (first - 1))) && after last -let references title = - let add kind name start_pos end_pos acc = +let parse_references ?(include_alias = false) make title = + let add ?alias kind name start_pos end_pos acc = let name = String.trim (unbracket name) in - if name = "" then acc else { kind; name; start_pos; end_pos } :: acc + if name = "" then acc else make { kind; name; start_pos; end_pos } alias :: acc in let rec inlines source offset allow_tags acc = match Angstrom.parse_string ~consume:Angstrom.Consume.All @@ -123,17 +123,18 @@ let references title = let raw = String.sub source pos.start_pos (pos.end_pos - pos.start_pos) in let target = "[[" ^ name ^ "]]" in (* For aliases, replace the destination while preserving the label. *) - let target_start = - if String_kit.starts_with ~prefix:"[[" raw then Some 0 - else - match String_kit.last_index_of ~sub:"](" raw with - | Some opening -> String_kit.index_of ~sub:target ~start:(opening + 2) raw - | None -> None - in - (match target_start with - | Some start -> add Page name (start_pos + start) - (start_pos + start + String.length target) acc - | None -> acc) + if String_kit.starts_with ~prefix:"[[" raw then + add Page name start_pos (start_pos + String.length target) acc + else + (match String_kit.last_index_of ~sub:"](" raw with + | Some opening -> + (match String_kit.index_of ~sub:target ~start:(opening + 2) raw with + | Some _ when include_alias && String_kit.starts_with ~prefix:"[" raw -> + add ~alias:(String.sub raw 1 (opening - 1)) Page name start_pos end_pos acc + | Some start -> + add Page name (start_pos + start) (start_pos + start + String.length target) acc + | None -> acc) + | None -> acc) | Inline.Emphasis (style, _) -> (* Emphasis children have no positions. Reparse the inner source for page refs; mldoc treats hashtags inside emphasis as plain text. *) @@ -161,6 +162,8 @@ let references title = [] blocks |> List.rev +let references title = parse_references (fun reference _ -> reference) title + let page_names title = List.map (fun reference -> reference.name) (references title) let tag_names title = @@ -219,22 +222,29 @@ let completion_prefix title caret = (Mldoc.Parser.parse config title); if !blocked then "" else String.sub title !floor (caret - !floor) -let rewrite resolve title = +let rewrite ?(include_alias = false) resolve title = let result = Buffer.create (String.length title) in let offset = ref 0 in - List.iter (fun reference -> - match resolve reference with + List.iter (fun (reference, alias) -> + match resolve reference alias with | None -> () | Some replacement -> Buffer.add_substring result title !offset (reference.start_pos - !offset); Buffer.add_string result replacement; offset := reference.end_pos) - (references title); + (parse_references ~include_alias (fun reference alias -> reference, alias) title); Buffer.add_substring result title !offset (String.length title - !offset); Buffer.contents result +let unlink uuid label title = + rewrite ~include_alias:true (fun reference alias -> + if reference.name <> uuid then None + else match reference.kind with + | Page -> Some (Option.value ~default:label alias) + | Tag -> Some ("#" ^ label)) title + let to_text tag_title ref_title title = - rewrite (fun reference -> + rewrite (fun reference _ -> match reference.kind with | Page -> Option.map (fun label -> "[[" ^ label ^ "]]") (ref_title reference.name) | Tag -> @@ -245,14 +255,14 @@ let to_text tag_title ref_title title = (tag_title reference.name)) title let to_ids resolve_ref resolve_tag title = - rewrite (fun reference -> + rewrite (fun reference _ -> if is_uuid reference.name then None else match reference.kind with | Page -> Option.map (fun uuid -> "[[" ^ uuid ^ "]]") (resolve_ref reference.name) | Tag -> Option.map (fun uuid -> "#[[" ^ uuid ^ "]]") (resolve_tag reference.name)) title let remap_page_ids map title = - rewrite (fun reference -> + rewrite (fun reference _ -> match reference.kind with | Page when is_uuid reference.name -> Option.map (fun uuid -> "[[" ^ uuid ^ "]]") (map reference.name) diff --git a/shared/src/logseq/core/ref_text.mli b/shared/src/logseq/core/ref_text.mli index f9eb8eeed..073db5488 100644 --- a/shared/src/logseq/core/ref_text.mli +++ b/shared/src/logseq/core/ref_text.mli @@ -15,3 +15,4 @@ val to_text : val to_ids : (string -> string option) -> (string -> string option) -> string -> string val remap_page_ids : (string -> string option) -> string -> string +val unlink : string -> string -> string -> string diff --git a/shared/src/logseq/core/rpc_encode.ml b/shared/src/logseq/core/rpc_encode.ml index 066a4b9b8..66c4183a1 100644 --- a/shared/src/logseq/core/rpc_encode.ml +++ b/shared/src/logseq/core/rpc_encode.ml @@ -194,6 +194,7 @@ let search_hit_json ?(summary_json = summary_json) (hit : Search_index.indexed_s | Some page -> summary_json page | None -> `Null ) ; ("breadcrumbs", `List (List.map summary_json hit.breadcrumbs)) + ; ("tags", `List (List.map summary_json hit.tags)) ] let outliner_row_json youtube_target_url serialize_block diff --git a/shared/src/logseq/core/rpc_session.ml b/shared/src/logseq/core/rpc_session.ml index ddaef0213..0c4f456b5 100644 --- a/shared/src/logseq/core/rpc_session.ml +++ b/shared/src/logseq/core/rpc_session.ml @@ -3013,6 +3013,7 @@ let rec dispatch session action payload = (fun () -> if (state session).config <> None then restore_semantic_queue session; + refresh_retained_search session; snapshot_visible session) | "unlockGraph" -> (match (s.config, h.Types.unlock_graph, payload) with diff --git a/shared/src/logseq/core/search_index.ml b/shared/src/logseq/core/search_index.ml index e1bf15200..7dcfa3f2f 100644 --- a/shared/src/logseq/core/search_index.ml +++ b/shared/src/logseq/core/search_index.ml @@ -25,6 +25,7 @@ type indexed_search_hit = ; is_page : bool ; page : Cache_model.entity_summary option ; breadcrumbs : Cache_model.entity_summary list + ; tags : Cache_model.entity_summary list } (* Count UTF-8 code points for search thresholds and editor matching. *) @@ -465,31 +466,24 @@ let row_of_eid db eid = | Some uuid -> (match Graph.entity_title (fun value -> Ok value) db eid with | Some title -> - let hidden = private_search_node db eid || Graph.page_is_hidden db eid in + let is_page = Option.is_some (Graph.string_value (Graph.value db eid "block/name")) in + let page_eid = if is_page then None else + Datascript_value.optional_ref_eid db "block/page" (Graph.value db eid "block/page") in + let hidden = private_search_node db eid || Graph.page_is_hidden db eid + || Option.exists (Graph.page_is_hidden db) page_eid in if String.trim title <> "" && (not hidden) && utf8_length title <= 10000 then - let is_page = - Option.is_some - (Graph.string_value (Graph.value db eid "block/name")) - in - let page_uuid = - if is_page then uuid - else - match - Datascript_value.optional_ref_eid db "block/page" - (Graph.value db eid "block/page") - with - | Some page_eid -> - (match - Graph.uuid_value (Graph.value db page_eid "block/uuid") - with - | Some page_uuid -> page_uuid - | None -> uuid) - | None -> uuid - in + let page_uuid = Option.value ~default:uuid (Option.bind page_eid (Graph.uuid_for_eid db)) in let title = Ref_text.to_text title_for_uuid title_for_uuid title in + let title = + if not is_page then title + else + let parents = Graph.namespace_breadcrumbs (fun value -> Ok value) db eid in + String.concat "/" (List.map (fun (page : Cache_model.entity_summary) -> + page.title) parents @ [title]) + in let title = match Graph.int_value (Graph.value db eid "block/journal-day") with | Some day -> title ^ " " ^ string_of_int day @@ -525,6 +519,37 @@ let collect_uuid_changes ?(skip_unchanged = false) before after uuids = Seq.fold_left (fun uuids (datom : Ds.datom) -> match Graph.uuid_for_eid after datom.e with Some uuid -> uuid :: uuids | None -> uuids) uuids (Ds.Db.datoms after Ds.Aevt ~a:"block/journal-day" ()) in + let page_location db uuid = + Option.bind (Ds.entid db "block/uuid" (Ds.Uuid uuid)) (fun eid -> + Option.map (fun _ -> + (eid, Graph.value db eid "block/title", Graph.ref_eids db eid "block/parent", + Graph.page_is_hidden db eid)) + (Graph.value db eid "block/name")) in + let add_children db ~include_blocks uuid_list eid = + let visited = Hashtbl.create 8 in + let rec walk uuids eid = + if Hashtbl.mem visited eid then uuids else ( + Hashtbl.add visited eid (); + let children = if not include_blocks then Graph.namespace_children db eid else + let incoming attr = Datascript_value.datoms_by_ref db Ds.Aevt attr eid + |> Seq.map (fun (datom : Ds.datom) -> datom.e) in + if Graph.value db eid "block/name" = None then incoming "block/parent" + else Seq.append (incoming "block/parent") (incoming "block/page") in + Seq.fold_left (fun uuids child -> + if Hashtbl.mem visited child then uuids else + match Graph.uuid_for_eid db child with + | Some uuid -> walk (uuid :: uuids) child + | None -> walk uuids child) uuids children) in + walk uuid_list eid in + let uuids = List.fold_left (fun affected uuid -> + match page_location before uuid, page_location after uuid with + | old, current when old <> current -> + let visible = Option.exists (fun (_, _, _, hidden) -> not hidden) in + let include_blocks = visible old <> visible current in + let add db affected = function + | Some (eid, _, _, _) -> add_children db ~include_blocks affected eid | None -> affected in + add after (add before affected old) current + | _ -> affected) uuids uuids in let seen = Hashtbl.create 32 in let affected = List.concat_map @@ -593,6 +618,15 @@ let refresh index db = let query_rows index sql binds = try search_query index.path sql binds with Failure _ -> [] +let namespace_query_tail query = + match String.rindex_opt query '/' with + | Some slash when slash > 0 && not (String.starts_with ~prefix:"../" query + || String.starts_with ~prefix:"./" query || String_kit.includes ~sub:"://" query + || Dev_query.Date_time_util.valid_journal_title query) -> + let tail = String.trim (String.sub query (slash + 1) (String.length query - slash - 1)) in + if utf8_length tail < 3 then None else Some tail + | _ -> None + let full_text_rows ?(prioritize_pages = false) ?exclude_uuid ~offset ~limit index query = let query = String.trim query in let query = if String.starts_with ~prefix:"#" query && not (String.exists whitespace_char query) @@ -600,24 +634,29 @@ let full_text_rows ?(prioritize_pages = false) ?exclude_uuid ~offset ~limit inde if query = "" || limit <= 0 then [] else (* Trigram MATCH cannot find one or two characters. Search the same indexed content literally, keeping the result window bounded before hydration. *) - let predicate, input = + let predicate, search_binds = if utf8_length query < 3 then let escaped = List.fold_left (fun value symbol -> String_kit.replace value ~match_:symbol ~replacement:("\\" ^ symbol)) query ["\\"; "%"; "_"] in - "title LIKE ? ESCAPE '\\'", "%" ^ escaped ^ "%" - else "title MATCH ?", get_match_input query in + "title LIKE ? ESCAPE '\\'", [Sqlite3.Data.TEXT ("%" ^ escaped ^ "%")] + else + let input = Sqlite3.Data.TEXT (get_match_input query) in + match namespace_query_tail query with + | Some tail -> "(title MATCH ? OR title MATCH ?)", [input; Sqlite3.Data.TEXT (get_match_input tail)] + | None -> "title MATCH ?", [input] in let predicate, search_binds = match exclude_uuid with - | Some uuid -> predicate ^ " AND id <> ?", [Sqlite3.Data.TEXT input; Sqlite3.Data.TEXT uuid] - | None -> predicate, [Sqlite3.Data.TEXT input] in + | Some uuid -> predicate ^ " AND id <> ?", search_binds @ [Sqlite3.Data.TEXT uuid] + | None -> predicate, search_binds in let order, rank_binds = if prioritize_pages then (* Rank page titles before LIMIT/OFFSET. Preserve the existing FTS order within each group so later pages continue where earlier ones ended. *) " ORDER BY CASE WHEN id <> page THEN 3 \ - WHEN title = ? COLLATE NOCASE THEN 0 \ - WHEN instr(lower(title), lower(?)) = 1 THEN 1 ELSE 2 END, rowid", - [Sqlite3.Data.TEXT query; Sqlite3.Data.TEXT query] + WHEN title = ? COLLATE NOCASE OR substr(title, -length(?) - 1) = '/' || ? COLLATE NOCASE THEN 0 \ + WHEN instr(lower(title), lower(?)) = 1 OR instr(lower(title), '/' || lower(?)) > 0 THEN 1 \ + ELSE 2 END, rowid", + List.init 5 (fun _ -> Sqlite3.Data.TEXT query) else "", [] in try Sql.with_search_db index.path (fun connection -> Sql.query connection @@ -636,6 +675,7 @@ let hydrate_hits db results = let plain uuid = Ok uuid in List.map (fun (result : search_result) -> + let target = entity_eid result.uuid in let page = if result.is_page then None else @@ -643,23 +683,25 @@ let hydrate_hits db results = | Some eid -> Graph.page_summary plain db eid | None -> None in - let breadcrumbs = - if result.is_page then [] - else - match entity_eid result.uuid with - | Some eid -> Graph.breadcrumbs plain db eid - | None -> [] + let breadcrumbs = match target with + | Some eid when result.is_page -> Graph.namespace_breadcrumbs plain db eid + | Some eid -> Graph.breadcrumbs plain db eid + | None -> [] in + let tags = match target with + | Some eid when result.is_page -> Graph.search_page_tags plain db eid + | _ -> [] in { uuid = result.uuid; - title = (match entity_eid result.uuid with - | Some eid when Option.fold ~none:false ~some:Journal.valid_day - (Graph.int_value (Graph.value db eid "block/journal-day")) -> - Option.value ~default:result.title (Graph.entity_title plain db eid) + title = (match target with + | Some eid when result.is_page -> + Option.fold ~none:result.title ~some:(fun (page : Cache_model.entity_summary) -> + page.title) (Graph.page_summary plain db eid) | _ -> result.title); is_page = result.is_page; page; breadcrumbs; + tags; }) results @@ -673,7 +715,9 @@ let search_hits limit index db query = if Graph.page_is_hidden db datom.e then None else Option.bind (Graph.page_summary (fun value -> Ok value) db datom.e) (fun page -> if String_kit.includes ~sub:query (Dev_query.Unicode.lowercase page.title) then - Some {uuid = page.uuid; title = page.title; is_page = true; page = None; breadcrumbs = []} + Some {uuid = page.uuid; title = page.title; is_page = true; page = None; + breadcrumbs = Graph.namespace_breadcrumbs (fun value -> Ok value) db datom.e; + tags = Graph.search_page_tags (fun value -> Ok value) db datom.e} else None)) |> Seq.take limit |> List.of_seq else hydrate_hits db (search limit index query) diff --git a/shared/src/logseq/core/search_index.mli b/shared/src/logseq/core/search_index.mli index 275d9cf04..a25914966 100644 --- a/shared/src/logseq/core/search_index.mli +++ b/shared/src/logseq/core/search_index.mli @@ -17,6 +17,7 @@ type indexed_search_hit = ; is_page : bool ; page : Cache_model.entity_summary option ; breadcrumbs : Cache_model.entity_summary list + ; tags : Cache_model.entity_summary list } val search_open : string -> unit diff --git a/shared/src/logseq/model.ml b/shared/src/logseq/model.ml index e01eaa531..9b23b89be 100644 --- a/shared/src/logseq/model.ml +++ b/shared/src/logseq/model.ml @@ -47,7 +47,10 @@ type sidebar_page = ; page_journal_day : int option } -type node_deletion = PageToDelete of sidebar_page | BlockToDelete of sidebar_page +type node_deletion = + | PageToDelete of sidebar_page + | BlockToDelete of sidebar_page + | PageDeletionWarning of string type tasks_tab = TasksToday | TasksUpcoming | TasksAll type push_preferences = { enabled : bool; comments : bool; reactions : bool } @@ -159,6 +162,7 @@ type search_hit = ; hit_journal_day : int option ; breadcrumb : string ; breadcrumbs : sidebar_page list + ; hit_tags : sidebar_page list ; is_page : bool } @@ -1650,15 +1654,21 @@ let active_page (current : logseq_model) = current.selected_page | None -> None -let node_permission (current : logseq_model) uuid permission = +let node_capability (current : logseq_model) uuid capability = let raw = match List.find_opt (fun (route : node_projection) -> route.node_uuid = uuid) current.node_routes with | Some route -> route.node_properties_json | None -> if Option.fold ~none:false ~some:(fun (page : sidebar_page) -> page.uuid = uuid) current.selected_page then current.properties_json else "" in match (try Yojson.Basic.from_string raw with _ -> `Null) with | `Assoc fields when List.assoc_opt "ownerUuid" fields = Some (`String uuid) -> - List.assoc_opt permission fields <> Some (`Bool false) - | _ -> true + List.assoc_opt capability fields + | _ -> None + +let node_permission current uuid permission = + node_capability current uuid permission <> Some (`Bool false) + +let page_has_children current uuid = + node_capability current uuid "hasChildPages" = Some (`Bool true) let active_delete_target (current : logseq_model) = let path = if current.search_open then current.search_navigation_path else current.app_navigation_path in @@ -2978,6 +2988,19 @@ let rec update (current : logseq_model) action = else resolve_failed_effect current eff message in let resolved_current = match eff with + | DeletePageEffect (_, uuid) -> + let path = if current.search_open then current.search_navigation_path + else current.app_navigation_path in + let viewing_page = match last_opt path with + | Some route -> navigation_route_uuid route = uuid + | None -> Option.exists (fun (page : sidebar_page) -> page.uuid = uuid) current.selected_page in + if not viewing_page then resolved_current + else if not succeeded then + {resolved_current with pending_node_deletion = Some (PageDeletionWarning message)} + else (match last_opt path with + | None -> enqueue_effect resolved_current (ClearSelectedPageEffect resolved_current.next_effect_id) + | Some _ when current.search_open -> back_search_navigation resolved_current 1 + | Some _ -> back_app_navigation resolved_current 1) | PushPreferenceEffect (_, preferences) -> if succeeded then {resolved_current with push_preferences = preferences; push_error = None} else {resolved_current with push_error = Some message} @@ -3624,6 +3647,12 @@ let rec update (current : logseq_model) action = | None -> current) | RequestDeleteActiveNode -> (match active_delete_target current with + | Some (PageToDelete page) when List.exists (function + | DeletePageEffect (_, uuid) -> uuid = page.uuid | _ -> false) + (current.pending_effects @ current.in_flight_effects) -> current + | Some (PageToDelete page) when page_has_children current page.uuid -> + {current with connection_menu_open = false; pending_node_deletion = + Some (PageDeletionWarning "This page has child pages. Move or delete them first.")} | Some target -> {current with connection_menu_open = false; pending_node_deletion = Some target} | None -> current) | CancelDeleteActiveNode -> @@ -3635,27 +3664,8 @@ let rec update (current : logseq_model) action = | Some (BlockToDelete block), Some (BlockToDelete active), Some cursor when block.uuid = active.uuid -> enqueue_effect updated (DeleteBlockEffect (updated.next_effect_id, block.uuid, cursor)) | Some (PageToDelete page), Some (PageToDelete active), _ when page.uuid = active.uuid -> - let delete_id = updated.next_effect_id in - let deleting = - enqueue_effect updated (DeletePageEffect (delete_id, page.uuid)) - in - if deleting.search_open && deleting.search_navigation_path <> [] then begin - let path = deleting.search_navigation_path in - let route = List.nth path (List.length path - 1) in - let closed = {deleting with search_navigation_path = pop_route path} in - enqueue_effect closed (CloseSearchNodeEffect (closed.next_effect_id, navigation_route_uuid route)) - end - else if deleting.app_navigation_path = [] then - let clear_id = deleting.next_effect_id in - enqueue_effect deleting (ClearSelectedPageEffect clear_id) - else begin - let path = deleting.app_navigation_path in - let route = List.nth path (List.length path - 1) in - let closed = { deleting with app_navigation_path = pop_route path } in - let close_id = closed.next_effect_id in - enqueue_effect closed - (CloseAppNodeEffect (close_id, navigation_route_uuid route)) - end + if page_has_children current page.uuid then update updated RequestDeleteActiveNode + else enqueue_effect updated (DeletePageEffect (updated.next_effect_id, page.uuid)) | _ -> updated) | OpenJournalCalendar -> enqueue_effect current (PresentJournalCalendarEffect current.next_effect_id) | OpenSettings -> diff --git a/shared/src/logseq/model.mli b/shared/src/logseq/model.mli index 7214fa08c..d0c1a8c89 100644 --- a/shared/src/logseq/model.mli +++ b/shared/src/logseq/model.mli @@ -34,7 +34,10 @@ type sidebar_page = ; page_journal_day : int option } -type node_deletion = PageToDelete of sidebar_page | BlockToDelete of sidebar_page +type node_deletion = + | PageToDelete of sidebar_page + | BlockToDelete of sidebar_page + | PageDeletionWarning of string type tasks_tab = TasksToday | TasksUpcoming | TasksAll type push_preferences = { enabled : bool; comments : bool; reactions : bool } @@ -144,6 +147,7 @@ type search_hit = ; hit_journal_day : int option ; breadcrumb : string ; breadcrumbs : sidebar_page list + ; hit_tags : sidebar_page list ; is_page : bool } diff --git a/shared/src/logseq/response_snapshot.ml b/shared/src/logseq/response_snapshot.ml index 02ad2e86c..cc8dbe1c1 100644 --- a/shared/src/logseq/response_snapshot.ml +++ b/shared/src/logseq/response_snapshot.ml @@ -77,6 +77,7 @@ let search_hit input = { Model.hit_uuid; hit_title; hit_journal_day = int_member "journalDay" fields; breadcrumb = breadcrumb fields; breadcrumbs; + hit_tags = List.filter_map sidebar_page (list_member "tags" fields); is_page = bool_member "isPage" fields } | _ -> None diff --git a/shared/src/logseq/view_screens.ml b/shared/src/logseq/view_screens.ml index ca31cb09e..58865dec3 100644 --- a/shared/src/logseq/view_screens.ml +++ b/shared/src/logseq/view_screens.ml @@ -85,6 +85,12 @@ let search_result_row model_source hit_source send : t = ~style_class:"search-match line-clamp-3" ~accessibility_identifier:("search.result.title." ^ hit.hit_uuid) []; + if_ ~test:(Signal.map (fun (hit : Model.search_hit) -> hit.hit_tags <> []) hit_source) + (text ~value:(reactive (Signal.map (fun (hit : Model.search_hit) -> + String.concat " " (List.map (fun (tag : Model.sidebar_page) -> "#" ^ tag.title) + hit.hit_tags)) hit_source)) + ~style_class:"caption single-line" ~foreground:"muted-foreground" + ~accessibility_identifier:("search.result.tags." ^ hit.hit_uuid) []); ]; ] in @@ -838,13 +844,13 @@ let active_overflow_menu model_source send : t = ~on_press:(press send Model.ShareActivePage) []); keyed_dropdown_menu_item ~source:(own (Signal.map (fun model -> Option.to_list (Model.active_delete_target model)) model_source)) - ~key:(function Model.BlockToDelete _ -> `Block | Model.PageToDelete _ -> `Page) ~cmp:compare + ~key:(function Model.BlockToDelete _ -> `Block | _ -> `Page) ~cmp:compare ~mount:(fun source -> match Signal.sample source with | Model.BlockToDelete _ -> dropdown_menu_item ~text:(View_base.tr (Signal.sample model_source) "Delete block") ~variant:`destructive ~accessibility_identifier:"button.block.delete" ?icon:(item_icon "toolbar-delete") ~on_press:(press send Model.RequestDeleteActiveNode) [] - | Model.PageToDelete _ -> + | Model.PageToDelete _ | Model.PageDeletionWarning _ -> dropdown_menu_item ~text:(View_base.tr (Signal.sample model_source) "Delete") ~variant:`destructive ~accessibility_identifier:"button.page.delete" ?icon:(item_icon "toolbar-delete") ~on_press:(press send Model.RequestDeleteActiveNode) []); diff --git a/shared/src/logseq/view_settings.ml b/shared/src/logseq/view_settings.ml index 85bb83272..950c88062 100644 --- a/shared/src/logseq/view_settings.ml +++ b/shared/src/logseq/view_settings.ml @@ -911,7 +911,7 @@ 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 confirm_node_delete_dialog model_source (context : Lui_ui.ui_context) 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 @@ -964,6 +964,28 @@ let page_delete_dialog model_source (context : Lui_ui.ui_context) send : t = ~text:(View_base.tr (Signal.sample model_source) "Delete") []; ] +let page_delete_dialog model_source context send : t = + let warning = Signal.map (fun (model : Model.logseq_model) -> + match model.pending_node_deletion with + | Some (Model.PageDeletionWarning message) -> Some (View_base.tr model message) + | _ -> None) model_source in + stack [ + if_ ~test:(Signal.map Option.is_none warning) + (confirm_node_delete_dialog model_source context send); + if_ ~test:(Signal.map Option.is_some warning) + (dialog ~style_class:"alert" + ~text:(View_base.tr (Signal.sample model_source) "Could not delete page") + ~accessibility_identifier:"dialog.page-delete.warning" + ~on_dismiss:(press send Model.CancelDeleteActiveNode) + [ + text ~value:(reactive (Signal.map (Option.value ~default:"") warning)) []; + button ~style_class:"cancellation-action" + ~accessibility_identifier:"button.page-delete.warning.dismiss" + ~on_press:(press send Model.CancelDeleteActiveNode) + ~text:(View_base.tr (Signal.sample model_source) "OK") []; + ]); + ] + let sync_status_sheet (context : Lui_ui.ui_context) model_source send : t = let sync_now ?variant () = if_ ~test:(Signal.map (fun current -> not (View_base.sync_indicator_synced current)) model_source) diff --git a/shared/test/logseq/app_test.ml b/shared/test/logseq/app_test.ml index 023118f64..3c30a620f 100644 --- a/shared/test/logseq/app_test.ml +++ b/shared/test/logseq/app_test.ml @@ -8497,7 +8497,7 @@ let search_query_publishes_a_core_effect_and_rejects_stale_results () = let hit = { Model.hit_uuid = "page-a"; - hit_title = "Project Alpha"; hit_journal_day = None; + hit_title = "Project Alpha"; hit_journal_day = None; hit_tags = []; breadcrumb = ""; breadcrumbs = []; is_page = true; @@ -8562,7 +8562,7 @@ let native_search_accepts_nonempty_unicode_queries () = ) [ios_backend; kotlin_backend] let shortening_search_clears_results_and_queued_requests () = - let hit = {Model.hit_uuid = "found"; hit_title = "Found"; hit_journal_day = None; + let hit = {Model.hit_uuid = "found"; hit_title = "Found"; hit_journal_day = None; hit_tags = []; breadcrumb = ""; breadcrumbs = []; is_page = false} in let queried = Model.update (Model.initial ()) (Model.ChangeSearchQuery "中文页") in let loaded = Model.update queried (Model.ApplySearchResults ("中文页", [hit])) in @@ -8596,7 +8596,7 @@ let search_results_render_as_keyed_native_rows () = let hit = { Model.hit_uuid = "block-a"; - hit_title = "Project note"; hit_journal_day = None; + hit_title = "Project note"; hit_journal_day = None; hit_tags = []; breadcrumb = "Journal › Parent"; breadcrumbs = []; is_page = false; @@ -8649,7 +8649,7 @@ let search_renders_main_empty_states_and_result_sections () = let page = { Model.hit_uuid = "page-a"; - hit_title = "Project"; hit_journal_day = None; + hit_title = "Project"; hit_journal_day = None; hit_tags = []; breadcrumb = ""; breadcrumbs = []; is_page = true; @@ -8658,7 +8658,7 @@ let search_renders_main_empty_states_and_result_sections () = let block = { Model.hit_uuid = "block-a"; - hit_title = "Project note"; hit_journal_day = None; + hit_title = "Project note"; hit_journal_day = None; hit_tags = []; breadcrumb = "Journal"; breadcrumbs = []; is_page = false; @@ -8766,7 +8766,7 @@ let search_uses_a_regular_list_and_paginates_on_scroll () = send application Model.OpenSearch; send application (Model.ChangeSearchQuery "needle"); let hit i = { Model.hit_uuid = Printf.sprintf "hit-%03d" i; - hit_title = "Needle"; hit_journal_day = None; breadcrumb = ""; breadcrumbs = []; is_page = false } in + hit_title = "Needle"; hit_journal_day = None; hit_tags = []; breadcrumb = ""; breadcrumbs = []; is_page = false } in send application (Model.ApplySearchResults ("needle", List.init 500 hit)); flush application; let renderer = Lui_app.runtime application in @@ -8833,7 +8833,7 @@ let search_navigation_preserves_the_result_list () = send application Model.OpenSearch; send application (Model.ChangeSearchQuery "needle"); let hit i = { Model.hit_uuid = Printf.sprintf "hit-%03d" i; - hit_title = "Needle"; hit_journal_day = None; breadcrumb = "Journal"; breadcrumbs = []; is_page = false } in + hit_title = "Needle"; hit_journal_day = None; hit_tags = []; breadcrumb = "Journal"; breadcrumbs = []; is_page = false } in send application (Model.ApplySearchResults ("needle", List.init 500 hit)); flush application; let renderer = Lui_app.runtime application in @@ -8872,7 +8872,7 @@ let search_navigation_preserves_the_result_list () = (find "screen.search.results" <> list_id) let duplicate_search_query_events_preserve_completed_results () = - let hit = { Model.hit_uuid = "found"; hit_title = "Found"; hit_journal_day = None; + let hit = { Model.hit_uuid = "found"; hit_title = "Found"; hit_journal_day = None; hit_tags = []; breadcrumb = ""; breadcrumbs = []; is_page = false } in let queried = Model.update (Model.initial ()) (Model.ChangeSearchQuery "needle") in let loaded = Model.update queried (Model.ApplySearchResults ("needle", [hit])) in @@ -9567,7 +9567,7 @@ let search_only_patches_preserve_the_open_outline () = let current = { (Model.initial ()) with Model.selected_graph_id = Some "graph"; search_query = "latest"; search_loading = true; outliner_rows = [outline_row "kept" "Keep this block"] } in - let hit = { Model.hit_uuid = "result"; hit_title = "Result"; hit_journal_day = None; breadcrumb = ""; breadcrumbs = []; is_page = true } in + let hit = { Model.hit_uuid = "result"; hit_title = "Result"; hit_journal_day = None; hit_tags = []; breadcrumb = ""; breadcrumbs = []; is_page = true } in let projection = { (empty_core_projection ()) with Model.is_search_patch = true; selected_graph_id = Some "graph"; projection_search_query = "latest"; search_results = [hit] } in let updated = Model.update current (Model.ApplyCoreSnapshot projection) in @@ -9840,15 +9840,23 @@ let active_page_actions_use_typed_core_and_platform_effects () = ]; check_eq ~msg:"page deletion requires explicit confirmation" requested.pending_node_deletion (Some (Model.PageToDelete page)); - check_eq ~msg:"confirmed deletion recycles the page and leaves its selected route" + check_eq ~msg:"confirmation stages deletion while keeping the current page visible" deleted.pending_effects [ Model.SetPageFavoriteEffect (1, "page-a", true); Model.PresentPageShareEffect (2, "Project\n- Photo.jpg", [ "Assets/Photo.jpg" ]); Model.DeletePageEffect (3, "page-a"); - Model.ClearSelectedPageEffect 4; - ] + ]; + let deleting = Model.update deleted (Model.DequeueEffect 3) in + let warning = "This page has child pages. Move or delete them first." in + let failed = Model.update deleting (Model.ResolveEffect (3, false, warning)) in + check_eq ~msg:"the page remains selected when deletion fails" failed.selected_page (Some page); + check_eq failed.pending_node_deletion (Some (Model.PageDeletionWarning warning)); + check_eq failed.pending_effects (List.filter (fun pending -> Model.effect_id pending <> 3) deleted.pending_effects); + let completed = Model.update deleting (Model.ResolveEffect (3, true, "")) in + check ~msg:"successful deletion leaves the selected page" + (List.mem (Model.ClearSelectedPageEffect 4) completed.pending_effects) let page_delete_dialog_exposes_stable_material_actions () = let application = App.create (kotlin_backend ()) in diff --git a/shared/test/logseq/background_search_test.ml b/shared/test/logseq/background_search_test.ml index b704f1ced..c05fab0df 100644 --- a/shared/test/logseq/background_search_test.ml +++ b/shared/test/logseq/background_search_test.ml @@ -98,6 +98,37 @@ let upgrades_rebuild_indexes_that_omitted_public_builtin_tags () = [title; "#" ^ String.lowercase_ascii title]) tags; check_eq ~msg:"index upgrades do not mutate the graph" (R.pending_operations upgraded) []; check ~msg:"a completed upgrade is reused on the next launch" (R.state (reopen ())).search_index_is_fresh) + +let upgrading_legacy_page_rows_indexes_parent_titles () = + let db = D.db_with [ + G.add 20 "block/uuid" (D.Uuid "parent"); + G.add 20 "block/name" (D.String "parent page"); + G.add 20 "block/title" (D.String "Parent Page"); + G.add 21 "block/uuid" (D.Uuid "child"); + G.add 21 "block/name" (D.String "child page"); + G.add 21 "block/title" (D.String "Child Page"); + G.add 21 "block/parent" (D.Ref 20); + ] (G.base_db "Old") in + G.with_search_runtime ~indexed:false db (fun path _ original -> + let stored = D.store ~storage:(Graph_store.storage original.path) db in + let legacy_version = Graph_sqlite.with_app_db original.path (fun connection -> + let roots = Graph_sqlite.query connection + "SELECT addr, content, addresses FROM kvs WHERE addr IN (0, 1) ORDER BY addr" [] + (fun row -> Sqlite3.column_int row 0, Sqlite3.column_text row 1, Sqlite3.column row 2) in + Digest.to_hex (Digest.string (Marshal.to_string ("search-index-v3", roots, []) []))) in + S.search_upsert path ["parent", "Parent Page", "parent"; "child", "Child Page", "child"]; + Graph_sqlite.set_search_version path (Some legacy_version); + let options = {R.default_options with search_index_path = Some path} in + let runtime = R.create original.path 42 (D.conn_from_db stored) options in + check (R.search_index_pending runtime); + check_eq (R.search_page runtime ~offset:0 ~limit:20 "Parent Child") ([], false); + finish runtime; + let hits, more = R.search_page runtime ~offset:0 ~limit:20 "Parent Child" in + check_eq (List.map (fun (hit : S.indexed_search_hit) -> hit.uuid) hits, more) (["child"], false); + check_eq (R.pending_operations runtime) []; + check ~msg:"the rebuilt namespace index survives reopening" + (R.state (R.create original.path 42 (Result.get_ok (Graph_store.restore_conn original.path)) options)).search_index_is_fresh) + let imported_graphs_have_scoped_maintenance () = Mobile_session_test.with_favorite_graphs (fun host call fields cache download -> ignore (call "bootstrapGraph" (fields "graph-a")); @@ -197,5 +228,6 @@ let cases = [ case "bounded indexing yields to editing and preserves concurrent changes" bounded_steps_allow_edits_and_cleanup; case "partial indexing resumes safely after restart" partial_rebuilds_resume_after_restart; case "index upgrades restore public built-in tags without graph edits" upgrades_rebuild_indexes_that_omitted_public_builtin_tags; + case "index upgrades add existing namespace paths without graph edits" upgrading_legacy_page_rows_indexes_parent_titles; case "imported graphs build automatically through scoped maintenance" imported_graphs_have_scoped_maintenance; ] diff --git a/shared/test/logseq/composer_tag_test.ml b/shared/test/logseq/composer_tag_test.ml index acc650c1f..f7cdf9032 100644 --- a/shared/test/logseq/composer_tag_test.ml +++ b/shared/test/logseq/composer_tag_test.ml @@ -335,7 +335,113 @@ let shortcut_text_preserves_readable_tags_and_page_references () = R.with_runtim (Graph_read.unique_named_uuid false (Graph_runtime.db runtime) "Code literal") None; sync_all runtime conn) +let namespace_deletion_preserves_children_and_unlinks_deleted_leaves () = + R.with_runtime (fun session runtime conn -> + let lookup name = Graph_read.unique_named_uuid false (Graph_runtime.db runtime) name in + let leaf = "80000000-0000-4000-8000-000000000066" in + let notes = "80000000-0000-4000-8000-000000000067" in + let capture uuid title = succeed (send session ~uuid ~body:title (tags [] [])) in + let value = Editor_command_test.value runtime in + capture captured "[[Parent Page/Child Page]]"; + let parent = Option.get (lookup "Parent Page") in + let child = Option.get (lookup "Parent Page/Child Page") in + sync_all runtime conn; + let before = Graph_runtime.db runtime in + check_eq (Graph_runtime.delete_page runtime parent "delete-parent" 1792719000000) + (Error "This page has child pages. Move or delete them first."); + check ~msg:"the refusal never stages a graph mutation" (Graph_runtime.db runtime == before); + check_eq (Graph_runtime.pending_operations runtime) []; + check ~msg:"the child can still be opened" + (Option.is_some (Graph_runtime.node_destination runtime child)); + capture notes "[[Parent Page]] [[Parent Page/Another Child Page]]"; + check_eq (lookup "Parent Page") (Some parent); + check ~msg:"another child can be created after the rejected deletion" + (Option.is_some (lookup "Parent Page/Another Child Page")); + capture leaf ("[[Parent Page/Child Page]] and [alias]([[" ^ child ^ "]])"); + check_ok (Graph_runtime.delete_page runtime child "delete-leaf" 1792719000000); + check_eq (value captured "block/title") (Some (Datascript.String "Parent Page/Child Page")); + check_eq (value leaf "block/title") (Some (Datascript.String "Parent Page/Child Page and alias")); + check_eq (Graph_runtime.node_destination runtime child) None; + sync_all runtime conn; + check_eq (value captured "block/title") (Some (Datascript.String "Parent Page/Child Page")); + capture "80000000-0000-4000-8000-000000000068" "[[Parent Page/Child Page]]"; + check ~msg:"an explicitly recreated leaf resolves independently of its Recycle entry" + (Option.exists ((<>) child) (lookup "Parent Page/Child Page")); + sync_all runtime conn) + +let recycled_names_do_not_interfere_with_live_namespaces () = R.with_runtime (fun session runtime conn -> + let module D = Datascript in + let old_parent = "80000000-0000-4000-8000-000000000072" in + let old_child = "80000000-0000-4000-8000-000000000073" in + let fixture = Graph_runtime.db runtime in + let parent, child = fixture.D.max_eid + 1, fixture.D.max_eid + 2 in + let add eid attr value = D.Add (D.Entity_id eid, attr, value) in + ignore (D.transact_conn conn [ + add parent "block/uuid" (D.Uuid old_parent); + add parent "block/title" (D.String "Parent Page"); + add parent "block/name" (D.String "parent page"); + add parent "block/parent" (D.Ref (Option.get (Graph_read.recycle_page_eid fixture))); + add parent "logseq.property/deleted-at" (D.Int64 1792719000000L); + add child "block/uuid" (D.Uuid old_child); + add child "block/title" (D.String "Old Child Page"); + add child "block/name" (D.String "old child page"); + add child "block/parent" (D.Ref parent); + ]); + Graph_runtime.rebase runtime 43 [] [old_parent; old_child]; + let capture uuid title = succeed (send session ~uuid ~body:title (tags [] [])) in + let lookup name = Graph_read.unique_named_uuid false (Graph_runtime.db runtime) name in + capture captured ("Legacy [[" ^ old_parent ^ "]] [[" ^ old_child ^ "]]"); + let db = Graph_runtime.db runtime in + let eid = Option.get (D.entid db "block/uuid" (D.Uuid captured)) in + let block = Option.get (Graph_read.block (fun text -> Ok text) db eid) in + let markup = items "markup" (Node_presentation.decorate db captured (Rpc.block_json block)) in + check ~msg:"existing links to recycled nodes retain their labels as text" + (List.for_all (fun node -> member "type" node = `String "text") markup); + capture "80000000-0000-4000-8000-000000000074" "[[Parent Page]]"; + let parent = Option.get (lookup "Parent Page") in + check (parent <> old_parent); + capture "80000000-0000-4000-8000-000000000075" "[[Parent Page]] [[Parent Page/Another Child Page]]"; + check_eq ~msg:"a recycled name cannot make a live parent ambiguous" (lookup "Parent Page") (Some parent); + check ~msg:"new children can be added beneath the live parent" + (Option.is_some (lookup "Parent Page/Another Child Page")); + sync_all runtime conn) + +let desktop_namespace_roots_are_reused () = R.with_runtime (fun session runtime conn -> + let module D = Datascript in + let uuid = "80000000-0000-4000-8000-000000000076" in + let db = Graph_runtime.db runtime in + let library = D.Db.datoms db D.Avet ~a:"block/name" ~v:(D.String "library") () + |> Seq.uncons |> Option.get |> fst in + let eid = D.Entity_id (db.D.max_eid + 1) in + ignore (D.transact_conn conn [ + D.Add (eid, "block/uuid", D.Uuid uuid); + D.Add (eid, "block/name", D.String "desktop parent"); + D.Add (eid, "block/title", D.String "Desktop Parent"); + D.Add (eid, "block/parent", D.Ref library.D.e); + D.Add (eid, "block/tags", D.Ref_to (D.Ident "logseq.class/Page")); + ]); + Graph_runtime.rebase runtime 43 [] [uuid]; + let capture id = send session ~uuid:id ~body:"[[Desktop Parent/Child Page]]" (tags [] []) in + succeed (capture captured); + let read () = + let db = Graph_runtime.db runtime in + let child = Option.get (Graph_read.unique_named_uuid false db "Desktop Parent/Child Page") in + let child_eid = Option.get (D.entid db "block/uuid" (D.Uuid child)) in + let parent = Option.bind (Graph_read.namespace_parent db child_eid) (Graph_read.uuid_for_eid db) in + check_eq parent (Some uuid); + check_eq (Graph_read.unique_named_uuid false db "Desktop Parent") (Some uuid); + child in + let child = read () in + succeed (capture "80000000-0000-4000-8000-000000000077"); + check_eq (read ()) child; + sync_all runtime conn; + check_eq (read ()) child) + let cases = [ + case "creating children reuses desktop namespace roots under Library" desktop_namespace_roots_are_reused; + case "recycled names do not interfere with live namespaces" recycled_names_do_not_interfere_with_live_namespaces; + case "namespace deletion protects children and unlinks deleted leaves" + namespace_deletion_preserves_children_and_unlinks_deleted_leaves; case "shortcut text renders tags and creates reusable page references" shortcut_text_preserves_readable_tags_and_page_references; case "new page and tag properties survive confirmed sync" new_property_definitions_roundtrip_through_sync; case "adjacent wiki reference tags apply to the referenced page" adjacent_reference_tags_target_the_page; diff --git a/shared/test/logseq/drive_host.ml b/shared/test/logseq/drive_host.ml index 0bf8197dd..e64bfc0ec 100644 --- a/shared/test/logseq/drive_host.ml +++ b/shared/test/logseq/drive_host.ml @@ -322,14 +322,14 @@ let search_hits host = [ { Model.hit_uuid = "page-1"; - hit_title = "Alpha Doc"; hit_journal_day = None; + hit_title = "Alpha Doc"; hit_journal_day = None; hit_tags = []; breadcrumb = ""; breadcrumbs = []; is_page = true; }; { Model.hit_uuid = "block-1"; - hit_title = "alpha block"; hit_journal_day = None; + hit_title = "alpha block"; hit_journal_day = None; hit_tags = []; breadcrumb = "Alpha Doc"; breadcrumbs = [ { Model.uuid = "page-1"; title = "Alpha Doc"; page_journal_day = None} ]; is_page = false; diff --git a/shared/test/logseq/mobile_feedback_test.ml b/shared/test/logseq/mobile_feedback_test.ml index 9902c5055..627c79e0f 100644 --- a/shared/test/logseq/mobile_feedback_test.ml +++ b/shared/test/logseq/mobile_feedback_test.ml @@ -99,7 +99,13 @@ let search_destinations_keep_the_page_menu () = let favorite = Model.update current Model.ToggleActivePageFavorite in check ~msg:"Favorite targets the visible search page" (List.exists (function Model.SetPageFavoriteEffect (_, uuid, _) -> uuid = Q.page | _ -> false) favorite.pending_effects); - let deleted = Model.update (Model.update current Model.RequestDeleteActiveNode) Model.ConfirmDeleteActiveNode in + let confirmed = Model.update (Model.update current Model.RequestDeleteActiveNode) Model.ConfirmDeleteActiveNode in + check_eq ~msg:"search stays on the page until deletion succeeds" + confirmed.search_navigation_path current.search_navigation_path; + let id = List.find_map (function Model.DeletePageEffect (id, uuid) when uuid = Q.page -> Some id + | _ -> None) confirmed.pending_effects |> Option.get in + let deleted = Model.update (Model.update confirmed (Model.DequeueEffect id)) + (Model.ResolveEffect (id, true, "")) in check_eq ~msg:"deleting a search page preserves the underlying app navigation" deleted.app_navigation_path current.app_navigation_path; check_eq ~msg:"deleting a search page returns to the previous search destination" deleted.search_navigation_path []; diff --git a/shared/test/logseq/rpc_test.ml b/shared/test/logseq/rpc_test.ml index 14976dfee..1ba553c1f 100644 --- a/shared/test/logseq/rpc_test.ml +++ b/shared/test/logseq/rpc_test.ml @@ -861,6 +861,7 @@ let search_projects_page_context_and_clears_blank_queries () = is_page = false; page = Some page; breadcrumbs = [ page ]; + tags = []; } in let session = @@ -892,7 +893,7 @@ let search_projects_page_context_and_clears_blank_queries () = let search_results_are_loaded_in_bounded_pages () = let hits = List.init 145 (fun i -> { Search.uuid = Printf.sprintf "hit-%03d" i; title = "Search"; - is_page = true; page = None; breadcrumbs = [] }) in + is_page = true; page = None; breadcrumbs = []; tags = [] }) in let session = Session.create_session { Session.default_options with outliner_projection_limit = Some 32; graph_search = Some (fun _ -> hits) } in @@ -6613,11 +6614,12 @@ let search_json_keeps_page_and_breadcrumb_order () = is_page = false; page = None; breadcrumbs = []; + tags = []; } in check_eq (Json.to_string (Rpc.search_hit_json hit)) - "{\"uuid\":\"hit\",\"title\":\"Hit\",\"isPage\":false,\"page\":null,\"breadcrumbs\":[]}"; + "{\"uuid\":\"hit\",\"title\":\"Hit\",\"isPage\":false,\"page\":null,\"breadcrumbs\":[],\"tags\":[]}"; check_eq (Json.to_string (Rpc.search_hit_json @@ -6626,8 +6628,9 @@ let search_json_keeps_page_and_breadcrumb_order () = is_page = true; page = Some page; breadcrumbs = [ parent; page ]; + tags = [ { uuid = "tag"; title = "Projects" } ]; })) - "{\"uuid\":\"hit\",\"title\":\"Hit\",\"isPage\":true,\"page\":{\"uuid\":\"page\",\"title\":\"Page\"},\"breadcrumbs\":[{\"uuid\":\"parent\",\"title\":\"Parent\"},{\"uuid\":\"page\",\"title\":\"Page\"}]}" + "{\"uuid\":\"hit\",\"title\":\"Hit\",\"isPage\":true,\"page\":{\"uuid\":\"page\",\"title\":\"Page\"},\"breadcrumbs\":[{\"uuid\":\"parent\",\"title\":\"Parent\"},{\"uuid\":\"page\",\"title\":\"Page\"}],\"tags\":[{\"uuid\":\"tag\",\"title\":\"Projects\"}]}" let flashcard_json_keeps_counters_state_and_children () = List.iter diff --git a/shared/test/logseq/search_index_test.ml b/shared/test/logseq/search_index_test.ml index 5427f5662..9367c30c9 100644 --- a/shared/test/logseq/search_index_test.ml +++ b/shared/test/logseq/search_index_test.ml @@ -304,6 +304,87 @@ let builtin_content_tags_are_searchable () = (not (List.exists (fun (hit : Search.indexed_search_hit) -> hit.title = "Node title") (Search.search_hits 100 index db "Node title")))) +let namespace_search_includes_parent_titles_and_tags () = with_index (fun index -> + let bootstrap = match Graph_bootstrap.database "test" false (fun value -> Ok value) with + | Ok db -> db | Error message -> fail message in + let first = bootstrap.Ds.max_eid + 1 in + let parent, child, tag, root, similar, block = first, first + 1, first + 2, first + 3, first + 4, first + 5 in + let root_uuid = "01927850-0000-7da0-8b3f-6dbb64aa4ec1" in + let similar_uuid = "01927850-0000-7da0-8b3f-6dbb64aa4ec2" in + let inside_uuid = "01927850-0000-7da0-8b3f-6dbb64aa4ec3" in + let library = Ds.Db.datoms bootstrap Ds.Avet ~a:"block/name" ~v:(Ds.String "library") () + |> Seq.uncons |> Option.get |> fst in + let db = Ds.db_with [ + add root "block/uuid" (Ds.Uuid root_uuid); + add root "block/name" (Ds.String "计划"); + add root "block/title" (Ds.String "计划"); + add root "block/parent" (Ds.Ref library.Ds.e); + add parent "block/uuid" (Ds.Uuid page_uuid); + add parent "block/name" (Ds.String "parent page"); + add parent "block/title" (Ds.String "Parent Page"); + add parent "block/parent" (Ds.Ref root); + add child "block/uuid" (Ds.Uuid block_uuid); + add child "block/name" (Ds.String "child page"); + add child "block/title" (Ds.String "Child Page"); + add child "block/parent" (Ds.Ref parent); + add tag "block/uuid" (Ds.Uuid ref_block_uuid); + add tag "block/title" (Ds.String "Projects"); + add tag "block/name" (Ds.String "projects"); + add tag "block/tags" (Ds.Ref_to (Ds.Ident "logseq.class/Tag")); + add child "block/tags" (Ds.Ref tag); + add child "block/tags" (Ds.Ref_to (Ds.Ident "logseq.class/Page")); + add child "block/tags" (Ds.Ref_to (Ds.Ident "logseq.class/Task")); + add similar "block/uuid" (Ds.Uuid similar_uuid); + add similar "block/name" (Ds.String "child page notes"); + add similar "block/title" (Ds.String "Child Page Notes"); + add block "block/uuid" (Ds.Uuid inside_uuid); + add block "block/title" (Ds.String "Child Page block"); + add block "block/page" (Ds.Ref child); + ] bootstrap in + Search.refresh index db; + let matching_child db query = + let hits, _ = Search.search_hits_page ~offset:0 ~limit:20 index db query in + List.find_opt (fun (hit : Search.indexed_search_hit) -> hit.uuid = block_uuid) hits in + let hit = match matching_child db "Parent Child" with + | Some hit -> hit | None -> fail "The child page must match terms across its namespace" in + check_eq hit.title "Child Page"; + check_eq (List.map (fun (page : Cache_model.entity_summary) -> page.title) hit.breadcrumbs) ["计划"; "Parent Page"]; + check_eq (List.map (fun (tag : Cache_model.entity_summary) -> tag.title) hit.tags |> List.sort String.compare) + ["Projects"; "Task"]; + List.iter (fun query -> + check_eq ~msg:query (matching_child db query) (Some hit)) + ["Child Page"; "计划"; "parent child"; "计划/Parent Page/Child Page"; "Parent/Child"]; + let ids hits = List.map (fun (hit : Search.indexed_search_hit) -> hit.uuid) hits in + let page offset = let hits, more = Search.search_hits_page ~offset ~limit:1 index db "Child Page" in + ids hits, more in + check_eq ~msg:"an exact leaf sorts ahead of title prefixes and block matches" (page 0) ([block_uuid], true); + check_eq (page 1) ([similar_uuid], true); + check_eq (page 2) ([inside_uuid], false); + check_eq (page 3) ([], false); + check ~msg:"unpaged queries hydrate the same metadata" + (List.mem hit (Search.search_hits 20 index db "Parent Child")); + check ~msg:"short unpaged queries preserve metadata" + (List.mem hit (Search.search_hits 20 index db "Ch")); + let renamed = Ds.db_with [add parent "block/title" (Ds.String "Renamed Page")] db in + Search.refresh_uuids index db renamed [page_uuid]; + check_eq (matching_child renamed "Parent Child") None; + check ~msg:"ancestor renames refresh the indexed child path" + (Option.is_some (matching_child renamed "Renamed Child")); + let moved = Ds.db_with [add parent "block/parent" (Ds.Ref similar)] renamed in + Search.refresh_uuids index renamed moved [page_uuid]; + check_eq (matching_child moved "计划") None; + let moved_hit = Option.get (matching_child moved "Renamed Child") in + check_eq (List.map (fun (page : Cache_model.entity_summary) -> page.uuid) moved_hit.breadcrumbs) + [similar_uuid; page_uuid]; + let recycled = Ds.db_with [add parent "logseq.property/deleted-at" (Ds.Int64 1234L)] moved in + Search.refresh_uuids index moved recycled [page_uuid]; + check_eq (matching_child recycled "Renamed Child") None; + check_eq (ids (fst (Search.search_hits_page ~offset:0 ~limit:20 index recycled "Child Page"))) + [similar_uuid]; + Search.refresh_uuids index recycled moved [page_uuid]; + check_eq ~msg:"restoring a namespace restores its search entries" + (matching_child moved "Renamed Child") (Some moved_hit)) + let page_title_matches_joins_sparse_pages_and_dynamic_journals () = let conn = Ds.create_conn ~schema () in check_eq (Search.page_title_matches ~limit:12 (Ds.conn_db conn) "needle") []; @@ -333,6 +414,8 @@ let page_title_matches_joins_sparse_pages_and_dynamic_journals () = let cases = [ + case "namespace search matches parent titles and returns ancestors and tags" + namespace_search_includes_parent_titles_and_tags; case "page completion joins sparse pages and dynamic journals" page_title_matches_joins_sparse_pages_and_dynamic_journals; case "graph search preserves FTS matches for long queries" graph_search_preserves_fts_matches_for_long_queries; From 5146f9de034b04eaa359842ef6b214f7ebdc25e0 Mon Sep 17 00:00:00 2001 From: Tienson Qin Date: Sat, 5 Dec 2026 15:03:23 +0800 Subject: [PATCH 2/2] Preserve page references through sync and scope namespace search --- shared/src/logseq/core/graph_read.ml | 8 +-- shared/src/logseq/core/graph_runtime.ml | 10 +++- shared/src/logseq/core/markup.ml | 33 +++++++---- shared/src/logseq/core/ref_text.ml | 2 +- shared/src/logseq/core/search_index.ml | 72 ++++++++++++++++-------- shared/test/logseq/composer_tag_test.ml | 58 +++++++++++++++++++ shared/test/logseq/graph_runtime_test.ml | 55 ++++++++++++++++++ shared/test/logseq/markup_test.ml | 7 +++ shared/test/logseq/search_index_test.ml | 23 ++++++++ 9 files changed, 225 insertions(+), 43 deletions(-) diff --git a/shared/src/logseq/core/graph_read.ml b/shared/src/logseq/core/graph_read.ml index 87cbcb7dd..6b64e18f3 100644 --- a/shared/src/logseq/core/graph_read.ml +++ b/shared/src/logseq/core/graph_read.ml @@ -800,17 +800,17 @@ let normalize_title_text create_tag db uuid title = , entity_summaries (fun value -> Ok value) db eid "block/tags" ) | None -> ([], []) in - let visible = function - | Some uuid as found when Option.exists (fun eid -> not (page_is_hidden db eid)) + let live = function + | Some uuid as found when Option.exists (fun eid -> not (recycled db eid)) (Ds.entid db "block/uuid" (Ds.Uuid uuid)) -> found | _ -> None in Ref_text.to_ids (fun name -> - match visible (known_title (refs @ tags) name) with + match live (known_title (refs @ tags) name) with | Some uuid -> Some uuid | None -> unique_named_uuid false db name) (fun name -> - match visible (known_title tags name) with + match live (known_title tags name) with | Some uuid -> Some uuid | None -> (match unique_named_uuid true db name with diff --git a/shared/src/logseq/core/graph_runtime.ml b/shared/src/logseq/core/graph_runtime.ml index c4614f87c..269195ed1 100644 --- a/shared/src/logseq/core/graph_runtime.ml +++ b/shared/src/logseq/core/graph_runtime.ml @@ -213,12 +213,16 @@ let confirmed_operation confirmed server_t _authoritative let stored_transaction runtime database (operation : Ops.pending_operation) = let recompile = operation.base_t <> (state runtime).server_t && - match operation.intent with Ops.Add_comment _ | Ops.Set_reaction _ -> true | _ -> false in + match operation.intent, operation.state with + | Ops.Add_comment _, _ | Ops.Set_reaction _, _ -> true + | Ops.Delete_page _, Ops.Accepted _ -> false + | Ops.Delete_page _, _ -> true + | _ -> false in match Graph_sqlite.pending_tx runtime.path operation.operation_id with | Some (tx, _) when not recompile -> Ok tx | _ -> - (* Discussion writes depend on the current thread and actor's reactions. - Other operations retain their resolved transaction during reconciliation. *) + (* Re-resolve discussion writes and pending page deletions when the graph + changes. In particular, unlink references from the current titles. *) let ( let* ) = Result.bind in let* () = if operation.base_t <> (state runtime).server_t && not (Ops.safe_to_rebase operation.intent) then diff --git a/shared/src/logseq/core/markup.ml b/shared/src/logseq/core/markup.ml index 10537b393..8e55cafdf 100644 --- a/shared/src/logseq/core/markup.ml +++ b/shared/src/logseq/core/markup.ml @@ -263,6 +263,8 @@ let emphasis = function | `Strike_through -> "strike-through" | `Highlight -> "highlight" +let escaped_hash_or_backslash = Str.regexp {|\\[\\#]|} + let rec tag_part node = match node with | Inline.Nested_link link -> node_name link @@ -304,7 +306,7 @@ and convert_macro (macro : Inline.Macro.t) raw = ] | _ -> raw -and convert_nodes source references tags nodes = +and convert_nodes ~decode_escaped_hash source references tags nodes = let rec collect converted = function | (Inline.Inline_Html "", _) :: rest -> let rec closing inside = function @@ -313,19 +315,27 @@ and convert_nodes source references tags nodes = | [] -> None in (match closing [] rest with | Some (inside, rest) -> collect (append_node converted - (Markup_emphasis ("underline", convert_nodes source references tags inside))) rest + (Markup_emphasis ("underline", convert_nodes ~decode_escaped_hash source references tags inside))) rest | None -> collect (append_node converted (Markup_text "")) rest) | (node, position) :: rest -> collect - (List.fold_left append_node converted (convert_node source references tags node position)) rest + (List.fold_left append_node converted + (convert_node ~decode_escaped_hash source references tags node position)) rest | [] -> converted in collect [] nodes -and convert_node source references tags node position = +and convert_node ~decode_escaped_hash source references tags node position = let raw = [ Markup_text (match position with | None -> Inline.ascii node | Some _ -> source_slice source position) ] in match node with - | Inline.Plain value -> [ Markup_text value ] + | Inline.Plain value -> + (* The inline parser keeps Markdown escapes. The block parser already + decodes table cells, so only plain text from inline parsing needs this. *) + let value = if decode_escaped_hash && S.includes ~sub:"\\#" value then + Str.global_substitute escaped_hash_or_backslash + (fun text -> String.sub (Str.matched_string text) 1 1) value + else value in + [ Markup_text value ] | Inline.Spaces value -> [ Markup_text value ] | Inline.Break_Line -> [ Markup_text "\n" ] | Inline.Hard_Break_Line -> [ Markup_text "\n" ] @@ -333,7 +343,8 @@ and convert_node source references tags node position = | Inline.Inline_Html html when S.starts_with ~prefix:"" html && S.ends_with ~suffix:"" html -> let inner = String.sub html 5 (String.length html - 11) in let children = match Angstrom.parse_string ~consume:Angstrom.Consume.All (Inline.parse config) inner with - | Ok nodes -> convert_nodes inner references tags nodes | Error _ -> [Markup_text inner] in + | Ok nodes -> convert_nodes ~decode_escaped_hash:true inner references tags nodes + | Error _ -> [Markup_text inner] in [Markup_emphasis ("underline", children)] | Inline.Verbatim value -> [ Markup_code value ] | Inline.Latex_Fragment (Inline.Inline expression) -> @@ -346,7 +357,7 @@ and convert_node source references tags node position = [ Markup_emphasis ( emphasis style - , convert_nodes source references tags + , convert_nodes ~decode_escaped_hash source references tags (List.map (fun child -> (child, None)) children) ); ] | Inline.Nested_link link -> @@ -383,7 +394,7 @@ and convert_node source references tags node position = (match link.label with | [] | [ Inline.Plain "" ] -> [ Markup_text value ] | label -> - convert_nodes source references tags + convert_nodes ~decode_escaped_hash source references tags (List.map (fun child -> (child, None)) label))) | _ -> let url = (match link.url with @@ -399,7 +410,7 @@ and convert_node source references tags node position = when S.includes ~sub:(protocol ^ "://") link.full_text -> protocol ^ "://" ^ value | url -> Inline.string_of_url url) - , convert_nodes source references tags + , convert_nodes ~decode_escaped_hash source references tags (List.map (fun child -> (child, None)) link.label) ); ]) | _ -> raw @@ -409,7 +420,7 @@ let parse_inline references tags source = Angstrom.parse_string ~consume:Angstrom.Consume.All (Inline.parse config) source with - | Ok nodes -> convert_nodes source references tags nodes + | Ok nodes -> convert_nodes ~decode_escaped_hash:true source references tags nodes | Error _ -> [ Markup_text source ] let heading_prefix = Str.regexp "^ ? ? ?#+[ \t]+" @@ -434,7 +445,7 @@ let parse_blocks references tags source = else let blocks = Mldoc.Parser.parse config source |> List.filter_map (function | Mldoc.Type.Table table, (position : Mldoc.Pos.pos_meta) -> - let cell nodes = convert_nodes source references tags + let cell nodes = convert_nodes ~decode_escaped_hash:false source references tags (List.map (fun node -> node, None) nodes) in let row cells = List.map cell cells in let header = Option.map row table.header in diff --git a/shared/src/logseq/core/ref_text.ml b/shared/src/logseq/core/ref_text.ml index 0b12fd0bf..7f0fb1285 100644 --- a/shared/src/logseq/core/ref_text.ml +++ b/shared/src/logseq/core/ref_text.ml @@ -241,7 +241,7 @@ let unlink uuid label title = if reference.name <> uuid then None else match reference.kind with | Page -> Some (Option.value ~default:label alias) - | Tag -> Some ("#" ^ label)) title + | Tag -> Some ("\\#" ^ label)) title let to_text tag_title ref_title title = rewrite (fun reference _ -> diff --git a/shared/src/logseq/core/search_index.ml b/shared/src/logseq/core/search_index.ml index 7dcfa3f2f..05aff3586 100644 --- a/shared/src/logseq/core/search_index.ml +++ b/shared/src/logseq/core/search_index.ml @@ -618,14 +618,31 @@ let refresh index db = let query_rows index sql binds = try search_query index.path sql binds with Failure _ -> [] -let namespace_query_tail query = - match String.rindex_opt query '/' with - | Some slash when slash > 0 && not (String.starts_with ~prefix:"../" query - || String.starts_with ~prefix:"./" query || String_kit.includes ~sub:"://" query - || Dev_query.Date_time_util.valid_journal_title query) -> - let tail = String.trim (String.sub query (slash + 1) (String.length query - slash - 1)) in - if utf8_length tail < 3 then None else Some tail - | _ -> None +let namespace_query_parts query = + if not (String.contains query '/') + || String.starts_with ~prefix:"../" query || String.starts_with ~prefix:"./" query + || String_kit.includes ~sub:"://" query || Dev_query.Date_time_util.valid_journal_title query + then None + else + let parts = List.rev_map String.trim (String.split_on_char '/' query) in + if List.mem "" parts then None else Some parts + +let title_matches_namespace parts title = + let titles = List.rev (String.split_on_char '/' title) in + let rec matches parts titles = match parts, titles with + | [], _ -> true + | part :: parts, title :: titles -> + String_kit.includes ~sub:part title && matches parts titles + | _ -> false in + matches parts titles + +let literal_match term = + if utf8_length term < 3 then + let escaped = List.fold_left (fun value symbol -> + String_kit.replace value ~match_:symbol ~replacement:("\\" ^ symbol)) + term ["\\"; "%"; "_"] in + "title LIKE ? ESCAPE '\\'", "%" ^ escaped ^ "%" + else "title MATCH ?", fts_phrase_input term let full_text_rows ?(prioritize_pages = false) ?exclude_uuid ~offset ~limit index query = let query = String.trim query in @@ -634,20 +651,9 @@ let full_text_rows ?(prioritize_pages = false) ?exclude_uuid ~offset ~limit inde if query = "" || limit <= 0 then [] else (* Trigram MATCH cannot find one or two characters. Search the same indexed content literally, keeping the result window bounded before hydration. *) - let predicate, search_binds = - if utf8_length query < 3 then - let escaped = List.fold_left (fun value symbol -> - String_kit.replace value ~match_:symbol ~replacement:("\\" ^ symbol)) - query ["\\"; "%"; "_"] in - "title LIKE ? ESCAPE '\\'", [Sqlite3.Data.TEXT ("%" ^ escaped ^ "%")] - else - let input = Sqlite3.Data.TEXT (get_match_input query) in - match namespace_query_tail query with - | Some tail -> "(title MATCH ? OR title MATCH ?)", [input; Sqlite3.Data.TEXT (get_match_input tail)] - | None -> "title MATCH ?", [input] in - let predicate, search_binds = match exclude_uuid with - | Some uuid -> predicate ^ " AND id <> ?", search_binds @ [Sqlite3.Data.TEXT uuid] - | None -> predicate, search_binds in + let predicate, input = + if utf8_length query < 3 then literal_match query + else "title MATCH ?", get_match_input query in let order, rank_binds = if prioritize_pages then (* Rank page titles before LIMIT/OFFSET. Preserve the existing FTS @@ -659,9 +665,27 @@ let full_text_rows ?(prioritize_pages = false) ?exclude_uuid ~offset ~limit inde List.init 5 (fun _ -> Sqlite3.Data.TEXT query) else "", [] in try Sql.with_search_db index.path (fun connection -> + let rows = "SELECT rowid, id, page, title FROM blocks_fts WHERE " in + let from, search_binds = match namespace_query_parts query with + | None -> "(" ^ rows ^ predicate ^ ")", [Sqlite3.Data.TEXT input] + | Some parts -> + let parts = List.map Dev_query.Unicode.lowercase parts in + let anchor = List.fold_left (fun longest part -> + if utf8_length part > utf8_length longest then part else longest) "" parts in + let candidate, term = literal_match anchor in + Sqlite3.create_fun1 connection "matches_namespace" (function + | Sqlite3.Data.TEXT title when title_matches_namespace parts (Dev_query.Unicode.lowercase title) -> + Sqlite3.Data.INT 1L + | _ -> Sqlite3.Data.INT 0L); + "(" ^ rows ^ predicate ^ " AND id <> page UNION ALL " + ^ rows ^ candidate ^ " AND id = page AND matches_namespace(title))", + [Sqlite3.Data.TEXT input; Sqlite3.Data.TEXT term] in + let filter, filter_binds = match exclude_uuid with + | Some uuid -> " WHERE id <> ?", [Sqlite3.Data.TEXT uuid] + | None -> "", [] in Sql.query connection - ("SELECT id, page, title FROM blocks_fts WHERE " ^ predicate ^ order ^ " LIMIT ? OFFSET ?") - (search_binds @ rank_binds @ [Sqlite3.Data.INT (Int64.of_int limit); + ("SELECT id, page, title FROM " ^ from ^ filter ^ order ^ " LIMIT ? OFFSET ?") + (search_binds @ filter_binds @ rank_binds @ [Sqlite3.Data.INT (Int64.of_int limit); Sqlite3.Data.INT (Int64.of_int (max 0 offset))]) (fun row -> let uuid = Sqlite3.column_text row 0 and page_uuid = Sqlite3.column_text row 1 in diff --git a/shared/test/logseq/composer_tag_test.ml b/shared/test/logseq/composer_tag_test.ml index f7cdf9032..e5d657449 100644 --- a/shared/test/logseq/composer_tag_test.ml +++ b/shared/test/logseq/composer_tag_test.ml @@ -437,7 +437,65 @@ let desktop_namespace_roots_are_reused () = R.with_runtime (fun session runtime sync_all runtime conn; check_eq (read ()) child) +let append_to_capture session suffix = + succeed (Rpc_test.dispatch_json session "openNode" (J.to_string (`Assoc ["uuid", `String captured]))); + let opened = Editor_command_test.event session "tapBlock" ["uuid", `String captured] in + let route = items "nodeRoutes" opened |> List.rev |> List.hd in + let title = text (member "title" (member "editing" (member "outlinerState" route))) ^ suffix in + ignore (Editor_command_test.type_at session title (Outliner_state.utf16_length title)); + Editor_command_test.save session + +let with_title_normalization f = R.with_runtime (fun session runtime conn -> + let session = Rpc_session.create_session { (Rpc_session.host session) with + graph_normalize_titles = Some (Graph_runtime.normalize_titles runtime) } in + ignore (Rpc_test.configure_plain_session session); + Q.open_results session; + f session runtime conn) + +let editing_a_note_preserves_its_hidden_page_link () = with_title_normalization (fun session runtime conn -> + let module D = Datascript in + let lookup name = Graph_read.unique_named_uuid false (Graph_runtime.db runtime) name in + succeed (send session ~body:"See [[Project Notes]]" (tags [] [])); + let hidden = Option.get (lookup "Project Notes") in + sync_all runtime conn; + let visible = "80000000-0000-4000-8000-000000000082" in + let id = D.Entity_id ((Graph_runtime.db runtime).D.max_eid + 1) in + ignore (D.transact_conn conn [ + D.Add (D.Lookup_ref ("block/uuid", D.Uuid hidden), "logseq.property/hide?", D.Bool true); + D.Add (id, "block/uuid", D.Uuid visible); + D.Add (id, "block/name", D.String "project notes"); + D.Add (id, "block/title", D.String "Project Notes"); + ]); + Graph_runtime.rebase runtime ((Graph_runtime.state runtime).server_t + 1) [] [hidden; visible]; + check_eq ~msg:"fresh lookups prefer the visible homonym" (lookup "Project Notes") (Some visible); + append_to_capture session " after approval"; + sync_all runtime conn; + check_eq ~msg:"editing an existing link preserves its hidden live target" + (Editor_command_test.value runtime captured "block/title") + (Some (D.String ("See [[" ^ hidden ^ "]] after approval")))) + +let editing_a_note_does_not_recreate_its_deleted_tag () = with_title_normalization (fun session runtime conn -> + let module D = Datascript in + let lookup name = Graph_read.unique_named_uuid true (Graph_runtime.db runtime) name in + succeed (send session ~body:"Draft #[[Weekly Review]]" (tags [] [])); + let tag = Option.get (lookup "Weekly Review") in + sync_all runtime conn; + check_eq (tag_titles runtime captured) ["Weekly Review"]; + check_ok (Graph_runtime.delete_page runtime tag "delete-weekly-review" 1792719000000); + check_eq (Editor_command_test.value runtime captured "block/title") (Some (D.String "Draft \\#Weekly Review")); + append_to_capture session " finished"; + sync_all runtime conn; + let db = Graph_runtime.db runtime in + let eid = Option.get (D.entid db "block/uuid" (D.Uuid captured)) in + let block = Option.get (Graph_read.block (fun text -> Ok text) db eid) in + check_eq (Markup.parse block.references block.tags block.title |> Markup.plain_text) "Draft #Weekly Review finished"; + check_eq (tag_titles runtime captured) []; + check_eq (lookup "Weekly") None; + check_eq (lookup "Weekly Review") None) + let cases = [ + case "unrelated edits preserve existing links to hidden live pages" editing_a_note_preserves_its_hidden_page_link; + case "editing a note keeps a deleted inline tag as literal text" editing_a_note_does_not_recreate_its_deleted_tag; case "creating children reuses desktop namespace roots under Library" desktop_namespace_roots_are_reused; case "recycled names do not interfere with live namespaces" recycled_names_do_not_interfere_with_live_namespaces; case "namespace deletion protects children and unlinks deleted leaves" diff --git a/shared/test/logseq/graph_runtime_test.ml b/shared/test/logseq/graph_runtime_test.ml index 6383311a4..ff74b9c48 100644 --- a/shared/test/logseq/graph_runtime_test.ml +++ b/shared/test/logseq/graph_runtime_test.ml @@ -544,6 +544,59 @@ let recorded_deletions_replay_after_remote_progress () = check_eq (Ds.entid (Runtime.db current) "block/uuid" (Ds.Uuid uuid)) None; check_eq (title (Ds.conn_db conn) uuid) "Remote update") +let page_delete_rebases_reference_rewrites_onto_remote_notes () = + with_store (fun path -> + let page = "00000000-0000-4000-8000-000000000021" in + let edited = "00000000-0000-4000-8000-000000000022" in + let unlinked = "00000000-0000-4000-8000-000000000023" in + let link = "[[" ^ page ^ "]]" in + let db = Ds.db_with [ + add 20 "block/uuid" (Ds.Uuid "00000000-0000-4000-8000-000000000020"); + add 20 "block/name" (Ds.String "recycle"); + add 20 "block/title" (Ds.String "Recycle"); + add 21 "block/uuid" (Ds.Uuid page); + add 21 "block/name" (Ds.String "project"); + add 21 "block/title" (Ds.String "Project"); + add 22 "block/uuid" (Ds.Uuid edited); + add 22 "block/title" (Ds.String ("See " ^ link)); + add 22 "block/refs" (Ds.Ref 21); + add 23 "block/uuid" (Ds.Uuid unlinked); + add 23 "block/title" (Ds.String ("Read " ^ link)); + add 23 "block/refs" (Ds.Ref 21); + ] (base_db "Old") in + let conn = Ds.conn_from_db db in + let runtime = Runtime.create path 42 conn Runtime.default_options in + check_ok (Runtime.delete_page runtime page "delete-project" 1792719000000); + check_eq (title (Runtime.db runtime) edited) "See Project"; + ignore (Ds.transact_conn conn [ + add 22 "block/title" (Ds.String ("See " ^ link ^ " after approval")); + add 23 "block/title" (Ds.String "Read the next draft"); + Ds.Retract (Ds.Entity_id 23, "block/refs", Some (Ds.Ref 21)); + ]); + Runtime.rebase runtime 43 [] [edited; unlinked]; + let check_notes db = + check_eq (title db edited) "See Project after approval"; + check_eq (title db unlinked) "Read the next draft"; + check_eq (Graph_read.ref_eids db 22 "block/refs") []; + check (Graph_read.recycled db 21) in + check_notes (Runtime.db runtime); + let reopened = Runtime.create path 43 conn Runtime.default_options in + check_notes (Runtime.db reopened); + let pending = List.hd (Runtime.pending_operations reopened) in + check_eq pending.base_t 43; + let action, tx = match Runtime.prepare_sync reopened pending with + | Ok payload -> payload | Error message -> fail message in + check_eq action "delete-page"; + let journal = match Journal_sync.decode (Json.to_string (`Assoc [ + "type", `String "tx/batch/ok"; "t-before", `Int 43; "t", `Int 44; + "txs", `List [`Assoc ["t", `Int 44; "tx-id", `String pending.operation_id; "tx", `String tx]]])) with + | Ok journal -> journal | Error message -> fail message in + let applied = match Journal_sync.apply (fun text -> Ok text) conn 43 journal with + | Ok applied -> applied | Error message -> fail message in + check_notes (Ds.conn_db conn); + Runtime.rebase reopened 44 applied.operation_ids applied.changed_uuids; + check_eq (Runtime.pending_operations reopened) []) + let confirmation_uses_journal_identity_and_keeps_server_corrections () = List.iter (fun remote -> with_runtime (fun path conn current -> @@ -2009,6 +2062,8 @@ let cases = cursor_advance_rebases_offline_edits_and_their_structural_dependencies; case "recorded deletions replay after remote progress" recorded_deletions_replay_after_remote_progress; + case "page deletion preserves remote referrer edits on replay and upload" + page_delete_rebases_reference_rewrites_onto_remote_notes; case "journal identity confirms server corrections" confirmation_uses_journal_identity_and_keeps_server_corrections; case "rebase replays valid applied operations and persists invalid conflicts" diff --git a/shared/test/logseq/markup_test.ml b/shared/test/logseq/markup_test.ml index 782b54aee..e54f917d6 100644 --- a/shared/test/logseq/markup_test.ml +++ b/shared/test/logseq/markup_test.ml @@ -85,6 +85,12 @@ let issue_hashes_stay_literal_even_when_matching_tags_exist () = summary "tag-13732" "13732)"] in check_eq [Markup_text source] (parse [] tags source) +let escaped_hashes_display_as_literal_text () = + let tags = [summary "weekly-tag" "Weekly"] in + check_eq [Markup_text "Draft #Weekly Review"] (parse [] tags {|Draft \#Weekly Review|}); + check_eq [Markup_emphasis ("bold", [Markup_text "#Weekly"])] (parse [] tags {|**\#Weekly**|}); + check_eq [Markup_code {|\#Weekly|}] (parse [] tags {|`\#Weekly`|}) + let stable_native_json_contract () = check_eq (Yojson.Basic.from_string @@ -236,6 +242,7 @@ let cases = external_links_keep_hashtags_and_references_as_label_text; case "issue hashes stay literal even when matching tags exist" issue_hashes_stay_literal_even_when_matching_tags_exist; + case "escaped hashes display without becoming tags" escaped_hashes_display_as_literal_text; case "external link protocols preserve source separators" external_link_protocols_preserve_source_separators; case "stable native json contract" stable_native_json_contract; diff --git a/shared/test/logseq/search_index_test.ml b/shared/test/logseq/search_index_test.ml index 9367c30c9..04948d957 100644 --- a/shared/test/logseq/search_index_test.ml +++ b/shared/test/logseq/search_index_test.ml @@ -385,6 +385,27 @@ let namespace_search_includes_parent_titles_and_tags () = with_index (fun index check_eq ~msg:"restoring a namespace restores its search entries" (matching_child moved "Renamed Child") (Some moved_hit)) +let qualified_search_respects_the_requested_namespace () = with_index (fun index -> + let db = Ds.conn_db (seeded_conn ()) in + Search.search_upsert index.path [ + "other-child", "Other Page/Child", "other-child"; + "parent-grandchild", "Parent Page/Child Page/Grandchild", "parent-grandchild"; + "visible-child", "Plans/Parent Page/Child Page", "visible-child"; + "leaf-only", "Child Page", "leaf-only"; + "block-leaf", "Child Page discussion", page_uuid; + "block-path", "Follow Parent/Child for details", page_uuid; + "short-path", "父计划/孩子页", "short-path"; + ]; + let ids ~offset ~limit query = + let hits, more = Search.search_hits_page ~offset ~limit index db query in + List.map (fun (hit : Search.indexed_search_hit) -> hit.uuid) hits, more in + check_eq (ids ~offset:0 ~limit:1 "Parent/Child") (["visible-child"], true); + check_eq (ids ~offset:1 ~limit:1 "Parent/Child") (["block-path"], false); + check_eq (ids ~offset:2 ~limit:1 "Parent/Child") ([], false); + check_eq (ids ~offset:0 ~limit:20 " pArEnT / ChIlD ") (["visible-child"], false); + check_eq (ids ~offset:0 ~limit:20 "Plans/Child") ([], false); + check_eq (ids ~offset:0 ~limit:20 "父/孩子") (["short-path"], false)) + let page_title_matches_joins_sparse_pages_and_dynamic_journals () = let conn = Ds.create_conn ~schema () in check_eq (Search.page_title_matches ~limit:12 (Ds.conn_db conn) "needle") []; @@ -416,6 +437,8 @@ let cases = [ case "namespace search matches parent titles and returns ancestors and tags" namespace_search_includes_parent_titles_and_tags; + case "qualified search matches the requested parent and leaf before paging" + qualified_search_respects_the_requested_namespace; case "page completion joins sparse pages and dynamic journals" page_title_matches_joins_sparse_pages_and_dynamic_journals; case "graph search preserves FTS matches for long queries" graph_search_preserves_fts_matches_for_long_queries;