Skip to content

Commit fccdac6

Browse files
committed
Merge pull request: Extract autocomplete filter logic to NodeSearchService (#204)
2 parents 9a3dc98 + 66e9f22 commit fccdac6

4 files changed

Lines changed: 555 additions & 44 deletions

File tree

‎packages/core/src/services/node_service_container_test.rs‎

Lines changed: 58 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,10 @@ mod tests {
3232
}
3333

3434
/// Helper to check if a node is marked as stale in the database
35-
async fn is_node_stale(db: &DatabaseService, node_id: &str) -> Result<bool, Box<dyn std::error::Error>> {
35+
async fn is_node_stale(
36+
db: &DatabaseService,
37+
node_id: &str,
38+
) -> Result<bool, Box<dyn std::error::Error>> {
3639
let conn = db.connect_with_timeout().await?;
3740
let mut stmt = conn
3841
.prepare("SELECT embedding_stale FROM nodes WHERE id = ?")
@@ -48,7 +51,10 @@ mod tests {
4851
}
4952

5053
/// Helper to mark a node as not stale (simulating successful embedding)
51-
async fn mark_not_stale(db: &DatabaseService, node_id: &str) -> Result<(), Box<dyn std::error::Error>> {
54+
async fn mark_not_stale(
55+
db: &DatabaseService,
56+
node_id: &str,
57+
) -> Result<(), Box<dyn std::error::Error>> {
5258
let conn = db.connect_with_timeout().await?;
5359
conn.execute(
5460
"UPDATE nodes SET embedding_stale = FALSE WHERE id = ?",
@@ -63,22 +69,31 @@ mod tests {
6369
let (service, db, _temp) = create_test_services().await;
6470

6571
// Create a container node (no container_node_id = root level)
66-
let container_node = Node::new("text".to_string(), "Container content".to_string(), None, json!({}));
72+
let container_node = Node::new(
73+
"text".to_string(),
74+
"Container content".to_string(),
75+
None,
76+
json!({}),
77+
);
6778
let container_id = container_node.id.clone();
6879

6980
service.create_node(container_node).await.unwrap();
7081

7182
// Verify container node is marked as stale
7283
let is_stale = is_node_stale(&db, &container_id).await.unwrap();
73-
assert!(is_stale, "Container node should be marked as stale on creation");
84+
assert!(
85+
is_stale,
86+
"Container node should be marked as stale on creation"
87+
);
7488
}
7589

7690
#[tokio::test]
7791
async fn test_child_node_not_created_as_stale() {
7892
let (service, db, _temp) = create_test_services().await;
7993

8094
// Create a container node first
81-
let container_node = Node::new("text".to_string(), "Container".to_string(), None, json!({}));
95+
let container_node =
96+
Node::new("text".to_string(), "Container".to_string(), None, json!({}));
8297
let container_id = container_node.id.clone();
8398
service.create_node(container_node).await.unwrap();
8499

@@ -96,15 +111,23 @@ mod tests {
96111

97112
// Verify child node is NOT marked as stale (only containers need embeddings)
98113
let is_stale = is_node_stale(&db, &child_id).await.unwrap();
99-
assert!(!is_stale, "Child node should NOT be marked as stale on creation");
114+
assert!(
115+
!is_stale,
116+
"Child node should NOT be marked as stale on creation"
117+
);
100118
}
101119

102120
#[tokio::test]
103121
async fn test_container_content_update_marks_stale() {
104122
let (service, db, _temp) = create_test_services().await;
105123

106124
// Create container and mark it as not stale (simulate existing embedding)
107-
let container_node = Node::new("text".to_string(), "Original content".to_string(), None, json!({}));
125+
let container_node = Node::new(
126+
"text".to_string(),
127+
"Original content".to_string(),
128+
None,
129+
json!({}),
130+
);
108131
let container_id = container_node.id.clone();
109132
service.create_node(container_node).await.unwrap();
110133
mark_not_stale(&db, &container_id).await.unwrap();
@@ -118,15 +141,19 @@ mod tests {
118141

119142
// Verify container is now marked as stale
120143
let is_stale = is_node_stale(&db, &container_id).await.unwrap();
121-
assert!(is_stale, "Container should be marked as stale after content update");
144+
assert!(
145+
is_stale,
146+
"Container should be marked as stale after content update"
147+
);
122148
}
123149

124150
#[tokio::test]
125151
async fn test_child_content_update_marks_parent_stale() {
126152
let (service, db, _temp) = create_test_services().await;
127153

128154
// Create container
129-
let container_node = Node::new("text".to_string(), "Container".to_string(), None, json!({}));
155+
let container_node =
156+
Node::new("text".to_string(), "Container".to_string(), None, json!({}));
130157
let container_id = container_node.id.clone();
131158
service.create_node(container_node).await.unwrap();
132159
mark_not_stale(&db, &container_id).await.unwrap();
@@ -162,12 +189,22 @@ mod tests {
162189
let (service, db, _temp) = create_test_services().await;
163190

164191
// Create two container nodes
165-
let container1 = Node::new("text".to_string(), "Container 1".to_string(), None, json!({}));
192+
let container1 = Node::new(
193+
"text".to_string(),
194+
"Container 1".to_string(),
195+
None,
196+
json!({}),
197+
);
166198
let container1_id = container1.id.clone();
167199
service.create_node(container1).await.unwrap();
168200
mark_not_stale(&db, &container1_id).await.unwrap();
169201

170-
let container2 = Node::new("text".to_string(), "Container 2".to_string(), None, json!({}));
202+
let container2 = Node::new(
203+
"text".to_string(),
204+
"Container 2".to_string(),
205+
None,
206+
json!({}),
207+
);
171208
let container2_id = container2.id.clone();
172209
service.create_node(container2).await.unwrap();
173210
mark_not_stale(&db, &container2_id).await.unwrap();
@@ -211,7 +248,8 @@ mod tests {
211248
let (service, db, _temp) = create_test_services().await;
212249

213250
// Create container
214-
let container_node = Node::new("text".to_string(), "Container".to_string(), None, json!({}));
251+
let container_node =
252+
Node::new("text".to_string(), "Container".to_string(), None, json!({}));
215253
let container_id = container_node.id.clone();
216254
service.create_node(container_node).await.unwrap();
217255
mark_not_stale(&db, &container_id).await.unwrap();
@@ -248,7 +286,12 @@ mod tests {
248286

249287
// Create a "task" node at root level (container_node_id = None)
250288
// This tests that container detection uses NULL check, not node_type == 'topic'
251-
let task_container = Node::new("task".to_string(), "Task as container".to_string(), None, json!({}));
289+
let task_container = Node::new(
290+
"task".to_string(),
291+
"Task as container".to_string(),
292+
None,
293+
json!({}),
294+
);
252295
let task_id = task_container.id.clone();
253296
service.create_node(task_container).await.unwrap();
254297

@@ -282,7 +325,8 @@ mod tests {
282325
let (service, db, _temp) = create_test_services().await;
283326

284327
// Create container
285-
let container_node = Node::new("text".to_string(), "Container".to_string(), None, json!({}));
328+
let container_node =
329+
Node::new("text".to_string(), "Container".to_string(), None, json!({}));
286330
let container_id = container_node.id.clone();
287331
service.create_node(container_node).await.unwrap();
288332
mark_not_stale(&db, &container_id).await.unwrap();

‎packages/desktop-app/src/lib/design/components/base-node.svelte‎

Lines changed: 4 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
import { positionCursor } from '$lib/actions/position-cursor';
4747
import { createMockElementForView, findCharacterFromClickFast } from './cursor-positioning';
4848
import { mapViewPositionToEditPosition } from '$lib/utils/view-edit-mapper';
49+
import { NodeSearchService } from '$lib/services/node-search-service';
4950
5051
// Props (Svelte 5 runes syntax) - nodeReferenceService removed
5152
let {
@@ -213,36 +214,9 @@
213214
// Get all nodes from the node manager
214215
const allNodes = Array.from(services.nodeManager.nodes.values());
215216
216-
// Filter nodes based on query
217-
// Show all non-text nodes (Tasks, Persons, etc.) + container text nodes only
218-
// Exclude date nodes
219-
const filtered = allNodes
220-
.filter((node) => {
221-
// Exclude date nodes
222-
if (node.nodeType === 'date') {
223-
return false;
224-
}
225-
226-
// Match query in title or content
227-
const title = node.content.split('\n')[0] || '';
228-
const matchesQuery =
229-
title.toLowerCase().includes(query.toLowerCase()) ||
230-
node.content.toLowerCase().includes(query.toLowerCase());
231-
232-
if (!matchesQuery) {
233-
return false;
234-
}
235-
236-
// Show non-text nodes regardless of hierarchy
237-
if (node.nodeType !== 'text') {
238-
return true;
239-
}
240-
241-
// For text nodes, only show container nodes
242-
const isContainer = node.containerNodeId === null;
243-
return isContainer;
244-
})
245-
.slice(0, 10); // Limit to 10 results
217+
// Filter nodes using NodeSearchService
218+
// Rules: Exclude dates, match query, show all non-text + container text only
219+
const filtered = NodeSearchService.filterMentionableNodes(allNodes, query).slice(0, 10); // Limit to 10 results
246220
247221
// Convert to NodeResult format
248222
autocompleteResults = filtered.map((node) => ({
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
/**
2+
* Node Search Service
3+
*
4+
* Provides filtering and search functionality for nodes, specifically
5+
* for @mention autocomplete and node discovery features.
6+
*
7+
* Extracted from base-node.svelte to provide:
8+
* - Testable, reusable search logic
9+
* - Centralized filter rules
10+
* - Easy extension for new features (e.g., date shortcuts)
11+
*/
12+
13+
import type { Node } from '$lib/types/node';
14+
15+
/**
16+
* Options for filtering mentionable nodes
17+
*/
18+
export interface FilterMentionableNodesOptions {
19+
/**
20+
* Node types to exclude from results
21+
* @default ['date'] - Date nodes are excluded by default (accessible via date shortcuts)
22+
*/
23+
excludeNodeTypes?: string[];
24+
}
25+
26+
/**
27+
* NodeSearchService
28+
*
29+
* Static service class providing node filtering and search functionality.
30+
*/
31+
export class NodeSearchService {
32+
/**
33+
* Filter nodes for @mention autocomplete
34+
*
35+
* Filtering rules:
36+
* 1. Exclude date nodes (accessible via date shortcuts - Issue #201)
37+
* 2. Match query in title/content (case-insensitive)
38+
* 3. Include ALL non-text nodes regardless of hierarchy
39+
* 4. Include ONLY container text nodes (top-level)
40+
*
41+
* @param nodes - Array of nodes to filter
42+
* @param query - Search query string
43+
* @param options - Filtering options
44+
* @returns Filtered array of mentionable nodes
45+
*
46+
* @example
47+
* ```typescript
48+
* const nodes = Array.from(nodeManager.nodes.values());
49+
* const results = NodeSearchService.filterMentionableNodes(nodes, 'my search');
50+
* ```
51+
*/
52+
static filterMentionableNodes(
53+
nodes: Node[],
54+
query: string,
55+
options: FilterMentionableNodesOptions = {}
56+
): Node[] {
57+
const excludeTypes = options.excludeNodeTypes || ['date'];
58+
59+
return nodes
60+
.filter((node) => !excludeTypes.includes(node.nodeType))
61+
.filter((node) => this.matchesQuery(node, query))
62+
.filter((node) => this.isMentionable(node));
63+
}
64+
65+
/**
66+
* Check if a node matches the search query
67+
*
68+
* Searches both the first line (title) and full content of the node.
69+
* Case-insensitive matching.
70+
*
71+
* @param node - Node to check
72+
* @param query - Search query string
73+
* @returns True if node matches query
74+
*
75+
* @private
76+
*/
77+
private static matchesQuery(node: Node, query: string): boolean {
78+
// Extract first line as title
79+
const title = node.content.split('\n')[0] || '';
80+
81+
// Case-insensitive search in title and content
82+
const lowerQuery = query.toLowerCase();
83+
return (
84+
title.toLowerCase().includes(lowerQuery) || node.content.toLowerCase().includes(lowerQuery)
85+
);
86+
}
87+
88+
/**
89+
* Check if a node is mentionable in autocomplete
90+
*
91+
* Rules:
92+
* - Non-text nodes (tasks, persons, etc.): Always mentionable
93+
* - Text nodes: Only containers (top-level, not nested content)
94+
*
95+
* Rationale: Text node children are part of their parent's content,
96+
* so we only show the container nodes to avoid duplication.
97+
*
98+
* @param node - Node to check
99+
* @returns True if node can be mentioned
100+
*
101+
* @private
102+
*/
103+
private static isMentionable(node: Node): boolean {
104+
// Non-text nodes: always mentionable
105+
if (node.nodeType !== 'text') {
106+
return true;
107+
}
108+
109+
// Text nodes: only containers (containerNodeId === null)
110+
return node.containerNodeId === null;
111+
}
112+
}

0 commit comments

Comments
 (0)