From 1e32cf0df3279e7337d6df294b0bcdc8d9c2de06 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 03:37:39 +0100 Subject: [PATCH 1/2] feat(app): browser-like tabs with per-tab history and persistence Co-Authored-By: Claude Opus 5.5 --- app/lib/src/editor/block_row.dart | 8 +- app/lib/src/editor/markdown.dart | 22 ++- app/lib/src/state/app_state.dart | 266 ++++++++++++++++++++++++-- app/lib/src/state/keymap.dart | 8 + app/lib/src/views/quick_switcher.dart | 18 +- app/lib/src/views/shell.dart | 30 ++- app/lib/src/views/tab_strip.dart | 252 ++++++++++++++++++++++++ app/lib/src/widgets/common.dart | 6 +- 8 files changed, 577 insertions(+), 33 deletions(-) create mode 100644 app/lib/src/views/tab_strip.dart diff --git a/app/lib/src/editor/block_row.dart b/app/lib/src/editor/block_row.dart index fe37180..8d8e7e8 100644 --- a/app/lib/src/editor/block_row.dart +++ b/app/lib/src/editor/block_row.dart @@ -317,8 +317,10 @@ class _BlockViewState extends State { base: blockTextStyle(context), refs: app.refs, assetPath: app.backend.assetPath, - onPage: app.openTitle, - onBlockRef: (r) => app.openId(r.pageId), + onPage: (t) => app.navigate(PageTarget(title: t)), + onBlockRef: (r) => app.navigate(PageTarget(id: r.pageId)), + onPageNewTab: app.openTitleInNewTab, + onBlockRefNewTab: (r) => app.openIdInNewTab(r.pageId), onUrl: openUrl, onToggleTodo: () => widget.controller.cycleTodo(widget.node), maxWidth: width, @@ -708,6 +710,8 @@ class _BlockEditorState extends State { return KeyEventResult.handled; } if (key == LogicalKeyboardKey.tab) { + // Ctrl+Tab switches app tabs (handled by the shell shortcuts). + if (ctrl) return KeyEventResult.ignored; if (shift) { c.outdent(n, caret: caret); } else { diff --git a/app/lib/src/editor/markdown.dart b/app/lib/src/editor/markdown.dart index 9f21fff..d16f064 100644 --- a/app/lib/src/editor/markdown.dart +++ b/app/lib/src/editor/markdown.dart @@ -65,6 +65,8 @@ class RenderContext { required this.onBlockRef, required this.onUrl, this.onToggleTodo, + this.onPageNewTab, + this.onBlockRefNewTab, this.maxWidth = 600, }); @@ -76,6 +78,10 @@ class RenderContext { final void Function(BlockRefDtoLike ref) onBlockRef; final void Function(String url) onUrl; final VoidCallback? onToggleTodo; + + /// Middle-click on a page link or block ref. + final void Function(String title)? onPageNewTab; + final void Function(BlockRefDtoLike ref)? onBlockRefNewTab; final double maxWidth; } @@ -298,6 +304,9 @@ class BlockRenderer { fontWeight: FontWeight.w500, ), onTap: () => ctx.onPage(title), + onMiddle: ctx.onPageNewTab == null + ? null + : () => ctx.onPageNewTab!(title), ); i = plain = close + 2; continue; @@ -476,11 +485,18 @@ class BlockRenderer { return null; } - void _text(String t, int s0, TextStyle style, {VoidCallback? onTap}) { + void _text( + String t, + int s0, + TextStyle style, { + VoidCallback? onTap, + VoidCallback? onMiddle, + }) { if (t.isEmpty) return; TapGestureRecognizer? rec; if (onTap != null) { rec = TapGestureRecognizer()..onTap = onTap; + if (onMiddle != null) rec.onTertiaryTapUp = (_) => onMiddle(); _recognizers.add(rec); } _spans.add( @@ -513,7 +529,9 @@ class BlockRenderer { TapGestureRecognizer? rec; if (ref != null) { rec = TapGestureRecognizer() - ..onTap = () => ctx.onBlockRef(BlockRefDtoLike(ref.id, ref.pageId)); + ..onTap = (() => ctx.onBlockRef(BlockRefDtoLike(ref.id, ref.pageId))) + ..onTertiaryTapUp = (_) => + ctx.onBlockRefNewTab?.call(BlockRefDtoLike(ref.id, ref.pageId)); _recognizers.add(rec); } _spans.add( diff --git a/app/lib/src/state/app_state.dart b/app/lib/src/state/app_state.dart index de27f1a..6cf9e8a 100644 --- a/app/lib/src/state/app_state.dart +++ b/app/lib/src/state/app_state.dart @@ -1,10 +1,12 @@ import 'dart:ui' show PlatformDispatcher; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart' show HardwareKeyboard; import '../backend/graph_backend.dart'; import '../graph/network_canvas.dart'; import '../theme/theme.dart'; +import '../widgets/dates.dart'; import 'keymap.dart'; import 'settings.dart'; import 'write_queue.dart'; @@ -55,6 +57,92 @@ class PageTarget extends AppRoute { final String? title; } +/// One browser-like tab: its current route plus its own back/forward history. +class AppTab { + AppTab(this.route, {this.label}); + + AppRoute route; + final back = []; + final forward = []; + + /// Title of a page route (the route only has an id); set once the page is shown. + String? label; + + /// Stable identity for widget keys (reordering, closing). + final int uid = _nextUid++; + static int _nextUid = 0; + + String get title => switch (route) { + JournalsRoute() => 'Journals', + TimelineRoute() => 'Timeline', + AllPagesRoute() => 'All pages', + SettingsRoute() => 'Settings', + GraphRoute() => 'Graph', + PageTarget(:final title) => label ?? title ?? 'Page', + }; + + IconData get icon => switch (route) { + JournalsRoute() => Icons.calendar_today_outlined, + TimelineRoute() => Icons.timeline_rounded, + AllPagesRoute() => Icons.description_outlined, + SettingsRoute() => Icons.settings_outlined, + GraphRoute() => Icons.hub_outlined, + PageTarget() => Icons.article_outlined, + }; +} + +/// True while Ctrl (Cmd on macOS) is held: a click then opens in a new tab. +bool get newTabModifierHeld => + HardwareKeyboard.instance.isControlPressed || + HardwareKeyboard.instance.isMetaPressed; + +Map? routeToJson(AppRoute r, {String? label}) => switch (r) { + JournalsRoute() => {'t': 'journals'}, + TimelineRoute() => {'t': 'timeline'}, + AllPagesRoute() => {'t': 'all'}, + SettingsRoute() => {'t': 'settings'}, + GraphRoute() => { + 't': 'graph', + 'mode': r.mode.name, + if (r.focusId != null) 'focus': r.focusId, + }, + PageTarget() => { + 't': 'page', + 'id': ?r.id, + 'title': ?r.title, + 'label': ?label, + }, +}; + +/// Null for unknown or broken entries. +AppRoute? routeFromJson(Object? j) { + if (j is! Map) return null; + switch (j['t']) { + case 'journals': + return const JournalsRoute(); + case 'timeline': + return const TimelineRoute(); + case 'all': + return const AllPagesRoute(); + case 'settings': + return const SettingsRoute(); + case 'graph': + final mode = GraphMode.values.asNameMap()[j['mode']]; + if (mode == null) return null; + final focus = j['focus']; + return GraphRoute(mode, focusId: focus is String ? focus : null); + case 'page': + final id = j['id']; + final title = j['title']; + if (id is! String && title is! String) return null; + return PageTarget( + id: id is String ? id : null, + title: title is String ? title : null, + ); + } + return null; +} + /// App-wide state: the open graph, navigation history, recents and theme. /// /// State management is plain `ChangeNotifier`s: one for the app, one per open outline @@ -81,6 +169,7 @@ class AppState extends ChangeNotifier { if (id is String && (id == autoThemeId || resolveTheme(id) != null)) { themeId = id; } + _restoreTabs(saved['tabs']); final keys = saved['keys']; keymap = Keymap( keys is Map @@ -105,9 +194,34 @@ class AppState extends ChangeNotifier { 'theme': themeId, 'customThemes': [for (final t in customThemes) t.toJson()], 'keys': keymap.toJson(), + 'tabs': { + 'active': _active, + 'items': [ + for (final t in _tabs) routeToJson(t.route, label: t.label) as Object, + ], + }, }); } + void _restoreTabs(Object? saved) { + if (saved is! Map || saved['items'] is! List) return; + final restored = []; + for (final j in saved['items'] as List) { + final r = routeFromJson(j); + if (r == null) continue; + final label = j is Map && j['label'] is String + ? j['label'] as String + : null; + restored.add(AppTab(r, label: label)); + } + if (restored.isEmpty) return; + _tabs + ..clear() + ..addAll(restored); + final a = saved['active']; + _active = a is int && a >= 0 && a < _tabs.length ? a : 0; + } + /// A built-in or custom theme by id; null for `auto` and unknown ids. AppTheme? resolveTheme(String id) { final built = themeById(id); @@ -192,9 +306,8 @@ class AppState extends ChangeNotifier { final WriteQueue queue; final BlockRefCache refs; - AppRoute _route = const JournalsRoute(); - final _back = []; - final _forward = []; + final List _tabs = [AppTab(const JournalsRoute())]; + int _active = 0; final List recent = []; /// Node positions shared by the graph views (stable layouts across modes and filters). @@ -220,9 +333,13 @@ class AppState extends ChangeNotifier { /// Last write error, shown once by the shell. String? writeError; - AppRoute get route => _route; - bool get canGoBack => _back.isNotEmpty; - bool get canGoForward => _forward.isNotEmpty; + AppTab get tab => _tabs[_active]; + List get tabs => List.unmodifiable(_tabs); + int get activeTab => _active; + + AppRoute get route => tab.route; + bool get canGoBack => tab.back.isNotEmpty; + bool get canGoForward => tab.forward.isNotEmpty; /// A failed write leaves the optimistic UI out of sync: reload the view from the core. void _writeFailed(Object e, StackTrace st) { @@ -238,10 +355,64 @@ class AppState extends ChangeNotifier { } void go(AppRoute r) { - _back.add(_route); - if (_back.length > 100) _back.removeAt(0); - _forward.clear(); - _route = r; + final t = tab; + t.back.add(t.route); + if (t.back.length > 100) t.back.removeAt(0); + t.forward.clear(); + t.route = r; + t.label = null; + _saveSettings(); + notifyListeners(); + } + + /// Opens `r` in a new tab (after the active one), optionally keeping the current tab. + void openInNewTab(AppRoute r, {bool activate = true}) { + _tabs.insert(_active + 1, AppTab(r)); + if (activate) _active++; + _saveSettings(); + notifyListeners(); + } + + /// A plain click navigates the active tab; with Ctrl/Cmd held it opens a new tab. + void navigate(AppRoute r) => newTabModifierHeld ? openInNewTab(r) : go(r); + + void newTab() => openInNewTab(const JournalsRoute()); + + void activateTab(int i) { + if (i < 0 || i >= _tabs.length || i == _active) return; + _active = i; + _saveSettings(); + notifyListeners(); + } + + void nextTab() => activateTab((_active + 1) % _tabs.length); + void previousTab() => + activateTab((_active - 1 + _tabs.length) % _tabs.length); + + /// Closes tab `i` (default: the active one). The last tab is replaced by a Journals tab. + void closeTab([int? i]) { + final at = i ?? _active; + if (at < 0 || at >= _tabs.length) return; + _tabs.removeAt(at); + if (_tabs.isEmpty) { + _tabs.add(AppTab(const JournalsRoute())); + _active = 0; + } else if (at < _active || _active >= _tabs.length) { + _active--; + } + _active = _active.clamp(0, _tabs.length - 1); + _saveSettings(); + notifyListeners(); + } + + void moveTab(int from, int to) { + if (from < 0 || from >= _tabs.length || to < 0 || to >= _tabs.length) { + return; + } + final active = _tabs[_active]; + _tabs.insert(to, _tabs.removeAt(from)); + _active = _tabs.indexOf(active); + _saveSettings(); notifyListeners(); } @@ -254,32 +425,73 @@ class AppState extends ChangeNotifier { r is PageTarget && r.id == null && r.title!.toLowerCase() == key ? PageTarget(id: id) : r; - if (_route is PageTarget) _route = PageTarget(id: id); - for (final l in [_back, _forward]) { - for (var i = 0; i < l.length; i++) { - l[i] = fix(l[i]); + for (final t in _tabs) { + if (t.route is PageTarget) { + final r = t.route as PageTarget; + // Only the shown page of the active tab is known to be the renamed one. + if (t == tab || (r.id == null && r.title!.toLowerCase() == key)) { + t.route = PageTarget(id: id); + } + } + for (final l in [t.back, t.forward]) { + for (var i = 0; i < l.length; i++) { + l[i] = fix(l[i]); + } } } generation++; + _saveSettings(); notifyListeners(); } void back() { - if (_back.isEmpty) return; - _forward.add(_route); - _route = _back.removeLast(); + final t = tab; + if (t.back.isEmpty) return; + t.forward.add(t.route); + t.route = t.back.removeLast(); + t.label = null; + _saveSettings(); notifyListeners(); } void forward() { - if (_forward.isEmpty) return; - _back.add(_route); - _route = _forward.removeLast(); + final t = tab; + if (t.forward.isEmpty) return; + t.back.add(t.route); + t.route = t.forward.removeLast(); + t.label = null; + _saveSettings(); + notifyListeners(); + } + + /// Pages were deleted: tabs showing them step back to the last surviving entry (or + /// Journals) and the recents drop them. + void pagesDeleted(Iterable ids) { + final gone = ids.toSet(); + bool dead(AppRoute r) => r is PageTarget && gone.contains(r.id); + recent.removeWhere((p) => gone.contains(p.id)); + for (final t in _tabs) { + t.back.removeWhere(dead); + t.forward.removeWhere(dead); + if (dead(t.route)) { + t.route = t.back.isNotEmpty + ? t.back.removeLast() + : (t.forward.isNotEmpty + ? t.forward.removeLast() + : const JournalsRoute()); + t.label = null; + } + } + generation++; + _saveSettings(); notifyListeners(); } void openTitle(String title) => go(PageTarget(title: title)); void openId(String id) => go(PageTarget(id: id)); + void openTitleInNewTab(String title) => + openInNewTab(PageTarget(title: title)); + void openIdInNewTab(String id) => openInNewTab(PageTarget(id: id)); /// Called by the page view once it knows which page it shows. void pageShown(PageDto page) { @@ -288,6 +500,16 @@ class AppState extends ChangeNotifier { if (from != page.id) { queue.run(() => backend.recordVisit(from, page.id)).ignore(); } + final shown = route; + if (shown is PageTarget) { + final label = page.journalDate != null + ? longDate(page.title) + : page.title; + if (tab.label != label) { + tab.label = label; + _saveSettings(); + } + } recent.removeWhere((p) => p.id == page.id); // Hubs are folders, not pages: they never show up in recents. if (!page.isHub) { @@ -319,6 +541,10 @@ class AppState extends ChangeNotifier { } void renamed(String id, String title) { + for (final t in _tabs) { + final r = t.route; + if (r is PageTarget && r.id == id) t.label = title; + } final i = recent.indexWhere((p) => p.id == id); if (i >= 0) { recent[i] = PageBrief( diff --git a/app/lib/src/state/keymap.dart b/app/lib/src/state/keymap.dart index 004a119..d832165 100644 --- a/app/lib/src/state/keymap.dart +++ b/app/lib/src/state/keymap.dart @@ -75,6 +75,10 @@ enum AppAction { settings('Settings', false), back('Back', false), forward('Forward', false), + newTab('New tab', false), + closeTab('Close tab', false), + nextTab('Next tab', false), + previousTab('Previous tab', false), bold('Bold', true), italic('Italic', true), strike('Strikethrough', true), @@ -96,6 +100,10 @@ enum AppAction { settings => Combo(LogicalKeyboardKey.comma, ctrl: true), back => Combo(LogicalKeyboardKey.arrowLeft, alt: true), forward => Combo(LogicalKeyboardKey.arrowRight, alt: true), + newTab => Combo(LogicalKeyboardKey.keyT, ctrl: true), + closeTab => Combo(LogicalKeyboardKey.keyW, ctrl: true), + nextTab => Combo(LogicalKeyboardKey.tab, ctrl: true), + previousTab => Combo(LogicalKeyboardKey.tab, ctrl: true, shift: true), bold => Combo(LogicalKeyboardKey.keyB, ctrl: true), italic => Combo(LogicalKeyboardKey.keyI, ctrl: true), strike => Combo(LogicalKeyboardKey.keyS, ctrl: true, shift: true), diff --git a/app/lib/src/views/quick_switcher.dart b/app/lib/src/views/quick_switcher.dart index 0ab331e..7d0a54b 100644 --- a/app/lib/src/views/quick_switcher.dart +++ b/app/lib/src/views/quick_switcher.dart @@ -57,14 +57,20 @@ class _QuickSwitcherState extends State { }); } - void _open(int i) { + /// Ctrl/Cmd held (or `newTab`, for middle-click) opens the result in a new tab. + void _open(int i, {bool newTab = false}) { final app = AppScope.read(context); + final query = _query; Navigator.of(context).pop(); + final AppRoute route; if (i < _hits.length) { - app.openId(_hits[i].pageId); - } else if (_query.isNotEmpty) { - app.openTitle(_query); + route = PageTarget(id: _hits[i].pageId); + } else if (query.isNotEmpty) { + route = PageTarget(title: query); + } else { + return; } + newTab ? app.openInNewTab(route) : app.navigate(route); } KeyEventResult _key(FocusNode _, KeyEvent e) { @@ -137,6 +143,7 @@ class _QuickSwitcherState extends State { _Item( selected: i == _selected, onTap: () => _open(i), + onMiddle: () => _open(i, newTab: true), icon: i < _hits.length ? Icons.description_outlined : Icons.add_rounded, @@ -164,10 +171,12 @@ class _Item extends StatelessWidget { required this.onTap, required this.icon, required this.title, + required this.onMiddle, this.detail, }); final bool selected; final VoidCallback onTap; + final VoidCallback onMiddle; final IconData icon; final String title; final String? detail; @@ -179,6 +188,7 @@ class _Item extends StatelessWidget { cursor: SystemMouseCursors.click, child: GestureDetector( onTap: onTap, + onTertiaryTapUp: (_) => onMiddle(), child: Container( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9), decoration: BoxDecoration( diff --git a/app/lib/src/views/shell.dart b/app/lib/src/views/shell.dart index c39cf9c..7087be3 100644 --- a/app/lib/src/views/shell.dart +++ b/app/lib/src/views/shell.dart @@ -12,6 +12,7 @@ import 'hubs_tree.dart'; import 'quick_switcher.dart'; import 'graph_view.dart'; import 'settings_view.dart'; +import 'tab_strip.dart'; /// App frame: sidebar (navigation, hubs, recents), top bar (history, search, theme, /// settings) and the current view. @@ -53,6 +54,10 @@ class _ShellState extends State { AppAction.settings: () => app.go(const SettingsRoute()), AppAction.back: app.back, AppAction.forward: app.forward, + AppAction.newTab: app.newTab, + AppAction.closeTab: app.closeTab, + AppAction.nextTab: app.nextTab, + AppAction.previousTab: app.previousTab, }; return CallbackShortcuts( bindings: { @@ -94,13 +99,15 @@ class _ShellState extends State { child: Column( children: [ _TopBar( + narrow: narrow, onMenu: () => narrow ? _scaffold.currentState?.openDrawer() : setState(() => _sidebar = !_sidebar), ), + if (!narrow) const TabStrip(), Expanded( child: KeyedSubtree( - key: ValueKey((route, app.generation)), + key: ValueKey((app.tab.uid, route, app.generation)), child: switch (route) { JournalsRoute() => const JournalsView(), TimelineRoute() => const GraphView( @@ -130,8 +137,9 @@ class _ShellState extends State { } class _TopBar extends StatelessWidget { - const _TopBar({required this.onMenu}); + const _TopBar({required this.onMenu, required this.narrow}); final VoidCallback onMenu; + final bool narrow; @override Widget build(BuildContext context) { @@ -167,6 +175,7 @@ class _TopBar extends StatelessWidget { app.canGoForward ? app.forward : null, ), const Spacer(), + if (narrow) const TabCountButton(), // Phones: an icon instead of the pill keeps the bar from overflowing. if (MediaQuery.sizeOf(context).width < 480) icon( @@ -240,8 +249,14 @@ class _Sidebar extends StatelessWidget { final app = AppScope.of(context); final colors = context.colors; final route = app.route; + // Ctrl/Cmd-click opens in a new tab, middle-click always does. void go(AppRoute r) { - app.go(r); + app.navigate(r); + onNavigate(); + } + + void newTab(AppRoute r) { + app.openInNewTab(r); onNavigate(); } @@ -277,18 +292,21 @@ class _Sidebar extends StatelessWidget { label: 'Journals', selected: route is JournalsRoute, onTap: () => go(const JournalsRoute()), + onMiddle: () => newTab(const JournalsRoute()), ), _NavItem( icon: Icons.hub_outlined, label: 'Graph', selected: route is GraphRoute, onTap: () => go(const GraphRoute(GraphMode.network)), + onMiddle: () => newTab(const GraphRoute(GraphMode.network)), ), _NavItem( icon: Icons.description_outlined, label: 'All pages', selected: route is AllPagesRoute, onTap: () => go(const AllPagesRoute()), + onMiddle: () => newTab(const AllPagesRoute()), ), const SizedBox(height: 22), Expanded( @@ -312,6 +330,7 @@ class _Sidebar extends StatelessWidget { selected: route is PageTarget && route.id == p.id, dense: true, onTap: () => go(PageTarget(id: p.id)), + onMiddle: () => newTab(PageTarget(id: p.id)), ), ], ), @@ -329,12 +348,14 @@ class _NavItem extends StatefulWidget { required this.label, required this.selected, required this.onTap, + this.onMiddle, this.dense = false, }); final IconData? icon; final String label; final bool selected; final VoidCallback onTap; + final VoidCallback? onMiddle; final bool dense; @override @@ -354,6 +375,9 @@ class _NavItemState extends State<_NavItem> { onExit: (_) => setState(() => _hover = false), child: GestureDetector( onTap: widget.onTap, + onTertiaryTapUp: widget.onMiddle == null + ? null + : (_) => widget.onMiddle!(), child: Container( margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 1), padding: EdgeInsets.symmetric( diff --git a/app/lib/src/views/tab_strip.dart b/app/lib/src/views/tab_strip.dart new file mode 100644 index 0000000..5e5723f --- /dev/null +++ b/app/lib/src/views/tab_strip.dart @@ -0,0 +1,252 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +import '../state/app_state.dart'; +import '../state/keymap.dart'; +import '../theme/theme.dart'; + +const _tabWidth = 168.0; +const _stripHeight = 34.0; + +/// Browser-like tab strip: one compact item per tab, close button on hover or when active, +/// a "+" button, horizontal scrolling on overflow and drag to reorder. +class TabStrip extends StatelessWidget { + const TabStrip({super.key}); + + @override + Widget build(BuildContext context) { + final app = AppScope.of(context); + final colors = context.colors; + final tabs = app.tabs; + return Container( + key: const ValueKey('tab-strip'), + height: _stripHeight, + decoration: BoxDecoration( + color: colors.surface, + border: Border( + top: BorderSide(color: colors.line), + bottom: BorderSide(color: colors.line), + ), + ), + child: Row( + children: [ + Expanded( + child: ReorderableListView.builder( + scrollDirection: Axis.horizontal, + buildDefaultDragHandles: false, + padding: const EdgeInsets.only(left: 6, top: 4), + itemCount: tabs.length, + onReorderItem: app.moveTab, + proxyDecorator: (child, _, _) => + Material(color: Colors.transparent, child: child), + itemBuilder: (context, i) => ReorderableDragStartListener( + key: ValueKey('tab-${tabs[i].uid}'), + index: i, + child: _TabItem( + tab: tabs[i], + index: i, + active: i == app.activeTab, + ), + ), + ), + ), + IconButton( + key: const ValueKey('tab-new'), + tooltip: 'New tab (${app.keymap.of(AppAction.newTab).label})', + iconSize: 16, + visualDensity: VisualDensity.compact, + color: colors.muted, + icon: const Icon(Icons.add_rounded), + onPressed: app.newTab, + ), + ], + ), + ); + } +} + +class _TabItem extends StatefulWidget { + const _TabItem({ + required this.tab, + required this.index, + required this.active, + }); + final AppTab tab; + final int index; + final bool active; + + @override + State<_TabItem> createState() => _TabItemState(); +} + +class _TabItemState extends State<_TabItem> { + bool _hover = false; + + @override + Widget build(BuildContext context) { + final app = AppScope.read(context); + final colors = context.colors; + final active = widget.active; + return MouseRegion( + onEnter: (_) => setState(() => _hover = true), + onExit: (_) => setState(() => _hover = false), + cursor: SystemMouseCursors.click, + child: Listener( + onPointerDown: (e) { + if (e.buttons == kMiddleMouseButton) app.closeTab(widget.index); + }, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => app.activateTab(widget.index), + child: Container( + width: _tabWidth, + margin: const EdgeInsets.only(right: 2), + padding: const EdgeInsets.only(left: 10, right: 4), + decoration: BoxDecoration( + color: active + ? colors.paper + : (_hover ? colors.line.withAlpha(0x66) : null), + border: Border.all( + color: active ? colors.line : Colors.transparent, + ), + borderRadius: const BorderRadius.vertical( + top: Radius.circular(8), + ), + ), + child: Row( + children: [ + Icon( + widget.tab.icon, + size: 13, + color: active ? colors.accent : colors.faint, + ), + const SizedBox(width: 7), + Expanded( + child: Text( + widget.tab.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12.5, + fontWeight: active ? FontWeight.w600 : FontWeight.w500, + color: active ? colors.ink : colors.muted, + ), + ), + ), + SizedBox( + width: 22, + child: active || _hover + ? InkResponse( + key: ValueKey('tab-close-${widget.index}'), + radius: 11, + onTap: () => app.closeTab(widget.index), + child: Icon( + Icons.close_rounded, + size: 14, + color: colors.muted, + ), + ) + : null, + ), + ], + ), + ), + ), + ), + ); + } +} + +/// Narrow layouts: a button with the tab count that opens the tab list. +class TabCountButton extends StatelessWidget { + const TabCountButton({super.key}); + + @override + Widget build(BuildContext context) { + final app = AppScope.of(context); + final colors = context.colors; + return IconButton( + key: const ValueKey('tab-count'), + tooltip: 'Tabs', + onPressed: () => showTabsSheet(context), + icon: Container( + width: 20, + height: 20, + alignment: Alignment.center, + decoration: BoxDecoration( + border: Border.all(color: colors.muted, width: 1.5), + borderRadius: BorderRadius.circular(5), + ), + child: Text( + '${app.tabs.length}', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: colors.muted, + ), + ), + ), + ); + } +} + +Future showTabsSheet(BuildContext context) { + final app = AppScope.read(context); + return showModalBottomSheet( + context: context, + showDragHandle: true, + isScrollControlled: true, + builder: (sheet) => ListenableBuilder( + listenable: app, + builder: (context, _) { + final colors = context.colors; + final tabs = app.tabs; + return SafeArea( + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(context).height * 0.7, + ), + child: ListView( + shrinkWrap: true, + children: [ + for (var i = 0; i < tabs.length; i++) + ListTile( + key: ValueKey('sheet-tab-$i'), + dense: true, + selected: i == app.activeTab, + selectedColor: colors.accent, + leading: Icon(tabs[i].icon, size: 18), + title: Text( + tabs[i].title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + trailing: IconButton( + key: ValueKey('sheet-tab-close-$i'), + tooltip: 'Close tab', + icon: const Icon(Icons.close_rounded, size: 18), + onPressed: () => app.closeTab(i), + ), + onTap: () { + app.activateTab(i); + Navigator.pop(sheet); + }, + ), + ListTile( + key: const ValueKey('sheet-tab-new'), + dense: true, + leading: const Icon(Icons.add_rounded, size: 18), + title: const Text('New tab'), + onTap: () { + app.newTab(); + Navigator.pop(sheet); + }, + ), + ], + ), + ), + ); + }, + ), + ); +} diff --git a/app/lib/src/widgets/common.dart b/app/lib/src/widgets/common.dart index 97adf40..f799667 100644 --- a/app/lib/src/widgets/common.dart +++ b/app/lib/src/widgets/common.dart @@ -129,8 +129,10 @@ class _StaticBlockState extends State { base: blockTextStyle(context), refs: app.refs, assetPath: app.backend.assetPath, - onPage: app.openTitle, - onBlockRef: (r) => app.openId(r.pageId), + onPage: (t) => app.navigate(PageTarget(title: t)), + onBlockRef: (r) => app.navigate(PageTarget(id: r.pageId)), + onPageNewTab: app.openTitleInNewTab, + onBlockRefNewTab: (r) => app.openIdInNewTab(r.pageId), onUrl: openUrl, maxWidth: box.maxWidth, ), From 399c65ca6f7e1de5e4adbb0f26e99c0dd9b3f4e4 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 03:40:35 +0100 Subject: [PATCH 2/2] feat(app): new page and delete actions in All pages, tab tests and docs Co-Authored-By: Claude Opus 5.5 --- app/lib/src/views/all_pages_view.dart | 465 ++++++++++++++++++++++---- app/lib/src/views/shell.dart | 2 +- app/test/tabs_test.dart | 339 +++++++++++++++++++ docs/app.md | 20 +- 4 files changed, 750 insertions(+), 76 deletions(-) create mode 100644 app/test/tabs_test.dart diff --git a/app/lib/src/views/all_pages_view.dart b/app/lib/src/views/all_pages_view.dart index ff1b128..59c2c40 100644 --- a/app/lib/src/views/all_pages_view.dart +++ b/app/lib/src/views/all_pages_view.dart @@ -5,6 +5,7 @@ import '../state/app_state.dart'; import '../theme/theme.dart'; import '../widgets/common.dart'; import '../widgets/dates.dart'; +import '../widgets/pickers.dart' show errorText; enum PageSort { edited('Edited'), @@ -28,6 +29,8 @@ class _AllPagesViewState extends State { final _pages = []; PageSort _sort = PageSort.edited; bool _ascending = false; + bool _selecting = false; + final _chosen = {}; @override void initState() { @@ -77,6 +80,74 @@ class _AllPagesViewState extends State { app.reload(); } + Future _newPage() async { + final app = AppScope.read(context); + final id = await showDialog( + context: context, + builder: (_) => NewPageDialog(app: app), + ); + if (id == null) return; + app.go(PageTarget(id: id)); + } + + /// Asks for confirmation, then deletes `targets` and tidies tabs, recents and the list. + Future _delete(List targets) async { + if (targets.isEmpty) return; + final app = AppScope.read(context); + final messenger = ScaffoldMessenger.of(context); + final ok = await showDialog( + context: context, + builder: (_) => DeletePagesDialog(pages: targets), + ); + if (ok != true) return; + final ids = [for (final p in targets) p.id]; + try { + for (final id in ids) { + await app.queue.run(() => app.backend.deletePage(id)); + } + } catch (e) { + messenger.showSnackBar(SnackBar(content: Text(errorText(e)))); + app.reload(); + return; + } + if (mounted) { + setState(() { + _pages.removeWhere((p) => ids.contains(p.id)); + _chosen.removeAll(ids); + if (_chosen.isEmpty) _selecting = false; + }); + } + app.pagesDeleted(ids); + messenger.showSnackBar( + SnackBar( + content: Text( + 'Deleted ${ids.length} ${ids.length == 1 ? 'page' : 'pages'}', + ), + ), + ); + } + + void _toggleSelect() => setState(() { + _selecting = !_selecting; + _chosen.clear(); + }); + + Future _rowMenu(PageDto p, Offset at) async { + final app = AppScope.read(context); + final v = await showMenu( + context: context, + position: RelativeRect.fromLTRB(at.dx, at.dy, at.dx, at.dy), + items: _menuItems, + ); + if (v == 'tab') app.openIdInNewTab(p.id); + if (v == 'delete') await _delete([p]); + } + + static const _menuItems = [ + PopupMenuItem(value: 'tab', child: Text('Open in new tab')), + PopupMenuItem(value: 'delete', child: Text('Delete…')), + ]; + @override Widget build(BuildContext context) { final app = AppScope.read(context); @@ -93,57 +164,101 @@ class _AllPagesViewState extends State { itemCount: pages.length + 1, itemBuilder: (context, i) { if (i == 0) { + final title = Text( + 'All pages', + style: Theme.of(context).textTheme.headlineLarge, + ); + final actions = [ + PopupMenuButton( + key: const ValueKey('page-sort'), + tooltip: 'Sort by', + initialValue: _sort, + onSelected: (v) => setState(() { + _sort = v; + _ascending = false; + }), + itemBuilder: (_) => [ + for (final v in PageSort.values) + PopupMenuItem(value: v, child: Text(v.label)), + ], + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Text( + _sort.label, + style: TextStyle(fontSize: 13, color: colors.muted), + ), + ), + ), + IconButton( + key: const ValueKey('page-sort-direction'), + tooltip: _ascending ? 'Ascending' : 'Descending', + visualDensity: VisualDensity.compact, + iconSize: 18, + color: colors.muted, + icon: Icon( + _ascending + ? Icons.arrow_upward_rounded + : Icons.arrow_downward_rounded, + ), + onPressed: () => setState(() => _ascending = !_ascending), + ), + const SizedBox(width: 8), + TextLink( + 'Clean up', + icon: Icons.cleaning_services_outlined, + onTap: _cleanUp, + ), + const SizedBox(width: 12), + TextLink( + _selecting ? 'Done' : 'Select', + key: const ValueKey('pages-select'), + icon: _selecting + ? Icons.check_rounded + : Icons.checklist_rounded, + onTap: _toggleSelect, + ), + const SizedBox(width: 12), + if (_selecting) + FilledButton( + key: const ValueKey('pages-delete-selected'), + onPressed: _chosen.isEmpty + ? null + : () => _delete([ + for (final p in _pages) + if (_chosen.contains(p.id)) p, + ]), + child: Text('Delete (${_chosen.length})'), + ) + else + FilledButton.icon( + key: const ValueKey('new-page'), + onPressed: _newPage, + icon: const Icon(Icons.add_rounded, size: 18), + label: const Text('New page'), + ), + ]; return Padding( padding: const EdgeInsets.only(bottom: 20), - child: Row( - children: [ - Expanded( - child: Text( - 'All pages', - style: Theme.of(context).textTheme.headlineLarge, + // Narrow widths: the actions wrap below the title. + child: box.maxWidth < 760 + ? Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + title, + const SizedBox(height: 8), + Wrap( + crossAxisAlignment: WrapCrossAlignment.center, + runSpacing: 6, + children: actions, + ), + ], + ) + : Row( + children: [ + Expanded(child: title), + ...actions, + ], ), - ), - PopupMenuButton( - key: const ValueKey('page-sort'), - tooltip: 'Sort by', - initialValue: _sort, - onSelected: (v) => setState(() { - _sort = v; - _ascending = false; - }), - itemBuilder: (_) => [ - for (final v in PageSort.values) - PopupMenuItem(value: v, child: Text(v.label)), - ], - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 8), - child: Text( - _sort.label, - style: TextStyle(fontSize: 13, color: colors.muted), - ), - ), - ), - IconButton( - key: const ValueKey('page-sort-direction'), - tooltip: _ascending ? 'Ascending' : 'Descending', - visualDensity: VisualDensity.compact, - iconSize: 18, - color: colors.muted, - icon: Icon( - _ascending - ? Icons.arrow_upward_rounded - : Icons.arrow_downward_rounded, - ), - onPressed: () => setState(() => _ascending = !_ascending), - ), - const SizedBox(width: 8), - TextLink( - 'Clean up', - icon: Icons.cleaning_services_outlined, - onTap: _cleanUp, - ), - ], - ), ); } final p = pages[i - 1]; @@ -151,35 +266,85 @@ class _AllPagesViewState extends State { p.updatedAt.toInt(), ); return InkWell( + key: ValueKey('page-row-${p.id}'), borderRadius: BorderRadius.circular(8), - onTap: () => app.openId(p.id), - child: Padding( - padding: const EdgeInsets.symmetric(vertical: 9, horizontal: 8), - child: Row( - children: [ - Expanded( - child: Text( - p.title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(fontSize: 14.5, color: colors.ink), + onTap: _selecting + ? () => setState( + () => _chosen.contains(p.id) + ? _chosen.remove(p.id) + : _chosen.add(p.id), + ) + : () => app.navigate(PageTarget(id: p.id)), + onSecondaryTapUp: _selecting + ? null + : (d) => _rowMenu(p, d.globalPosition), + child: GestureDetector( + onTertiaryTapUp: _selecting + ? null + : (_) => app.openIdInNewTab(p.id), + onLongPressStart: _selecting + ? null + : (d) => _rowMenu(p, d.globalPosition), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 9, horizontal: 8), + child: Row( + children: [ + if (_selecting) + Padding( + padding: const EdgeInsets.only(right: 10), + child: Icon( + _chosen.contains(p.id) + ? Icons.check_box_rounded + : Icons.check_box_outline_blank_rounded, + key: ValueKey('page-check-${p.id}'), + size: 20, + color: _chosen.contains(p.id) + ? colors.accent + : colors.faint, + ), + ), + Expanded( + child: Text( + p.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14.5, color: colors.ink), + ), ), - ), - if (p.originJournal != null) - Text( - 'born ${shortDate(parseDay(p.originJournal!))}', - style: TextStyle(fontSize: 12, color: colors.faint), + if (p.originJournal != null) + Text( + 'born ${shortDate(parseDay(p.originJournal!))}', + style: TextStyle(fontSize: 12, color: colors.faint), + ), + const SizedBox(width: 16), + SizedBox( + width: 70, + child: Text( + shortDate(edited), + textAlign: TextAlign.right, + style: TextStyle(fontSize: 12, color: colors.muted), + ), ), - const SizedBox(width: 16), - SizedBox( - width: 70, - child: Text( - shortDate(edited), - textAlign: TextAlign.right, - style: TextStyle(fontSize: 12, color: colors.muted), - ), - ), - ], + if (!_selecting) + PopupMenuButton( + key: ValueKey('page-menu-${p.id}'), + tooltip: 'More', + iconSize: 18, + padding: EdgeInsets.zero, + icon: Icon( + Icons.more_horiz_rounded, + color: colors.faint, + ), + itemBuilder: (_) => _menuItems, + onSelected: (v) { + if (v == 'tab') app.openIdInNewTab(p.id); + if (v == 'delete') _delete([p]); + }, + ) + else + const SizedBox(width: 8), + ], + ), ), ), ); @@ -273,3 +438,155 @@ class _CleanupDialogState extends State { ); } } + +/// Asks for a page title. Pops with the id of the created page, or of the existing one when +/// the user picks "Open it" after a duplicate-title error. +class NewPageDialog extends StatefulWidget { + const NewPageDialog({super.key, required this.app}); + final AppState app; + + @override + State createState() => _NewPageDialogState(); +} + +class _NewPageDialogState extends State { + final _text = TextEditingController(); + String? _error; + String? _existingId; + bool _busy = false; + + @override + void dispose() { + _text.dispose(); + super.dispose(); + } + + Future _create() async { + final title = _text.text.trim(); + if (title.isEmpty) { + setState(() { + _error = 'Enter a title'; + _existingId = null; + }); + return; + } + if (_busy) return; + setState(() { + _busy = true; + _error = null; + _existingId = null; + }); + final app = widget.app; + try { + final existing = await app.backend.pageByTitle(title); + if (existing != null) { + if (!mounted) return; + setState(() { + _busy = false; + _error = 'A page titled "${existing.page.title}" already exists'; + _existingId = existing.page.id; + }); + return; + } + final page = await app.queue.run(() => app.backend.openPage(title)); + if (mounted) Navigator.pop(context, page.page.id); + } catch (e) { + if (mounted) { + setState(() { + _busy = false; + _error = errorText(e); + }); + } + } + } + + @override + Widget build(BuildContext context) => AlertDialog( + title: const Text('New page'), + content: SizedBox( + width: 380, + child: TextField( + key: const ValueKey('new-page-title'), + controller: _text, + autofocus: true, + decoration: InputDecoration(hintText: 'Title', errorText: _error), + onChanged: (_) { + if (_error != null) { + setState(() { + _error = null; + _existingId = null; + }); + } + }, + onSubmitted: (_) => _create(), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + if (_existingId != null) + TextButton( + key: const ValueKey('open-existing'), + onPressed: () => Navigator.pop(context, _existingId), + child: const Text('Open it'), + ), + FilledButton( + key: const ValueKey('create-page'), + onPressed: _create, + child: const Text('Create'), + ), + ], + ); +} + +/// Confirmation before deleting pages; pops true when confirmed. +class DeletePagesDialog extends StatelessWidget { + const DeletePagesDialog({super.key, required this.pages}); + final List pages; + + @override + Widget build(BuildContext context) { + final n = pages.length; + final hubs = pages.any((p) => p.isHub); + final journals = pages.any((p) => p.journalDate != null); + return AlertDialog( + title: Text('Delete $n ${n == 1 ? 'page' : 'pages'}?'), + content: SizedBox( + width: 420, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Their blocks are removed; links to them stay as plain references.', + ), + if (hubs) ...[ + const SizedBox(height: 8), + const Text( + "Hubs: their members leave the hub, and the hub's template " + 'is deleted with it.', + ), + ], + if (journals) ...[ + const SizedBox(height: 8), + const Text('This includes journal pages.'), + ], + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('Cancel'), + ), + FilledButton( + key: const ValueKey('confirm-delete'), + onPressed: () => Navigator.pop(context, true), + child: const Text('Delete'), + ), + ], + ); + } +} diff --git a/app/lib/src/views/shell.dart b/app/lib/src/views/shell.dart index 7087be3..b5b87f7 100644 --- a/app/lib/src/views/shell.dart +++ b/app/lib/src/views/shell.dart @@ -177,7 +177,7 @@ class _TopBar extends StatelessWidget { const Spacer(), if (narrow) const TabCountButton(), // Phones: an icon instead of the pill keeps the bar from overflowing. - if (MediaQuery.sizeOf(context).width < 480) + if (MediaQuery.sizeOf(context).width < 600) icon( Icons.search_rounded, 'Search (${app.keymap.of(AppAction.quickSwitcher).label})', diff --git a/app/test/tabs_test.dart b/app/test/tabs_test.dart new file mode 100644 index 0000000..62fcb49 --- /dev/null +++ b/app/test/tabs_test.dart @@ -0,0 +1,339 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:synapse/src/backend/graph_backend.dart'; +import 'package:synapse/src/state/app_state.dart'; +import 'package:synapse/src/state/settings.dart'; +import 'package:synapse/src/theme/theme.dart'; +import 'package:synapse/src/views/all_pages_view.dart'; +import 'package:synapse/src/views/shell.dart'; + +import 'support/memory_backend.dart'; + +MemoryBackend demo() { + final b = MemoryBackend(); + for (final t in ['Alpha', 'Beta', 'Gamma']) { + b.createPage(t); + } + return b; +} + +PageDto byTitle(MemoryBackend b, String t) => + b.pages.values.firstWhere((p) => p.title == t); + +Future settle(WidgetTester tester) async { + for (var i = 0; i < 6; i++) { + await tester.pump(const Duration(milliseconds: 50)); + } +} + +Future pump( + WidgetTester tester, + MemoryBackend b, { + Widget home = const Shell(), + AppState? state, + Size size = const Size(1600, 1000), +}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final app = state ?? AppState(b); + await tester.pumpWidget( + AppScope( + state: app, + child: MaterialApp(theme: buildTheme(Brightness.light), home: home), + ), + ); + await settle(tester); + return app; +} + +Future chord( + WidgetTester tester, + LogicalKeyboardKey key, { + bool shift = false, +}) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + if (shift) await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyEvent(key); + if (shift) await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await settle(tester); +} + +void main() { + group('tab state', () { + test('each tab keeps its own history', () { + final app = AppState(demo()); + app.go(const AllPagesRoute()); + app.openInNewTab(const SettingsRoute()); + expect(app.tabs.length, 2); + expect(app.activeTab, 1); + expect(app.canGoBack, isFalse); + app.go(const TimelineRoute()); + expect(app.canGoBack, isTrue); + app.activateTab(0); + expect(app.route, isA()); + app.back(); + expect(app.route, isA()); + app.activateTab(1); + expect(app.route, isA()); + app.back(); + expect(app.route, isA()); + app.forward(); + expect(app.route, isA()); + }); + + test( + 'closing tabs keeps the active one sensible; the last leaves Journals', + () { + final app = AppState(demo()); + app.openInNewTab(const AllPagesRoute()); + app.openInNewTab(const SettingsRoute(), activate: false); + expect(app.activeTab, 1); + app.closeTab(0); + expect(app.activeTab, 0); + expect(app.route, isA()); + app.closeTab(); + expect(app.route, isA()); + app.closeTab(); + expect(app.tabs.length, 1); + expect(app.route, isA()); + }, + ); + + test('tabs persist across a restart; broken entries are skipped', () { + final store = MemorySettings(); + final b = demo(); + final alpha = byTitle(b, 'Alpha'); + final app = AppState(b, settings: store); + app.go(PageTarget(id: alpha.id)); + app.openInNewTab(const GraphRoute(GraphMode.tree, focusId: 'x')); + app.openInNewTab(const AllPagesRoute()); + app.activateTab(1); + final saved = store.load(); + (saved['tabs']['items'] as List).insert(1, {'t': 'nonsense'}); + (saved['tabs']['items'] as List).add('garbage'); + saved['tabs']['active'] = 2; + store.save(saved); + + final again = AppState(b, settings: store); + expect(again.tabs.length, 3); + expect(again.activeTab, 2); + expect((again.tabs[0].route as PageTarget).id, alpha.id); + final g = again.tabs[1].route as GraphRoute; + expect(g.mode, GraphMode.tree); + expect(g.focusId, 'x'); + expect(again.tabs[2].route, isA()); + expect(again.canGoBack, isFalse); + }); + + test('deleting a page falls back in tabs and drops recents', () { + final b = demo(); + final alpha = byTitle(b, 'Alpha'); + final beta = byTitle(b, 'Beta'); + final app = AppState(b); + app.go(PageTarget(id: beta.id)); + app.go(PageTarget(id: alpha.id)); + app.openInNewTab(PageTarget(id: alpha.id)); + app.recent.add( + PageBrief(id: alpha.id, title: 'Alpha', isJournal: false, isHub: false), + ); + app.pagesDeleted([alpha.id]); + expect(app.recent, isEmpty); + expect(app.route, isA()); + app.activateTab(0); + expect((app.route as PageTarget).id, beta.id); + }); + }); + + group('tabs UI', () { + testWidgets('keyboard shortcuts open, switch and close tabs', ( + tester, + ) async { + final app = await pump(tester, demo()); + expect(app.tabs.length, 1); + await chord(tester, LogicalKeyboardKey.keyT); + expect(app.tabs.length, 2); + expect(app.activeTab, 1); + await chord(tester, LogicalKeyboardKey.tab); + expect(app.activeTab, 0); + await chord(tester, LogicalKeyboardKey.tab, shift: true); + expect(app.activeTab, 1); + await chord(tester, LogicalKeyboardKey.keyW); + expect(app.tabs.length, 1); + await chord(tester, LogicalKeyboardKey.keyW); + expect(app.tabs.length, 1); + expect(app.route, isA()); + }); + + testWidgets('strip shows titles; middle-click closes, plus opens', ( + tester, + ) async { + final app = await pump(tester, demo()); + app.go(const AllPagesRoute()); + await settle(tester); + await tester.tap(find.byKey(const ValueKey('tab-new'))); + await settle(tester); + expect(app.tabs.length, 2); + final strip = find.byKey(const ValueKey('tab-strip')); + expect( + find.descendant(of: strip, matching: find.text('All pages')), + findsOneWidget, + ); + final at = tester.getCenter( + find.descendant(of: strip, matching: find.text('All pages')), + ); + final mouse = await tester.createGesture( + kind: PointerDeviceKind.mouse, + buttons: kMiddleMouseButton, + ); + await mouse.down(at); + await mouse.up(); + await settle(tester); + expect(app.tabs.length, 1); + expect(app.route, isA()); + }); + + testWidgets('narrow layout lists tabs in a sheet', (tester) async { + final app = await pump(tester, demo(), size: const Size(500, 900)); + app.openInNewTab(const AllPagesRoute()); + await settle(tester); + expect(find.byKey(const ValueKey('tab-strip')), findsNothing); + await tester.tap(find.byKey(const ValueKey('tab-count'))); + await settle(tester); + expect(find.byKey(const ValueKey('sheet-tab-1')), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('sheet-tab-0'))); + await settle(tester); + expect(app.activeTab, 0); + await tester.tap(find.byKey(const ValueKey('tab-count'))); + await settle(tester); + await tester.tap(find.byKey(const ValueKey('sheet-tab-close-1'))); + await settle(tester); + expect(app.tabs.length, 1); + }); + + testWidgets('ctrl+click on an All pages row opens a new tab', ( + tester, + ) async { + final b = demo(); + final app = await pump(tester, b, state: AppState(b)); + app.go(const AllPagesRoute()); + await settle(tester); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.tap(find.text('Beta')); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await settle(tester); + expect(app.tabs.length, 2); + expect(app.activeTab, 1); + expect((app.route as PageTarget).id, byTitle(b, 'Beta').id); + expect(app.tabs[0].route, isA()); + }); + }); + + group('All pages actions', () { + testWidgets('new page: validation, duplicate error and open it', ( + tester, + ) async { + final b = demo(); + final app = await pump( + tester, + b, + home: const Scaffold(body: AllPagesView()), + ); + await tester.tap(find.byKey(const ValueKey('new-page'))); + await settle(tester); + await tester.tap(find.byKey(const ValueKey('create-page'))); + await settle(tester); + expect(find.text('Enter a title'), findsOneWidget); + + await tester.enterText( + find.byKey(const ValueKey('new-page-title')), + 'alpha', + ); + await tester.tap(find.byKey(const ValueKey('create-page'))); + await settle(tester); + expect(find.textContaining('already exists'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('open-existing'))); + await settle(tester); + expect((app.route as PageTarget).id, byTitle(b, 'Alpha').id); + + await tester.tap(find.byKey(const ValueKey('new-page'))); + await settle(tester); + await tester.enterText( + find.byKey(const ValueKey('new-page-title')), + 'Delta', + ); + await tester.tap(find.byKey(const ValueKey('create-page'))); + await settle(tester); + expect(b.pages.values.where((p) => p.title == 'Delta').length, 1); + expect((app.route as PageTarget).id, byTitle(b, 'Delta').id); + }); + + testWidgets('single delete asks first and says what happens', ( + tester, + ) async { + final b = demo(); + final beta = byTitle(b, 'Beta'); + await pump(tester, b, home: const Scaffold(body: AllPagesView())); + await tester.tap(find.byKey(ValueKey('page-menu-${beta.id}'))); + await settle(tester); + await tester.tap(find.text('Delete…')); + await settle(tester); + expect(find.text('Delete 1 page?'), findsOneWidget); + expect(find.textContaining('plain references'), findsOneWidget); + await tester.tap(find.text('Cancel')); + await settle(tester); + expect(b.pages.containsKey(beta.id), isTrue); + + await tester.tap(find.byKey(ValueKey('page-menu-${beta.id}'))); + await settle(tester); + await tester.tap(find.text('Delete…')); + await settle(tester); + await tester.tap(find.byKey(const ValueKey('confirm-delete'))); + await settle(tester); + expect(b.pages.containsKey(beta.id), isFalse); + expect(find.text('Beta'), findsNothing); + expect(find.text('Deleted 1 page'), findsOneWidget); + }); + + testWidgets('bulk delete in selection mode; open tab falls back', ( + tester, + ) async { + final b = demo(); + final alpha = byTitle(b, 'Alpha'); + final beta = byTitle(b, 'Beta'); + final app = await pump(tester, b, home: const Shell()); + app.go(PageTarget(id: alpha.id)); + app.openInNewTab(const AllPagesRoute()); + await settle(tester); + + await tester.tap(find.byKey(const ValueKey('pages-select'))); + await settle(tester); + expect( + tester + .widget( + find.byKey(const ValueKey('pages-delete-selected')), + ) + .onPressed, + isNull, + ); + await tester.tap(find.byKey(ValueKey('page-row-${alpha.id}'))); + await tester.tap(find.byKey(ValueKey('page-row-${beta.id}'))); + await settle(tester); + await tester.tap(find.byKey(const ValueKey('pages-delete-selected'))); + await settle(tester); + expect(find.text('Delete 2 pages?'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('confirm-delete'))); + await settle(tester); + + expect(b.pages.values.map((p) => p.title), isNot(contains('Alpha'))); + expect(b.pages.values.map((p) => p.title), isNot(contains('Beta'))); + expect(find.text('Deleted 2 pages'), findsOneWidget); + app.activateTab(0); + await settle(tester); + expect(app.route, isA()); + }); + }); +} diff --git a/docs/app.md b/docs/app.md index 7a49cc8..8c5023b 100644 --- a/docs/app.md +++ b/docs/app.md @@ -79,7 +79,21 @@ Commit the regenerated `crates/synapse-ffi/src/frb_generated.rs` and `app/lib/sr structure wins if they ever disagree. - App shortcuts (defaults, all rebindable in Settings): Ctrl+K quick switcher, Ctrl+Shift+J journals, Ctrl+Shift+G graph, Ctrl+Shift+T timeline, Ctrl+\ sidebar, Ctrl+Shift+\ graph - sidebar, Ctrl+, settings, Alt+←/→ back/forward. + sidebar, Ctrl+, settings, Alt+←/→ back/forward, Ctrl+T new tab, Ctrl+W close tab, + Ctrl+Tab / Ctrl+Shift+Tab next/previous tab. + +## Tabs +- `AppState` holds a list of `AppTab`s; each has its own route and back/forward history, and + `go`/`back`/`forward`/`canGoBack` act on the active one. The strip (`views/tab_strip.dart`) + sits under the top bar: × on hover or on the active tab, middle-click closes, drag reorders, + "+" opens a Journals tab; closing the last tab leaves one Journals tab. Below 760 px the strip + is replaced by a tab-count button in the top bar that opens a bottom sheet. +- Ctrl/Cmd+click (or middle-click) on a page link or block ref in the editor, on sidebar + entries, All pages rows and quick switcher results opens in a new tab + (`AppState.navigate` / `openInNewTab`). +- Open tabs (route type and page id/title, graph mode) and the active index are saved under + `tabs` in the settings JSON and restored on start; history is not persisted. Deleting a page + (`AppState.pagesDeleted`) sends tabs showing it back (or to Journals) and drops it from recents. ## Settings, themes and key bindings - Top-bar gear icon, next to the theme toggle (Ctrl+,): theme cards and the shortcut list. Click a shortcut, press the new @@ -156,6 +170,10 @@ comments, selectors and unknown properties are ignored (unknown `--vars` are rep related pages; on narrow windows they appear below the content. - All pages lists notes only (hubs are folders, not pages) and can be sorted by edited, created or title, ascending or descending. +- "New page" asks for a title (empty or duplicate titles are refused inline, with "Open it" + for an existing page). Each row has a `⋯` menu (also on right-click or long-press) with + "Open in new tab" and "Delete…"; "Select" switches to checkboxes with a bulk "Delete (N)". + Deletion always asks for confirmation and runs `deletePage` per page. ## Graph view One view (sidebar "Graph", Ctrl+Shift+G) with a mode selector: