diff --git a/app/lib/src/rust/api/dto.dart b/app/lib/src/rust/api/dto.dart index b081b3d..b8a7f2d 100644 --- a/app/lib/src/rust/api/dto.dart +++ b/app/lib/src/rust/api/dto.dart @@ -110,20 +110,23 @@ class BlockDto { hasChildren == other.hasChildren; } -/// `((` autocomplete hit. +/// A block matching a search (`((` autocomplete, quick switcher content results). class BlockHit { final String id; final String content; + final String pageId; final String pageTitle; const BlockHit({ required this.id, required this.content, + required this.pageId, required this.pageTitle, }); @override - int get hashCode => id.hashCode ^ content.hashCode ^ pageTitle.hashCode; + int get hashCode => + id.hashCode ^ content.hashCode ^ pageId.hashCode ^ pageTitle.hashCode; @override bool operator ==(Object other) => @@ -132,6 +135,7 @@ class BlockHit { runtimeType == other.runtimeType && id == other.id && content == other.content && + pageId == other.pageId && pageTitle == other.pageTitle; } diff --git a/app/lib/src/rust/frb_generated.dart b/app/lib/src/rust/frb_generated.dart index 218ef9e..bea5243 100644 --- a/app/lib/src/rust/frb_generated.dart +++ b/app/lib/src/rust/frb_generated.dart @@ -2950,12 +2950,13 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { BlockHit dco_decode_block_hit(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs final arr = raw as List; - if (arr.length != 3) - throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); + if (arr.length != 4) + throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); return BlockHit( id: dco_decode_String(arr[0]), content: dco_decode_String(arr[1]), - pageTitle: dco_decode_String(arr[2]), + pageId: dco_decode_String(arr[2]), + pageTitle: dco_decode_String(arr[3]), ); } @@ -3644,8 +3645,14 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { // Codec=Sse (Serialization based), see doc to use other codecs var var_id = sse_decode_String(deserializer); var var_content = sse_decode_String(deserializer); + var var_pageId = sse_decode_String(deserializer); var var_pageTitle = sse_decode_String(deserializer); - return BlockHit(id: var_id, content: var_content, pageTitle: var_pageTitle); + return BlockHit( + id: var_id, + content: var_content, + pageId: var_pageId, + pageTitle: var_pageTitle, + ); } @protected @@ -4461,6 +4468,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { // Codec=Sse (Serialization based), see doc to use other codecs sse_encode_String(self.id, serializer); sse_encode_String(self.content, serializer); + sse_encode_String(self.pageId, serializer); sse_encode_String(self.pageTitle, serializer); } diff --git a/app/lib/src/views/quick_switcher.dart b/app/lib/src/views/quick_switcher.dart index 7d0a54b..2f93f14 100644 --- a/app/lib/src/views/quick_switcher.dart +++ b/app/lib/src/views/quick_switcher.dart @@ -5,7 +5,8 @@ import '../backend/graph_backend.dart'; import '../state/app_state.dart'; import '../theme/theme.dart'; -/// Ctrl+K: jump to a page by title or alias, or create it. +/// Ctrl+K: jump to a page by title or alias, to a page whose blocks contain the text, or +/// create it. Future showQuickSwitcher(BuildContext context) => showDialog( context: context, barrierColor: Colors.black.withAlpha(0x33), @@ -23,6 +24,9 @@ class QuickSwitcher extends StatefulWidget { class _QuickSwitcherState extends State { final _text = TextEditingController(); List _hits = const []; + + /// Blocks containing the query (pages already listed by title are not repeated). + List _blocks = const []; int _selected = 0; int _seq = 0; @@ -44,15 +48,31 @@ class _QuickSwitcherState extends State { _query.isNotEmpty && !_hits.any((h) => h.title.toLowerCase() == _query.toLowerCase()); - int get _count => _hits.length + (_offerCreate ? 1 : 0); + // Rows: title hits, then block hits, then "Create page". + int get _count => _hits.length + _blocks.length + (_offerCreate ? 1 : 0); Future _search(String q) async { final seq = ++_seq; - final hits = await AppScope.read(context).backend - .searchTitles(q, limit: 12); + final backend = AppScope.read(context).backend; + final results = await Future.wait([ + backend.searchTitles(q, limit: 12), + // Content search starts at two characters: one matches nearly every block. + q.trim().length < 2 + ? Future.value(const []) + : backend.searchBlocks(q, limit: 30), + ]); if (!mounted || seq != _seq) return; + final hits = results[0] as List; + final titled = {for (final h in hits) h.pageId}; + final seen = {}; + final blocks = [ + for (final b in results[1] as List) + // One row per page, the first (most recent) matching block. + if (!titled.contains(b.pageId) && seen.add(b.pageId)) b, + ].take(12).toList(); setState(() { _hits = hits; + _blocks = blocks; _selected = 0; }); } @@ -65,6 +85,8 @@ class _QuickSwitcherState extends State { final AppRoute route; if (i < _hits.length) { route = PageTarget(id: _hits[i].pageId); + } else if (i < _hits.length + _blocks.length) { + route = PageTarget(id: _blocks[i - _hits.length].pageId); } else if (query.isNotEmpty) { route = PageTarget(title: query); } else { @@ -139,20 +161,40 @@ class _QuickSwitcherState extends State { shrinkWrap: true, padding: const EdgeInsets.all(6), children: [ - for (var i = 0; i < _count; i++) + for (var i = 0; i < _hits.length; i++) _Item( selected: i == _selected, onTap: () => _open(i), onMiddle: () => _open(i, newTab: true), - icon: i < _hits.length - ? Icons.description_outlined - : Icons.add_rounded, - title: i < _hits.length - ? _hits[i].title - : 'Create page “$_query”', - detail: i < _hits.length && _hits[i].isAlias - ? 'alias' - : null, + icon: Icons.description_outlined, + title: _hits[i].title, + detail: _hits[i].isAlias ? 'alias' : null, + ), + if (_blocks.isNotEmpty) + Padding( + padding: const EdgeInsets.fromLTRB(12, 10, 12, 4), + child: Text( + 'IN NOTES', + style: Theme.of(context).textTheme.labelSmall, + ), + ), + for (var j = 0; j < _blocks.length; j++) + _Item( + key: ValueKey('block-hit-${_blocks[j].id}'), + selected: _hits.length + j == _selected, + onTap: () => _open(_hits.length + j), + onMiddle: () => _open(_hits.length + j, newTab: true), + icon: Icons.notes_rounded, + title: _blocks[j].pageTitle, + snippet: _Snippet(_blocks[j].content, _query), + ), + if (_offerCreate) + _Item( + selected: _count - 1 == _selected, + onTap: () => _open(_count - 1), + onMiddle: () => _open(_count - 1, newTab: true), + icon: Icons.add_rounded, + title: 'Create page “$_query”', ), ], ), @@ -167,12 +209,14 @@ class _QuickSwitcherState extends State { class _Item extends StatelessWidget { const _Item({ + super.key, required this.selected, required this.onTap, required this.icon, required this.title, required this.onMiddle, this.detail, + this.snippet, }); final bool selected; final VoidCallback onTap; @@ -181,6 +225,9 @@ class _Item extends StatelessWidget { final String title; final String? detail; + /// Matching text shown under the title (content results). + final Widget? snippet; + @override Widget build(BuildContext context) { final colors = context.colors; @@ -204,11 +251,20 @@ class _Item extends StatelessWidget { ), const SizedBox(width: 10), Expanded( - child: Text( - title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(fontSize: 14, color: colors.ink), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14, color: colors.ink), + ), + if (snippet != null) ...[ + const SizedBox(height: 2), + snippet!, + ], + ], ), ), if (detail != null) @@ -223,3 +279,45 @@ class _Item extends StatelessWidget { ); } } + +/// One line of a block around the first match of `query`, the match highlighted. +class _Snippet extends StatelessWidget { + const _Snippet(this.content, this.query); + final String content; + final String query; + + @override + Widget build(BuildContext context) { + final colors = context.colors; + final text = content.replaceAll(RegExp(r'\s+'), ' ').trim(); + final at = text.toLowerCase().indexOf(query.toLowerCase()); + // Start a little before the match so it stays visible on one line. + final from = at > 40 ? at - 30 : 0; + final shown = (from > 0 ? '…' : '') + text.substring(from); + final base = TextStyle(fontSize: 12.5, color: colors.muted); + final spans = []; + final m = at < 0 ? -1 : at - from + (from > 0 ? 1 : 0); + if (m < 0 || query.isEmpty) { + spans.add(TextSpan(text: shown)); + } else { + spans + ..add(TextSpan(text: shown.substring(0, m))) + ..add( + TextSpan( + text: shown.substring(m, m + query.length), + style: TextStyle( + color: colors.ink, + fontWeight: FontWeight.w600, + backgroundColor: colors.highlight, + ), + ), + ) + ..add(TextSpan(text: shown.substring(m + query.length))); + } + return Text.rich( + TextSpan(style: base, children: spans), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ); + } +} diff --git a/app/test/quick_switcher_test.dart b/app/test/quick_switcher_test.dart new file mode 100644 index 0000000..26a94c9 --- /dev/null +++ b/app/test/quick_switcher_test.dart @@ -0,0 +1,41 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:synapse/src/state/app_state.dart'; +import 'package:synapse/src/theme/theme.dart'; +import 'package:synapse/src/views/quick_switcher.dart'; + +import 'support/memory_backend.dart'; + +void main() { + testWidgets('the quick switcher finds pages by their content', ( + tester, + ) async { + final b = MemoryBackend(); + final recipes = b.createPage('Recipes'); + b.seed(recipes.id, [(0, 'Tortilla de patatas con cebolla')]); + final soups = b.createPage('Soups'); + b.seed(soups.id, [(0, 'Gazpacho'), (0, 'Salmorejo con cebolla')]); + final cebolla = b.createPage('Cebolla'); + b.seed(cebolla.id, [(0, 'cebolla morada')]); + final app = AppState(b); + await tester.pumpWidget( + AppScope( + state: app, + child: MaterialApp( + theme: buildTheme(Brightness.light), + home: const Scaffold(body: QuickSwitcher()), + ), + ), + ); + await tester.enterText(find.byType(TextField), 'cebolla'); + await tester.pumpAndSettle(); + // The title hit first, then one row per other page whose blocks match. + expect(find.text('IN NOTES'), findsOneWidget); + expect(find.text('Recipes'), findsOneWidget); + expect(find.text('Soups'), findsOneWidget); + expect(find.text('Cebolla'), findsOneWidget); + await tester.tap(find.text('Soups')); + await tester.pumpAndSettle(); + expect((app.route as PageTarget).id, soups.id); + }); +} diff --git a/app/test/support/memory_backend.dart b/app/test/support/memory_backend.dart index 2baa0c4..e940ba2 100644 --- a/app/test/support/memory_backend.dart +++ b/app/test/support/memory_backend.dart @@ -291,8 +291,21 @@ class MemoryBackend implements GraphBackend { } @override - Future> searchBlocks(String query, {int limit = 20}) async => - []; + Future> searchBlocks(String query, {int limit = 20}) async { + final q = query.trim().toLowerCase(); + if (q.isEmpty) return []; + return [ + for (final e in outlines.entries) + for (final n in e.value) + if (n.content.toLowerCase().contains(q)) + BlockHit( + id: n.id, + content: n.content, + pageId: e.key, + pageTitle: pages[e.key]?.title ?? '', + ), + ].take(limit).toList(); + } @override String? assetPath(String hash) => null; diff --git a/crates/synapse-ffi/src/api/dto.rs b/crates/synapse-ffi/src/api/dto.rs index 130d841..4732f3e 100644 --- a/crates/synapse-ffi/src/api/dto.rs +++ b/crates/synapse-ffi/src/api/dto.rs @@ -187,11 +187,12 @@ pub struct TitleHit { pub is_alias: bool, } -/// `((` autocomplete hit. +/// A block matching a search (`((` autocomplete, quick switcher content results). #[derive(Debug, Clone, PartialEq)] pub struct BlockHit { pub id: String, pub content: String, + pub page_id: String, pub page_title: String, } diff --git a/crates/synapse-ffi/src/api/search.rs b/crates/synapse-ffi/src/api/search.rs index c3a90a2..3bf8d34 100644 --- a/crates/synapse-ffi/src/api/search.rs +++ b/crates/synapse-ffi/src/api/search.rs @@ -79,14 +79,15 @@ impl SynapseGraph { let g = self.lock(); // Read-only stopgap over the core tables until synapse-search lands. let mut st = g.conn().prepare_cached( - "SELECT b.id, b.content, p.title FROM blocks b JOIN pages p ON p.id = b.page_id + "SELECT b.id, b.content, p.id, p.title FROM blocks b JOIN pages p ON p.id = b.page_id WHERE b.content LIKE ?1 ESCAPE '\\' ORDER BY b.updated_at DESC LIMIT ?2", )?; let rows = st.query_map((pattern, limit), |r| { Ok(BlockHit { id: r.get(0)?, content: r.get(1)?, - page_title: r.get(2)?, + page_id: r.get(2)?, + page_title: r.get(3)?, }) })?; Ok(rows.collect::>()?) diff --git a/crates/synapse-ffi/src/frb_generated.rs b/crates/synapse-ffi/src/frb_generated.rs index 83b051c..d9ecec6 100644 --- a/crates/synapse-ffi/src/frb_generated.rs +++ b/crates/synapse-ffi/src/frb_generated.rs @@ -3568,10 +3568,12 @@ impl SseDecode for crate::api::dto::BlockHit { fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut var_id = ::sse_decode(deserializer); let mut var_content = ::sse_decode(deserializer); + let mut var_pageId = ::sse_decode(deserializer); let mut var_pageTitle = ::sse_decode(deserializer); return crate::api::dto::BlockHit { id: var_id, content: var_content, + page_id: var_pageId, page_title: var_pageTitle, }; } @@ -4664,6 +4666,7 @@ impl flutter_rust_bridge::IntoDart for crate::api::dto::BlockHit { [ self.id.into_into_dart().into_dart(), self.content.into_into_dart().into_dart(), + self.page_id.into_into_dart().into_dart(), self.page_title.into_into_dart().into_dart(), ] .into_dart() @@ -5183,6 +5186,7 @@ impl SseEncode for crate::api::dto::BlockHit { fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { ::sse_encode(self.id, serializer); ::sse_encode(self.content, serializer); + ::sse_encode(self.page_id, serializer); ::sse_encode(self.page_title, serializer); } } diff --git a/docs/app.md b/docs/app.md index 78409e6..3e7168d 100644 --- a/docs/app.md +++ b/docs/app.md @@ -81,6 +81,10 @@ Commit the regenerated `crates/synapse-ffi/src/frb_generated.rs` and `app/lib/sr journals, Ctrl+Shift+G graph, Ctrl+Shift+T timeline, Ctrl+\ sidebar, Ctrl+Shift+\ graph sidebar, Ctrl+, settings, Alt+←/→ back/forward, Ctrl+T new tab, Ctrl+W close tab, Ctrl+Tab / Ctrl+Shift+Tab next/previous tab. +- Quick switcher (Ctrl+K): page titles and aliases first, then "In notes": pages whose blocks + contain the text (from two characters; one row per page with the first matching block as + a highlighted snippet), then "Create page". Content search is the FFI's `search_blocks` + (SQL `LIKE`, case-insensitive for ASCII only) until synapse-search's full-text index is wired. ## Tabs - `AppState` holds a list of `AppTab`s; each has its own route and back/forward history, and