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'; import '../windows/diff_windows.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)); // The page may sit above the shell: carry the app's diff windows into it // so it can offer Open in a window. final windows = DiffWindowsScope.windowsOf(context); return Navigator.of(context).push( MaterialPageRoute( builder: (_) => windows == null ? page : DiffWindowsScope(windows: windows, child: 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, this.inWindow = false, }); final List files; final int initialIndex; /// Shown inside a floating window: no Back, and no Open in a window. final bool inWindow; @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), ); } } /// Leaves the page and shows the same files, on the same file, in a /// floating window. void _openInWindow(DiffWindows windows) { Navigator.of(context).maybePop(); windows.open(widget.files, initialIndex: _index); } 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, automaticallyImplyLeading: !widget.inWindow, actions: [ if (!widget.inWindow) ?switch (DiffWindowsScope.maybeOf(context)) { final windows? => IconButton( key: const ValueKey('diff-open-window'), tooltip: 'Open in a window', onPressed: () => _openInWindow(windows), icon: const Icon(Icons.open_in_new), ), null => null, }, 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, ); } }