feat(app): quick switcher also finds pages by block content

BlockHit carries the page id so a hit opens its page (journals included).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-26 04:02:21 +01:00
1 parent a6d566ff6f
commit b44cbee038
9 files changed
+204 -30

No files matched your search

+6 -2
View File
@@ -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;
}
+12 -4
View File
@@ -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<dynamic>;
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);
}
+117 -19
View File
@@ -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<void> showQuickSwitcher(BuildContext context) => showDialog<void>(
context: context,
barrierColor: Colors.black.withAlpha(0x33),
@@ -23,6 +24,9 @@ class QuickSwitcher extends StatefulWidget {
class _QuickSwitcherState extends State<QuickSwitcher> {
final _text = TextEditingController();
List<TitleHit> _hits = const [];
/// Blocks containing the query (pages already listed by title are not repeated).
List<BlockHit> _blocks = const [];
int _selected = 0;
int _seq = 0;
@@ -44,15 +48,31 @@ class _QuickSwitcherState extends State<QuickSwitcher> {
_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<void> _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 <BlockHit>[])
: backend.searchBlocks(q, limit: 30),
]);
if (!mounted || seq != _seq) return;
final hits = results[0] as List<TitleHit>;
final titled = {for (final h in hits) h.pageId};
final seen = <String>{};
final blocks = [
for (final b in results[1] as List<BlockHit>)
// 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<QuickSwitcher> {
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<QuickSwitcher> {
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<QuickSwitcher> {
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 = <TextSpan>[];
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,
);
}
}
+41
View File
@@ -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);
});
}
+15 -2
View File
@@ -291,8 +291,21 @@ class MemoryBackend implements GraphBackend {
}
@override
Future<List<BlockHit>> searchBlocks(String query, {int limit = 20}) async =>
[];
Future<List<BlockHit>> 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;