From d407a72a0644017cab288c7468eac5c59d75cd48 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 21 Nov 2026 18:13:08 +0000 Subject: [PATCH] Diff viewer: vim keys, scrolling, find in diff and an all-files view Left/right and h/l step between files (or headers in the all-files view), up/down and j/k scroll, / opens find-in-diff (highlighted matches across every file, n/N or Enter/Shift+Enter to move, Escape to close), and a top-bar toggle switches between one file at a time and every file stacked with collapsible headers, like a pull request's Files changed tab. Co-Authored-By: Claude Opus 5.5 --- .../features/changes/domain/diff_search.dart | 91 ++++++ .../changes/widgets/capture_section.dart | 5 +- .../changes/widgets/diff_highlight.dart | 43 +++ .../changes/widgets/diff_keyboard.dart | 87 ++++++ .../changes/widgets/diff_search_bar.dart | 102 +++++++ .../widgets/diff_search_controller.dart | 55 ++++ .../changes/widgets/file_diff_page.dart | 285 ++++++++++++++++++ .../changes/widgets/file_diff_viewer.dart | 106 ++----- .../features/changes/widgets/patch_view.dart | 71 ++++- .../changes/widgets/raw_patch_view.dart | 9 +- .../changes/widgets/stacked_diff_view.dart | 149 +++++++++ .../features/changes/file_diff_page_test.dart | 167 ++++++++++ 12 files changed, 1072 insertions(+), 98 deletions(-) create mode 100644 app/lib/features/changes/domain/diff_search.dart create mode 100644 app/lib/features/changes/widgets/diff_highlight.dart create mode 100644 app/lib/features/changes/widgets/diff_keyboard.dart create mode 100644 app/lib/features/changes/widgets/diff_search_bar.dart create mode 100644 app/lib/features/changes/widgets/diff_search_controller.dart create mode 100644 app/lib/features/changes/widgets/file_diff_page.dart create mode 100644 app/lib/features/changes/widgets/stacked_diff_view.dart create mode 100644 app/test/features/changes/file_diff_page_test.dart diff --git a/app/lib/features/changes/domain/diff_search.dart b/app/lib/features/changes/domain/diff_search.dart new file mode 100644 index 00000000..a5aff734 --- /dev/null +++ b/app/lib/features/changes/domain/diff_search.dart @@ -0,0 +1,91 @@ +import 'file_change.dart'; + +/// One occurrence of a search query in a rendered diff line: the file's index +/// in the viewed list, the hunk and line within its parsed patch, and the +/// match's character range in the line's text. +class DiffMatch { + const DiffMatch({ + required this.file, + required this.hunk, + required this.line, + required this.start, + required this.end, + }); + + final int file; + final int hunk; + final int line; + final int start; + final int end; + + /// Whether this match lies on the given line. + bool isOn(int file, int hunk, int line) => + this.file == file && this.hunk == hunk && this.line == line; + + @override + bool operator ==(Object other) => + other is DiffMatch && + other.file == file && + other.hunk == hunk && + other.line == line && + other.start == start; + + @override + int get hashCode => Object.hash(file, hunk, line, start); +} + +/// Every case-insensitive occurrence of [query] in the rendered lines of +/// [files], in reading order. A blank query matches nothing. Only hunk lines +/// are searched: the rendered view does not draw the `---`/`+++` headers. +List diffMatches(List files, String query) { + final needle = query.toLowerCase(); + if (needle.trim().isEmpty) return const []; + final matches = []; + for (var f = 0; f < files.length; f++) { + final file = files[f]; + if (!file.hasPatch) continue; + final hunks = file.parsedPatch.hunks; + for (var h = 0; h < hunks.length; h++) { + final lines = hunks[h].lines; + for (var l = 0; l < lines.length; l++) { + for (final range in matchRanges(lines[l].text, needle)) { + matches.add( + DiffMatch( + file: f, + hunk: h, + line: l, + start: range.$1, + end: range.$2, + ), + ); + } + } + } + } + return matches; +} + +/// The non-overlapping case-insensitive ranges of [query] in [text]. +List<(int, int)> matchRanges(String text, String query) { + final needle = query.toLowerCase(); + if (needle.isEmpty) return const []; + final haystack = text.toLowerCase(); + final ranges = <(int, int)>[]; + var from = 0; + while (true) { + final at = haystack.indexOf(needle, from); + if (at < 0) break; + ranges.add((at, at + needle.length)); + from = at + needle.length; + } + return ranges; +} + +/// The index of the first match in [matches] at or after file [file], wrapping +/// to the first match; null when there are none. Opening a search starts at +/// the file being read rather than at the top of the list. +int? firstMatchFrom(List matches, int file) { + if (matches.isEmpty) return null; + final index = matches.indexWhere((match) => match.file >= file); + return index < 0 ? 0 : index; +} diff --git a/app/lib/features/changes/widgets/capture_section.dart b/app/lib/features/changes/widgets/capture_section.dart index 071cf708..bb505b4f 100644 --- a/app/lib/features/changes/widgets/capture_section.dart +++ b/app/lib/features/changes/widgets/capture_section.dart @@ -109,7 +109,7 @@ class ChangeFileRow extends StatelessWidget { @override Widget build(BuildContext context) { final mono = nativeDiffText(DefaultTextStyle.of(context).style); - final leading = Icon(_kindIcon(file.kind)); + final leading = Icon(changeKindIcon(file.kind)); final title = Text(file.path, style: mono); final subtitle = ChangeStatText(changeFileMeta(file)); const trailing = Icon(Icons.chevron_right); @@ -179,7 +179,8 @@ IconData _noteIcon(_NoteKind kind) => switch (kind) { _NoteKind.pending => Icons.schedule, }; -IconData _kindIcon(ChangeKind kind) => switch (kind) { +/// The glyph a changed file's kind is drawn with. +IconData changeKindIcon(ChangeKind kind) => switch (kind) { ChangeKind.added => Icons.add_circle_outline, ChangeKind.deleted => Icons.delete_outline, ChangeKind.modified => Icons.edit_outlined, diff --git a/app/lib/features/changes/widgets/diff_highlight.dart b/app/lib/features/changes/widgets/diff_highlight.dart new file mode 100644 index 00000000..a049bd89 --- /dev/null +++ b/app/lib/features/changes/widgets/diff_highlight.dart @@ -0,0 +1,43 @@ +import 'package:flutter/widgets.dart'; + +import '../domain/diff_search.dart'; + +/// The active diff search, handed down to the rendered patch lines: the query +/// they highlight, the current match drawn stronger and the key that match's +/// line carries so the page can scroll it into view. +class DiffHighlight extends InheritedWidget { + const DiffHighlight({ + super.key, + required this.query, + required this.current, + required this.currentKey, + required super.child, + }); + + final String query; + final DiffMatch? current; + final GlobalKey currentKey; + + bool get active => query.trim().isNotEmpty; + + static DiffHighlight? maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType(); + + @override + bool updateShouldNotify(DiffHighlight oldWidget) => + query != oldWidget.query || current != oldWidget.current; +} + +/// The index of the file a rendered patch belongs to in the viewed list, so a +/// line can tell whether the current match is on it. +class DiffFileIndex extends InheritedWidget { + const DiffFileIndex({super.key, required this.index, required super.child}); + + final int index; + + static int? maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()?.index; + + @override + bool updateShouldNotify(DiffFileIndex oldWidget) => index != oldWidget.index; +} diff --git a/app/lib/features/changes/widgets/diff_keyboard.dart b/app/lib/features/changes/widgets/diff_keyboard.dart new file mode 100644 index 00000000..c92c1956 --- /dev/null +++ b/app/lib/features/changes/widgets/diff_keyboard.dart @@ -0,0 +1,87 @@ +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +/// The diff page's keyboard: left/right and `h`/`l` step between files, +/// up/down and `k`/`j` scroll, `/` opens search, `n`/`N` go to the next and +/// previous match, Escape closes. While a text field has focus (the search +/// box) every key is left to it, so typing an `h` never changes file. +class DiffKeyboard extends StatelessWidget { + const DiffKeyboard({ + super.key, + required this.focusNode, + required this.onPrevious, + required this.onNext, + required this.onScroll, + required this.onSearch, + required this.onMatch, + required this.onEscape, + required this.child, + }); + + final FocusNode focusNode; + final VoidCallback onPrevious; + final VoidCallback onNext; + + /// Called with +1 (down) or -1 (up). + final ValueChanged onScroll; + final VoidCallback onSearch; + + /// Called with +1 (next match) or -1 (previous match). + final ValueChanged onMatch; + final VoidCallback onEscape; + final Widget child; + + @override + Widget build(BuildContext context) => Focus( + focusNode: focusNode, + autofocus: true, + onKeyEvent: _handle, + child: child, + ); + + KeyEventResult _handle(FocusNode node, KeyEvent event) { + if (event is KeyUpEvent) return KeyEventResult.ignored; + final primary = FocusManager.instance.primaryFocus; + final focused = primary?.context; + if (primary != node && + focused != null && + (focused.widget is EditableText || + focused.findAncestorWidgetOfExactType() != null)) { + return KeyEventResult.ignored; + } + final keyboard = HardwareKeyboard.instance; + if (keyboard.isControlPressed || + keyboard.isMetaPressed || + keyboard.isAltPressed) { + return KeyEventResult.ignored; + } + final key = event.logicalKey; + final shift = keyboard.isShiftPressed; + final repeatable = event is KeyDownEvent || event is KeyRepeatEvent; + if (!repeatable) return KeyEventResult.ignored; + if (key == LogicalKeyboardKey.arrowDown || key == LogicalKeyboardKey.keyJ) { + onScroll(1); + } else if (key == LogicalKeyboardKey.arrowUp || + key == LogicalKeyboardKey.keyK) { + onScroll(-1); + } else if (event is! KeyDownEvent) { + // Only scrolling repeats while a key is held. + return KeyEventResult.ignored; + } else if (key == LogicalKeyboardKey.arrowLeft || + key == LogicalKeyboardKey.keyH) { + onPrevious(); + } else if (key == LogicalKeyboardKey.arrowRight || + key == LogicalKeyboardKey.keyL) { + onNext(); + } else if (key == LogicalKeyboardKey.slash || event.character == '/') { + onSearch(); + } else if (key == LogicalKeyboardKey.keyN) { + onMatch(shift ? -1 : 1); + } else if (key == LogicalKeyboardKey.escape) { + onEscape(); + } else { + return KeyEventResult.ignored; + } + return KeyEventResult.handled; + } +} diff --git a/app/lib/features/changes/widgets/diff_search_bar.dart b/app/lib/features/changes/widgets/diff_search_bar.dart new file mode 100644 index 00000000..4aa57ca9 --- /dev/null +++ b/app/lib/features/changes/widgets/diff_search_bar.dart @@ -0,0 +1,102 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +/// The find-in-diff field `/` opens: the query, "3 of 12", previous and next +/// match, and close. Enter goes to the next match, Shift+Enter to the +/// previous one, Escape closes. +class DiffSearchBar extends StatelessWidget { + const DiffSearchBar({ + super.key, + required this.controller, + required this.focusNode, + required this.position, + required this.count, + required this.onChanged, + required this.onNext, + required this.onPrevious, + required this.onClose, + }); + + final TextEditingController controller; + final FocusNode focusNode; + + /// The current match, counted from 1; 0 when there is none. + final int position; + final int count; + final ValueChanged onChanged; + final VoidCallback onNext; + final VoidCallback onPrevious; + final VoidCallback onClose; + + @override + Widget build(BuildContext context) { + final summary = controller.text.isEmpty + ? '' + : count == 0 + ? 'No matches' + : '$position of $count'; + return Material( + elevation: 3, + borderRadius: BorderRadius.circular(28), + color: Theme.of(context).colorScheme.surfaceContainerHigh, + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 4, 4), + child: Row( + children: [ + const Icon(Icons.search), + const SizedBox(width: 8), + Expanded( + child: CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.enter, shift: true): + onPrevious, + const SingleActivator(LogicalKeyboardKey.escape): onClose, + }, + child: TextField( + key: const ValueKey('diff-search-field'), + controller: controller, + focusNode: focusNode, + autofocus: true, + decoration: const InputDecoration( + hintText: 'Find in diff', + border: InputBorder.none, + isDense: true, + ), + onChanged: onChanged, + onSubmitted: (_) { + onNext(); + focusNode.requestFocus(); + }, + ), + ), + ), + if (summary.isNotEmpty) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Text( + summary, + key: const ValueKey('diff-search-summary'), + style: Theme.of(context).textTheme.bodySmall, + ), + ), + IconButton( + tooltip: 'Previous match', + onPressed: count == 0 ? null : onPrevious, + icon: const Icon(Icons.keyboard_arrow_up), + ), + IconButton( + tooltip: 'Next match', + onPressed: count == 0 ? null : onNext, + icon: const Icon(Icons.keyboard_arrow_down), + ), + IconButton( + tooltip: 'Close search', + onPressed: onClose, + icon: const Icon(Icons.close), + ), + ], + ), + ), + ); + } +} diff --git a/app/lib/features/changes/widgets/diff_search_controller.dart b/app/lib/features/changes/widgets/diff_search_controller.dart new file mode 100644 index 00000000..4683a9cf --- /dev/null +++ b/app/lib/features/changes/widgets/diff_search_controller.dart @@ -0,0 +1,55 @@ +import 'package:flutter/foundation.dart'; + +import '../domain/diff_search.dart'; +import '../domain/file_change.dart'; + +/// The diff page's search: whether it is open, its query, every match across +/// the viewed files and which one is current. +class DiffSearchController extends ChangeNotifier { + bool _open = false; + String _query = ''; + List _matches = const []; + int? _current; + + bool get open => _open; + String get query => _open ? _query : ''; + List get matches => _matches; + + /// The current match, or null when there is none. + DiffMatch? get current => _current == null ? null : _matches[_current!]; + + /// The current match's position counted from 1, or 0. + int get position => _current == null ? 0 : _current! + 1; + + void show() { + if (_open) return; + _open = true; + notifyListeners(); + } + + void close() { + if (!_open) return; + _open = false; + notifyListeners(); + } + + /// Searches [files] for [query], starting at the first match in [fromFile] + /// or after it. + void search(List files, String query, {required int fromFile}) { + _open = true; + _query = query; + _matches = diffMatches(files, query); + _current = firstMatchFrom(_matches, fromFile); + notifyListeners(); + } + + /// Moves to the next (+1) or previous (-1) match, wrapping around. Returns + /// false when there is no match to move to. + bool step(int delta) { + if (!_open || _matches.isEmpty) return false; + final from = _current ?? (delta > 0 ? -1 : 0); + _current = (from + delta) % _matches.length; + notifyListeners(); + return true; + } +} diff --git a/app/lib/features/changes/widgets/file_diff_page.dart b/app/lib/features/changes/widgets/file_diff_page.dart new file mode 100644 index 00000000..c8810e0b --- /dev/null +++ b/app/lib/features/changes/widgets/file_diff_page.dart @@ -0,0 +1,285 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/floating_bar_layout.dart'; +import '../../../ui/adaptive/glass_bar.dart'; +import '../../../ui/adaptive/segmented_bar.dart'; +import '../../../ui/navigation/chevron_pager.dart'; +import '../domain/file_change.dart'; +import 'diff_highlight.dart'; +import 'diff_keyboard.dart'; +import 'diff_search_bar.dart'; +import 'diff_search_controller.dart'; +import 'file_diff_viewer.dart'; +import 'stacked_diff_view.dart'; + +/// Whether diff pages show every file stacked (GitHub's Files changed) rather +/// than one file at a time. Remembered for the rest of the session. +final ValueNotifier diffShowsAllFiles = ValueNotifier(false); + +/// How far one up/down (`k`/`j`) press scrolls. +const double diffScrollStep = 64; + +/// Open [file] on its own page, as the browser's file view. [files] is the +/// list it was picked from (the visit's shown files); the page steps through +/// them with previous/next chevrons at its bottom right. +Future showFileDiffViewer( + BuildContext context, + FileChange file, { + List? files, +}) { + final list = files == null || !files.contains(file) ? [file] : files; + final page = FileDiffPage(files: list, initialIndex: list.indexOf(file)); + return Navigator.of( + context, + ).push(MaterialPageRoute(builder: (_) => page)); +} + +/// A diff's files as a page: one file at a time with previous/next, or every +/// file stacked with collapsible headers. The keyboard steps between files +/// (arrows, `h`/`l`), scrolls (arrows, `j`/`k`) and searches (`/`, `n`/`N`). +class FileDiffPage extends StatefulWidget { + const FileDiffPage({super.key, required this.files, this.initialIndex = 0}); + + final List files; + final int initialIndex; + + @override + State createState() => _FileDiffPageState(); +} + +class _FileDiffPageState extends State { + late int _index = widget.initialIndex.clamp(0, widget.files.length - 1); + final _single = ScrollController(); + final _stacked = ScrollController(); + final _pageFocus = FocusNode(debugLabel: 'diff page'); + final _searchFocus = FocusNode(debugLabel: 'diff search'); + final _searchText = TextEditingController(); + final _search = DiffSearchController(); + final _matchKey = GlobalKey(debugLabel: 'diff current match'); + late final _headerKeys = [ + for (final file in widget.files) GlobalKey(debugLabel: file.path), + ]; + final _collapsed = {}; + + bool get _all => diffShowsAllFiles.value; + int get _count => widget.files.length; + + @override + void initState() { + super.initState(); + diffShowsAllFiles.addListener(_rebuild); + _search.addListener(_rebuild); + } + + @override + void dispose() { + diffShowsAllFiles.removeListener(_rebuild); + _search.dispose(); + _single.dispose(); + _stacked.dispose(); + _pageFocus.dispose(); + _searchFocus.dispose(); + _searchText.dispose(); + super.dispose(); + } + + void _rebuild() { + if (mounted) setState(() {}); + } + + void _step(int delta) { + final next = (_index + delta).clamp(0, _count - 1); + if (next == _index) return; + setState(() => _index = next); + if (_all) _reveal(_headerKeys[next].currentContext, 0); + } + + void _scroll(int direction) { + final controller = _all ? _stacked : _single; + if (!controller.hasClients) return; + final position = controller.position; + final target = (position.pixels + direction * diffScrollStep).clamp( + position.minScrollExtent, + position.maxScrollExtent, + ); + controller.jumpTo(target); + } + + void _reveal(BuildContext? target, double alignment) { + if (target == null) return; + Scrollable.ensureVisible( + target, + alignment: alignment, + duration: const Duration(milliseconds: 150), + ); + } + + void _openSearch() { + _search.show(); + if (_searchText.text.isNotEmpty) _query(_searchText.text); + _searchFocus.requestFocus(); + } + + void _closeSearch() { + _search.close(); + _pageFocus.requestFocus(); + } + + void _query(String text) { + _search.search(widget.files, text, fromFile: _index); + _showCurrent(); + } + + void _match(int delta) { + if (_search.step(delta)) _showCurrent(); + } + + /// Brings the current match's file up (expanding it when stacked) and + /// scrolls its line into view once drawn. + void _showCurrent() { + final match = _search.current; + if (match == null) return; + setState(() { + _index = match.file; + _collapsed.remove(match.file); + }); + WidgetsBinding.instance.addPostFrameCallback( + (_) => _reveal(_matchKey.currentContext, 0.4), + ); + } + + void _toggleLayout() { + diffShowsAllFiles.value = !_all; + if (_all) { + WidgetsBinding.instance.addPostFrameCallback( + (_) => _reveal(_headerKeys[_index].currentContext, 0), + ); + } + } + + void _toggleFile(int index) => setState(() { + if (!_collapsed.remove(index)) _collapsed.add(index); + }); + + void _toggleAll() => setState(() { + if (_collapsed.length == _count) { + _collapsed.clear(); + } else { + _collapsed.addAll(List.generate(_count, (i) => i)); + } + }); + + @override + Widget build(BuildContext context) { + final file = widget.files[_index]; + final title = _all + ? '$_count ${_count == 1 ? 'file' : 'files'} changed' + : file.path.split('/').last; + final content = _all + ? StackedDiffView( + files: widget.files, + collapsed: _collapsed, + onToggle: _toggleFile, + controller: _stacked, + headerKeys: _headerKeys, + ) + : DiffFileIndex( + index: _index, + child: FileDiffViewer( + key: ValueKey('file-diff-${file.path}'), + file: file, + floatBehindTopBar: true, + scrollController: _single, + ), + ); + final pager = _all || _count < 2 + ? null + : ChevronPager( + key: const ValueKey('file-diff-pager'), + index: _index, + count: _count, + previousLabel: 'Previous file', + nextLabel: 'Next file', + onPrevious: _index > 0 ? () => _step(-1) : null, + onNext: _index < _count - 1 ? () => _step(1) : null, + ); + final bar = SafeArea( + top: false, + minimum: const EdgeInsets.all(8), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + if (_search.open) + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 560), + child: DiffSearchBar( + controller: _searchText, + focusNode: _searchFocus, + position: _search.position, + count: _search.matches.length, + onChanged: _query, + onNext: () => _match(1), + onPrevious: () => _match(-1), + onClose: _closeSearch, + ), + ), + if (_search.open && pager != null) const SizedBox(height: 8), + ?(pager == null ? null : GlassControlBar(child: pager)), + ], + ), + ); + final body = DiffKeyboard( + focusNode: _pageFocus, + onPrevious: () => _step(-1), + onNext: () => _step(1), + onScroll: _scroll, + onSearch: _openSearch, + onMatch: _match, + onEscape: () => + _search.open ? _closeSearch() : Navigator.of(context).maybePop(), + child: DiffHighlight( + query: _search.query, + current: _search.open ? _search.current : null, + currentKey: _matchKey, + child: FloatingBarOverlay(bar: bar, child: content), + ), + ); + return Scaffold( + extendBodyBehindAppBar: true, + appBar: SegmentedBar( + title: title, + actions: [ + IconButton( + key: const ValueKey('diff-search-open'), + tooltip: 'Find in diff (/)', + onPressed: _openSearch, + icon: const Icon(Icons.search), + ), + if (_all) + IconButton( + key: const ValueKey('diff-collapse-all'), + tooltip: _collapsed.length == _count + ? 'Expand all files' + : 'Collapse all files', + onPressed: _toggleAll, + icon: Icon( + _collapsed.length == _count + ? Icons.unfold_more + : Icons.unfold_less, + ), + ), + IconButton( + key: const ValueKey('diff-layout-toggle'), + tooltip: _all ? 'Show one file at a time' : 'Show all files', + onPressed: _toggleLayout, + icon: Icon( + _all ? Icons.article_outlined : Icons.view_agenda_outlined, + ), + ), + ], + ), + body: body, + ); + } +} diff --git a/app/lib/features/changes/widgets/file_diff_viewer.dart b/app/lib/features/changes/widgets/file_diff_viewer.dart index 2d8310b8..dac7419d 100644 --- a/app/lib/features/changes/widgets/file_diff_viewer.dart +++ b/app/lib/features/changes/widgets/file_diff_viewer.dart @@ -1,21 +1,20 @@ -import '../../../ui/adaptive/segmented_bar.dart'; -import '../../../ui/input/arrow_key_pager.dart'; import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import '../../../ui/navigation/chevron_pager.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; -import '../../../ui/adaptive/glass_bar.dart'; import '../domain/change_kind.dart'; import '../domain/change_wording.dart'; import '../domain/file_change.dart'; import '../domain/unified_patch.dart'; import 'change_style.dart'; +import 'diff_highlight.dart'; import 'patch_view.dart'; import 'raw_patch_view.dart'; +export 'file_diff_page.dart'; + /// The reusable viewer for one recorded file change: its kind, path, stat, /// tags, the rendered or raw unified patch, Copy patch (the server's exact /// bytes) and Close. Binary/truncated/mode-only/no-patch entries show an honest @@ -26,10 +25,15 @@ class FileDiffViewer extends StatefulWidget { required this.file, this.onClose, this.floatBehindTopBar = false, + this.scrollController, }); final FileChange file; + /// Scrolls the diff body; the page passes its own so the keyboard can + /// scroll it. + final ScrollController? scrollController; + /// Called by the Close control. Defaults to popping the enclosing route. final VoidCallback? onClose; @@ -212,15 +216,22 @@ class _FileDiffViewerState extends State { if (!file.hasPatch) { return _message(context, patchUnavailableReason(file)); } - if (_form == DiffForm.raw) { + // A search highlights rendered lines, so it shows the rendered form. + final searching = DiffHighlight.maybeOf(context)?.active ?? false; + if (_form == DiffForm.raw && !searching) { return Semantics( container: true, label: 'Raw patch for ${file.path}', value: file.patch, - child: RawPatchView(patch: file.patch!, style: mono), + child: RawPatchView( + patch: file.patch!, + style: mono, + controller: widget.scrollController, + ), ); } return SingleChildScrollView( + controller: widget.scrollController, padding: const EdgeInsets.only(bottom: 16), child: PatchView(file: file), ); @@ -228,6 +239,7 @@ class _FileDiffViewerState extends State { Widget _message(BuildContext context, String text) { return SingleChildScrollView( + controller: widget.scrollController, padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), child: Text(text), ); @@ -242,85 +254,3 @@ class _FileDiffViewerState extends State { /// keeps its usual layout until scaled text or a narrow phone demands more room. Widget _scrollsWhenTooWide(Widget control) => SingleChildScrollView(scrollDirection: Axis.horizontal, child: control); - -/// Open [file] on its own page, as the browser's file view. [files] is the -/// list it was picked from (the visit's shown files); the page steps through -/// them with previous/next chevrons at its bottom right. -Future showFileDiffViewer( - BuildContext context, - FileChange file, { - List? files, -}) { - final list = files == null || !files.contains(file) ? [file] : files; - final page = FileDiffPage(files: list, initialIndex: list.indexOf(file)); - return Navigator.of( - context, - ).push(MaterialPageRoute(builder: (_) => page)); -} - -/// One recorded file's diff as a page, with the previous and next file of the -/// list it came from. -class FileDiffPage extends StatefulWidget { - const FileDiffPage({super.key, required this.files, this.initialIndex = 0}); - - final List files; - final int initialIndex; - - @override - State createState() => _FileDiffPageState(); -} - -class _FileDiffPageState extends State { - late int _index = widget.initialIndex.clamp(0, widget.files.length - 1); - - void _step(int delta) => setState(() => _index += delta); - - @override - Widget build(BuildContext context) { - final file = widget.files[_index]; - final name = file.path.split('/').last; - final count = widget.files.length; - final viewer = FileDiffViewer( - key: ValueKey('file-diff-${file.path}'), - file: file, - floatBehindTopBar: true, - ); - final pager = count < 2 - ? null - : ChevronPager( - key: const ValueKey('file-diff-pager'), - index: _index, - count: count, - previousLabel: 'Previous file', - nextLabel: 'Next file', - onPrevious: _index > 0 ? () => _step(-1) : null, - onNext: _index < count - 1 ? () => _step(1) : null, - ); - // Left/right arrows step between changed files, like the chevrons; - // Escape closes the page, like its back button. - final body = ArrowKeyPager( - onPrevious: _index > 0 ? () => _step(-1) : null, - onNext: _index < count - 1 ? () => _step(1) : null, - onEscape: () => Navigator.of(context).maybePop(), - child: FloatingBarOverlay( - bar: pager == null - ? const SizedBox.shrink() - : Align( - alignment: AlignmentDirectional.centerEnd, - heightFactor: 1, - child: SafeArea( - top: false, - minimum: const EdgeInsets.all(8), - child: GlassControlBar(child: pager), - ), - ), - child: viewer, - ), - ); - return Scaffold( - extendBodyBehindAppBar: true, - appBar: SegmentedBar(title: name), - body: body, - ); - } -} diff --git a/app/lib/features/changes/widgets/patch_view.dart b/app/lib/features/changes/widgets/patch_view.dart index e9b44d20..ab6edaa8 100644 --- a/app/lib/features/changes/widgets/patch_view.dart +++ b/app/lib/features/changes/widgets/patch_view.dart @@ -1,9 +1,11 @@ import 'package:flutter/material.dart'; import '../domain/change_wording.dart'; +import '../domain/diff_search.dart'; import '../domain/file_change.dart'; import '../domain/unified_patch.dart'; import 'change_style.dart'; +import 'diff_highlight.dart'; /// The rendered reading of one recorded unified patch: each hunk's `@@` header, /// the shared diff line language (`+`/`-`/space) and the old/new gutter numbers. @@ -38,7 +40,8 @@ class PatchView extends StatelessWidget { // The web rendered view shows hunks, not the recorded `---`/`+++` // file headers (they stay in the Raw view), so the dialog does not // show a long header clipped at its edge. - for (final hunk in parsed.hunks) _HunkView(hunk: hunk), + for (var index = 0; index < parsed.hunks.length; index++) + _HunkView(hunk: parsed.hunks[index], index: index), ], ), ); @@ -46,9 +49,10 @@ class PatchView extends StatelessWidget { } class _HunkView extends StatelessWidget { - const _HunkView({required this.hunk}); + const _HunkView({required this.hunk, required this.index}); final PatchHunk hunk; + final int index; @override Widget build(BuildContext context) { @@ -80,6 +84,8 @@ class _HunkView extends StatelessWidget { for (var index = 0; index < hunk.lines.length; index++) _LineRow( key: ValueKey('diff-line-$index'), + hunk: this.index, + index: index, line: hunk.lines[index], width: width, base: base, @@ -99,11 +105,15 @@ class _HunkView extends StatelessWidget { class _LineRow extends StatelessWidget { const _LineRow({ super.key, + required this.hunk, + required this.index, required this.line, required this.width, required this.base, }); + final int hunk; + final int index; final PatchLine line; final int width; final TextStyle base; @@ -114,7 +124,7 @@ class _LineRow extends StatelessWidget { ? ' ' * (width * 2 + 1) : '${gutterText(line.oldLine, width)} ${gutterText(line.newLine, width)}'; final colors = diffLineColors(context, line.kind); - return Container( + final row = Container( color: colors.background, padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2), child: Text.rich( @@ -133,15 +143,62 @@ class _LineRow extends StatelessWidget { : FontWeight.w700, ), ), - TextSpan( - text: ' ${line.text}', - style: base.copyWith(color: colors.text), - ), + const TextSpan(text: ' '), + ..._textSpans(context, base.copyWith(color: colors.text)), ], ), softWrap: false, overflow: TextOverflow.visible, ), ); + final highlight = DiffHighlight.maybeOf(context); + final file = DiffFileIndex.maybeOf(context); + final current = highlight?.current; + if (current != null && file != null && current.isOn(file, hunk, index)) { + return KeyedSubtree(key: highlight!.currentKey, child: row); + } + return row; + } + + /// The line's text with every search match marked, the current one + /// strongest. + List _textSpans(BuildContext context, TextStyle style) { + final highlight = DiffHighlight.maybeOf(context); + if (highlight == null || !highlight.active) { + return [TextSpan(text: line.text, style: style)]; + } + final ranges = matchRanges(line.text, highlight.query); + if (ranges.isEmpty) return [TextSpan(text: line.text, style: style)]; + final scheme = Theme.of(context).colorScheme; + final file = DiffFileIndex.maybeOf(context); + final current = highlight.current; + final spans = []; + var at = 0; + for (final (start, end) in ranges) { + if (start > at) { + spans.add(TextSpan(text: line.text.substring(at, start), style: style)); + } + final isCurrent = + current != null && + file != null && + current.isOn(file, hunk, index) && + current.start == start; + spans.add( + TextSpan( + text: line.text.substring(start, end), + style: style.copyWith( + color: isCurrent ? scheme.onTertiary : scheme.onTertiaryContainer, + backgroundColor: isCurrent + ? scheme.tertiary + : scheme.tertiaryContainer, + ), + ), + ); + at = end; + } + if (at < line.text.length) { + spans.add(TextSpan(text: line.text.substring(at), style: style)); + } + return spans; } } diff --git a/app/lib/features/changes/widgets/raw_patch_view.dart b/app/lib/features/changes/widgets/raw_patch_view.dart index ca83d9b0..b4c81d1e 100644 --- a/app/lib/features/changes/widgets/raw_patch_view.dart +++ b/app/lib/features/changes/widgets/raw_patch_view.dart @@ -6,14 +6,21 @@ import 'package:flutter/material.dart'; /// The text keeps its intrinsic line width, so long lines scroll sideways /// instead of wrapping a continuation under a new line. class RawPatchView extends StatelessWidget { - const RawPatchView({super.key, required this.patch, required this.style}); + const RawPatchView({ + super.key, + required this.patch, + required this.style, + this.controller, + }); final String patch; final TextStyle style; + final ScrollController? controller; @override Widget build(BuildContext context) { return SingleChildScrollView( + controller: controller, padding: const EdgeInsets.fromLTRB(16, 0, 16, 16), child: SingleChildScrollView( scrollDirection: Axis.horizontal, diff --git a/app/lib/features/changes/widgets/stacked_diff_view.dart b/app/lib/features/changes/widgets/stacked_diff_view.dart new file mode 100644 index 00000000..5cbc64e6 --- /dev/null +++ b/app/lib/features/changes/widgets/stacked_diff_view.dart @@ -0,0 +1,149 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/floating_bar_layout.dart'; +import '../domain/change_wording.dart'; +import '../domain/file_change.dart'; +import '../domain/unified_patch.dart'; +import 'capture_section.dart' show changeKindIcon; +import 'change_style.dart'; +import 'diff_highlight.dart'; +import 'patch_view.dart'; + +/// Every file of a diff one below the other, like a pull request's Files +/// changed tab: each file has a header that collapses or expands its patch. +/// [headerKeys] (one per file) let the page jump between files. +class StackedDiffView extends StatelessWidget { + const StackedDiffView({ + super.key, + required this.files, + required this.collapsed, + required this.onToggle, + required this.controller, + required this.headerKeys, + }); + + final List files; + final Set collapsed; + final ValueChanged onToggle; + final ScrollController controller; + final List headerKeys; + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + key: const ValueKey('stacked-diff'), + controller: controller, + padding: withTopBarClearance( + context, + const EdgeInsets.fromLTRB(8, 8, 8, 96), + ), + child: Align( + alignment: Alignment.topCenter, + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 1100), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (var index = 0; index < files.length; index++) + Padding( + padding: const EdgeInsets.only(bottom: 12), + child: _FileSection( + key: ValueKey('stacked-diff-file-${files[index].path}'), + headerKey: headerKeys[index], + index: index, + file: files[index], + expanded: !collapsed.contains(index), + onToggle: () => onToggle(index), + ), + ), + ], + ), + ), + ), + ); + } +} + +class _FileSection extends StatelessWidget { + const _FileSection({ + super.key, + required this.headerKey, + required this.index, + required this.file, + required this.expanded, + required this.onToggle, + }); + + final GlobalKey headerKey; + final int index; + final FileChange file; + final bool expanded; + final VoidCallback onToggle; + + @override + Widget build(BuildContext context) { + final mono = nativeDiffText(DefaultTextStyle.of(context).style); + final stat = changeStat(file.added, file.removed); + final header = Semantics( + key: headerKey, + button: true, + expanded: expanded, + label: '${expanded ? 'Collapse' : 'Expand'} ${file.path}', + excludeSemantics: true, + onTap: onToggle, + child: InkWell( + onTap: onToggle, + child: Padding( + padding: const EdgeInsets.fromLTRB(8, 8, 12, 8), + child: Row( + children: [ + Icon(expanded ? Icons.expand_more : Icons.chevron_right), + const SizedBox(width: 4), + Icon(changeKindIcon(file.kind), size: 20), + const SizedBox(width: 8), + Expanded( + child: Text( + file.path, + style: mono, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + if (stat.isNotEmpty) ...[ + const SizedBox(width: 12), + ChangeStatText(stat, style: mono), + ], + ], + ), + ), + ), + ); + return Card.outlined( + margin: EdgeInsets.zero, + clipBehavior: Clip.antiAlias, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + header, + if (expanded) ...[ + const Divider(height: 1), + DiffFileIndex(index: index, child: _body(context)), + ], + ], + ), + ); + } + + Widget _body(BuildContext context) { + final reason = noPatchReasonMessage(file.noPatchReason); + final message = file.binary && reason == null + ? binaryDiffMessage + : !file.hasPatch + ? patchUnavailableReason(file) + : null; + if (message != null) { + return Padding(padding: const EdgeInsets.all(12), child: Text(message)); + } + return PatchView(file: file); + } +} diff --git a/app/test/features/changes/file_diff_page_test.dart b/app/test/features/changes/file_diff_page_test.dart new file mode 100644 index 00000000..92eeba2d --- /dev/null +++ b/app/test/features/changes/file_diff_page_test.dart @@ -0,0 +1,167 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/changes/changes.dart'; +import 'package:pipelines_app/features/changes/domain/diff_search.dart'; + +FileChange _file(String path, {int lines = 3, String word = 'alpha'}) { + final body = [for (var i = 0; i < lines; i++) '+$word line $i'].join('\n'); + return FileChange( + path: path, + kind: ChangeKind.modified, + patch: '--- a/$path\n+++ b/$path\n@@ -0,0 +1,$lines @@\n$body\n', + ); +} + +Future _pump(WidgetTester tester, List files) async { + tester.view.physicalSize = const Size(1000, 700); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + diffShowsAllFiles.value = false; + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => + showFileDiffViewer(context, files.first, files: files), + child: const Text('open'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); +} + +Future _key(WidgetTester tester, LogicalKeyboardKey key) async { + await tester.sendKeyEvent(key); + await tester.pumpAndSettle(); +} + +ScrollPosition _scrollOf(WidgetTester tester, Finder within) { + final scrollable = tester.widgetList( + find.descendant(of: within, matching: find.byType(Scrollable)), + ); + final state = tester.state( + find.byWidget( + scrollable.firstWhere((s) => s.axisDirection == AxisDirection.down), + ), + ); + return state.position; +} + +void main() { + test('search finds every case-insensitive occurrence in reading order', () { + final matches = diffMatches([ + _file('a', lines: 2, word: 'Alpha alpha'), + _file('b', lines: 1, word: 'beta'), + ], 'ALPHA'); + expect(matches, hasLength(4)); + expect(matches.first.file, 0); + expect(diffMatches([_file('a')], ' '), isEmpty); + expect(firstMatchFrom(matches, 1), 0); + }); + + testWidgets('h and l step between files like the arrows', (tester) async { + await _pump(tester, [_file('lib/one.dart'), _file('lib/two.dart')]); + expect(find.text('one.dart'), findsWidgets); + await _key(tester, LogicalKeyboardKey.keyL); + expect(find.text('two.dart'), findsWidgets); + await _key(tester, LogicalKeyboardKey.keyH); + expect(find.text('one.dart'), findsWidgets); + }); + + testWidgets('j, k and the up/down arrows scroll the diff', (tester) async { + await _pump(tester, [_file('lib/long.dart', lines: 200)]); + final viewer = find.byType(FileDiffViewer); + expect(_scrollOf(tester, viewer).pixels, 0); + await _key(tester, LogicalKeyboardKey.keyJ); + await _key(tester, LogicalKeyboardKey.arrowDown); + expect(_scrollOf(tester, viewer).pixels, diffScrollStep * 2); + await _key(tester, LogicalKeyboardKey.keyK); + expect(_scrollOf(tester, viewer).pixels, diffScrollStep); + await _key(tester, LogicalKeyboardKey.arrowUp); + expect(_scrollOf(tester, viewer).pixels, 0); + }); + + testWidgets('/ searches across files; typed letters stay in the field', ( + tester, + ) async { + await _pump(tester, [ + _file('lib/one.dart', word: 'alpha'), + _file('lib/two.dart', word: 'hello'), + ]); + await _key(tester, LogicalKeyboardKey.slash); + expect(find.byKey(const ValueKey('diff-search-field')), findsOneWidget); + await tester.enterText( + find.byKey(const ValueKey('diff-search-field')), + 'hello', + ); + await tester.pumpAndSettle(); + // The only matches are in the second file, so the page moves there. + expect(find.text('two.dart'), findsWidgets); + expect(find.text('1 of 3'), findsOneWidget); + // An h typed into the field must not change file. + await _key(tester, LogicalKeyboardKey.keyH); + expect(find.text('two.dart'), findsWidgets); + + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pumpAndSettle(); + expect(find.text('2 of 3'), findsOneWidget); + + // Escape closes the search first, then leaves the page. + await _key(tester, LogicalKeyboardKey.escape); + expect(find.byKey(const ValueKey('diff-search-field')), findsNothing); + await _key(tester, LogicalKeyboardKey.keyN); + await _key(tester, LogicalKeyboardKey.escape); + expect(find.byType(FileDiffPage), findsNothing); + }); + + testWidgets('all files stacks every file with collapsible headers', ( + tester, + ) async { + await _pump(tester, [ + _file('lib/one.dart', word: 'alpha'), + _file('lib/two.dart', word: 'gamma'), + ]); + await tester.tap(find.byKey(const ValueKey('diff-layout-toggle'))); + await tester.pumpAndSettle(); + expect(find.text('2 files changed'), findsWidgets); + expect(find.text('lib/one.dart'), findsOneWidget); + expect(find.text('lib/two.dart'), findsOneWidget); + expect(find.byKey(const ValueKey('file-diff-pager')), findsNothing); + expect( + find.textContaining('gamma line 0', findRichText: true), + findsOneWidget, + ); + + await tester.tap(find.text('lib/two.dart')); + await tester.pumpAndSettle(); + expect( + find.textContaining('gamma line 0', findRichText: true), + findsNothing, + ); + + // Searching reopens the collapsed file that holds the match. + await _key(tester, LogicalKeyboardKey.slash); + await tester.enterText( + find.byKey(const ValueKey('diff-search-field')), + 'gamma', + ); + await tester.pumpAndSettle(); + expect(find.textContaining('gamma', findRichText: true), findsWidgets); + + await tester.tap(find.byKey(const ValueKey('diff-collapse-all'))); + await tester.pumpAndSettle(); + expect( + find.textContaining('alpha line 0', findRichText: true), + findsNothing, + ); + diffShowsAllFiles.value = false; + }); +}