feat(app): add run change captures and native diff viewer

This commit is contained in:
2026-10-21 18:26:53 +01:00
parent 160ab45fe0
commit 15cca17aa4
25 changed files with 4658 additions and 0 deletions
@@ -0,0 +1,238 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../domain/change_capture.dart';
import '../domain/change_kind.dart';
import '../domain/change_wording.dart';
import '../domain/file_change.dart';
import 'change_style.dart';
/// One stage/visit capture: its honest status, scope, counters and diagnostic,
/// followed by the recorded file rows. Missing and unavailable captures are
/// shown as evidence gaps, never as an observed no-change.
class StageCaptureSection extends StatelessWidget {
const StageCaptureSection({
super.key,
required this.stage,
required this.query,
required this.onOpen,
});
final StageCapture stage;
final String query;
final ValueChanged<FileChange> onOpen;
@override
Widget build(BuildContext context) {
final capture = stage.capture;
final filtered = capture == null
? const <FileChange>[]
: filterFileChanges(capture.files, query);
// The aggregate trims and lowercases the status before testing it; do the
// same here so the section and the run header always agree.
final status = stage.stepStatus.trim().toLowerCase();
final pending =
capture == null && (status == 'running' || status == 'waiting');
final meta = [
'Visit ${stage.visit}',
if (stage.stepStatus.isNotEmpty) stage.stepStatus,
].join(' · ');
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(stage.stage, style: Theme.of(context).textTheme.titleMedium),
Text(meta, style: Theme.of(context).textTheme.bodySmall),
if (capture != null) ...[
Text(
fileChangesSummary(capture),
style: Theme.of(context).textTheme.bodySmall,
),
if (capture.scope.isNotEmpty)
Text(
'Scope: ${capture.scope}',
style: Theme.of(context).textTheme.bodySmall,
),
],
],
),
),
const Divider(height: 1),
if (capture == null)
_CaptureNote(
icon: _noteIcon(
context,
pending ? _NoteKind.pending : _NoteKind.missing,
),
title: pending ? 'Capture pending' : 'Capture unavailable',
detail: pending ? pendingCaptureDetail : missingCaptureDetail,
)
else if (capture.unavailable)
_CaptureNote(
icon: _noteIcon(context, _NoteKind.unavailable),
title: 'Capture unavailable',
detail: capture.diagnostic.isEmpty
? unavailableCaptureDetail
: capture.diagnostic,
)
else if (capture.files.isEmpty)
_CaptureNote(
icon: _noteIcon(
context,
capture.partial ? _NoteKind.partial : _NoteKind.empty,
),
title: capture.partial ? 'Partial capture' : 'No changes observed',
detail: capture.partial ? partialCaptureDetail : emptyCaptureDetail,
)
else if (filtered.isEmpty)
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
child: Text('No changed filenames match "$query".'),
)
else
for (final file in filtered)
_FileRow(
key: ValueKey('change-${stage.sequence}-${file.path}'),
file: file,
onOpen: onOpen,
),
],
);
}
}
class _FileRow extends StatelessWidget {
const _FileRow({super.key, required this.file, required this.onOpen});
final FileChange file;
final ValueChanged<FileChange> onOpen;
@override
Widget build(BuildContext context) {
final mono = monospaceText(DefaultTextStyle.of(context).style);
final cupertino = usesCupertino(context);
final leading = Icon(_kindIcon(context, file.kind));
final title = Text(file.path, style: mono);
final subtitle = Text(changeFileMeta(file));
final trailing = cupertino
? const CupertinoListTileChevron()
: const Icon(Icons.chevron_right);
return Semantics(
container: true,
button: true,
// Announce the visible kind and meta too; the row's icon and subtitle are
// excluded from the semantic tree by [excludeSemantics].
label:
'Open diff for ${file.path}. '
'${changeKindTitle(file.kind)} · ${changeFileMeta(file)}',
excludeSemantics: true,
onTap: () => onOpen(file),
child: cupertino
? CupertinoListTile(
leading: leading,
// A recorded path is the row's identity, so it wraps instead of
// being ellipsized to one line.
title: _unclampedText(title),
subtitle: _unclampedText(subtitle),
trailing: trailing,
onTap: () => onOpen(file),
)
: ListTile(
leading: leading,
title: title,
subtitle: subtitle,
trailing: trailing,
onTap: () => onOpen(file),
),
);
}
}
/// CupertinoListTile caps its title and subtitle at one ellipsized line through
/// the inherited [DefaultTextStyle]. Re-establish the ambient style without that
/// cap so a long recorded path stays readable; the tile keeps its native
/// padding, pressed state and chevron.
Widget _unclampedText(Widget child) {
return Builder(
builder: (context) {
final inherited = DefaultTextStyle.of(context);
return DefaultTextStyle(
style: inherited.style,
softWrap: true,
overflow: TextOverflow.visible,
textAlign: inherited.textAlign,
textWidthBasis: inherited.textWidthBasis,
textHeightBehavior: inherited.textHeightBehavior,
child: child,
);
},
);
}
class _CaptureNote extends StatelessWidget {
const _CaptureNote({
required this.icon,
required this.title,
required this.detail,
});
final IconData icon;
final String title;
final String detail;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: Theme.of(context).textTheme.titleSmall),
const SizedBox(height: 4),
Text(detail),
],
),
),
],
),
);
}
}
enum _NoteKind { missing, unavailable, empty, partial, pending }
IconData _noteIcon(BuildContext context, _NoteKind kind) {
final cupertino = usesCupertino(context);
return switch (kind) {
_NoteKind.missing || _NoteKind.unavailable =>
cupertino ? CupertinoIcons.exclamationmark_triangle : Icons.warning_amber,
_NoteKind.empty =>
cupertino ? CupertinoIcons.checkmark_circle : Icons.check_circle_outline,
_NoteKind.partial => cupertino ? CupertinoIcons.info : Icons.info_outline,
_NoteKind.pending => cupertino ? CupertinoIcons.clock : Icons.schedule,
};
}
IconData _kindIcon(BuildContext context, ChangeKind kind) {
final cupertino = usesCupertino(context);
return switch (kind) {
ChangeKind.added =>
cupertino ? CupertinoIcons.add_circled : Icons.add_circle_outline,
ChangeKind.deleted =>
cupertino ? CupertinoIcons.trash : Icons.delete_outline,
ChangeKind.modified =>
cupertino ? CupertinoIcons.pencil : Icons.edit_outlined,
ChangeKind.other =>
cupertino ? CupertinoIcons.doc : Icons.description_outlined,
};
}
@@ -0,0 +1,166 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../domain/unified_patch.dart';
/// Which form of a recorded patch the viewer is showing.
enum DiffForm { rendered, raw }
/// The bundled code face (`assets/fonts/RobotoMono.ttf`, SIL OFL 1.1). Flutter
/// web cannot resolve a system monospace family, so the app carries one and
/// every target renders patch text the same way. The fallbacks are only for
/// hosts that cannot load the asset.
const codeFontFamily = 'RobotoMono';
/// The app's established platform switch: Material for Android/desktop/web,
/// Cupertino for iOS and macOS. Feature widgets stay portable across all three
/// targets instead of hard-coding one control set.
bool usesCupertino(BuildContext context) {
final platform = Theme.of(context).platform;
return platform == TargetPlatform.iOS || platform == TargetPlatform.macOS;
}
/// The app's code face for patch text. The size, weight and text scaler come
/// from the caller's theme style, so code follows the operator's text size.
TextStyle monospaceText(TextStyle base) => base.copyWith(
fontFamily: codeFontFamily,
fontFamilyFallback: const ['Menlo', 'Consolas', 'Courier New', 'monospace'],
);
/// The distinguishable success/removal colours shared by the stat line and the
/// diff rows. A theme-aware green/red pair, never two shades of the same hue:
/// the light Material containers alone made additions and removals read alike.
({Color text, Color? background}) diffLineColors(
BuildContext context,
ChangeLineKind kind,
) {
final dark = usesCupertino(context)
? CupertinoTheme.of(context).brightness == Brightness.dark
: Theme.of(context).brightness == Brightness.dark;
return switch (kind) {
ChangeLineKind.add =>
dark
? (text: const Color(0xFF7FE0A8), background: const Color(0x297FE0A8))
: (
text: const Color(0xFF116B33),
background: const Color(0xFFE3F3E7),
),
ChangeLineKind.remove =>
dark
? (text: const Color(0xFFFF9E9E), background: const Color(0x29FF9E9E))
: (
text: const Color(0xFFB3261E),
background: const Color(0xFFFBE7E5),
),
ChangeLineKind.context => (text: labelColor(context), background: null),
};
}
/// The plain body/label colour for non-diff text inside the viewer.
Color labelColor(BuildContext context) => usesCupertino(context)
? CupertinoColors.label.resolveFrom(context)
: Theme.of(context).colorScheme.onSurface;
/// The muted colour for gutters, notes and secondary metadata.
Color mutedColor(BuildContext context) => usesCupertino(context)
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
/// The hunk header's fill.
Color hunkHeaderColor(BuildContext context) => usesCupertino(context)
? CupertinoColors.tertiarySystemFill.resolveFrom(context)
: Theme.of(context).colorScheme.surfaceContainerHighest;
/// The viewer's shared Rendered/Raw control: a native segmented control on each
/// platform, with the same two words the browser uses.
Widget diffFormControl(
BuildContext context, {
required DiffForm form,
required ValueChanged<DiffForm> onChanged,
}) {
if (usesCupertino(context)) {
return CupertinoSlidingSegmentedControl<DiffForm>(
groupValue: form,
onValueChanged: (value) {
if (value != null) onChanged(value);
},
children: const {
DiffForm.rendered: _SegmentLabel('Rendered'),
DiffForm.raw: _SegmentLabel('Raw patch'),
},
);
}
return SegmentedButton<DiffForm>(
segments: const [
ButtonSegment(value: DiffForm.rendered, label: Text('Rendered')),
ButtonSegment(value: DiffForm.raw, label: Text('Raw patch')),
],
selected: {form},
showSelectedIcon: false,
onSelectionChanged: (selection) {
if (selection.isNotEmpty) onChanged(selection.first);
},
);
}
class _SegmentLabel extends StatelessWidget {
const _SegmentLabel(this.label);
final String label;
@override
Widget build(BuildContext context) =>
Padding(padding: const EdgeInsets.all(6), child: Text(label));
}
/// Copy the server's raw patch exactly as recorded. Disabled when the entry has
/// no readable patch, so the action never copies a fabricated empty diff.
Widget copyPatchControl(
BuildContext context, {
required bool enabled,
required bool copied,
required VoidCallback onPressed,
}) {
final label = copied ? 'Copied' : 'Copy patch';
if (usesCupertino(context)) {
return CupertinoButton(
padding: EdgeInsets.zero,
onPressed: enabled ? onPressed : null,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(CupertinoIcons.doc_on_doc),
const SizedBox(width: 8),
Text(label),
],
),
);
}
return TextButton.icon(
onPressed: enabled ? onPressed : null,
icon: const Icon(Icons.copy_all_outlined),
label: Text(label),
);
}
/// The standard close action, labelled exactly on both platforms.
Widget closeDiffControl(BuildContext context, VoidCallback onClose) {
if (usesCupertino(context)) {
return Semantics(
label: 'Close diff',
button: true,
excludeSemantics: true,
onTap: onClose,
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onClose,
child: const Icon(CupertinoIcons.xmark),
),
);
}
return IconButton(
tooltip: 'Close diff',
onPressed: onClose,
icon: const Icon(Icons.close),
);
}
@@ -0,0 +1,189 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/change_capture.dart';
import '../domain/change_wording.dart';
import '../domain/run_changes.dart';
import 'capture_section.dart';
import 'change_style.dart';
import 'file_diff_viewer.dart';
/// The run's Changes surface: an honest final-state summary followed by one
/// section per stage/visit capture, with changed-filename filtering and the
/// reusable single-file diff viewer.
///
/// The viewer fills the available height, so give it a bounded parent (a
/// Scaffold body, tab body or Expanded child). It never opens its own socket or
/// requests data; the caller passes the run detail's `steps`.
class ChangesViewer extends StatefulWidget {
const ChangesViewer({super.key, required this.steps});
/// The run detail's steps exactly as the server returned them. Each step's
/// `file_changes` may be null (no capture), a complete/partial/unavailable
/// capture, or a capture with zero files (a recorded no-change).
///
/// Pass a stable list: the same instance until the server reply changes. The
/// captures and the summary are derived from it rather than on every rebuild.
final List<JsonMap> steps;
@override
State<ChangesViewer> createState() => _ChangesViewerState();
}
class _ChangesViewerState extends State<ChangesViewer> {
final _filter = TextEditingController();
late List<StageCapture> _captures;
late RunChanges _run;
@override
void initState() {
super.initState();
_derive();
}
@override
void didUpdateWidget(ChangesViewer oldWidget) {
super.didUpdateWidget(oldWidget);
// Filter keystrokes rebuild this widget with the same steps list; only a
// new server reply re-derives the captures and the aggregate.
if (!identical(oldWidget.steps, widget.steps)) _derive();
}
void _derive() {
_captures = stageCaptures(widget.steps);
_run = runChangesFor(_captures);
}
@override
void dispose() {
_filter.dispose();
super.dispose();
}
String get _query => _filter.text;
@override
Widget build(BuildContext context) {
final run = _run;
final captures = _captures;
final hasFiles = captures.any(
(visit) => visit.capture?.files.isNotEmpty ?? false,
);
final note = runChangesNote(run);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
runChangesHeader(run),
style: Theme.of(context).textTheme.titleMedium,
),
if (note.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
note,
style: Theme.of(context).textTheme.bodySmall,
),
),
if (hasFiles)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
'The summary counts each path once, as the last recorded '
'visit left it. Each stage/visit below lists what its own '
'capture recorded.',
style: Theme.of(context).textTheme.bodySmall,
),
),
],
),
),
if (hasFiles)
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: _filterField(context, run),
),
const Divider(height: 1),
Expanded(
child: captures.isEmpty
? SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Text(noChangeDetail(run)),
)
: ListView.builder(
itemCount: captures.length,
itemBuilder: (context, index) {
final visit = captures[index];
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
StageCaptureSection(
stage: visit,
query: _query,
onOpen: (file) => showFileDiffViewer(context, file),
),
const Divider(height: 1),
],
);
},
),
),
],
);
}
Widget _filterField(BuildContext context, RunChanges run) {
final query = _query;
final matched = query.trim().isEmpty
? run.files.length
: filterFileChanges(run.files, query).length;
// The summary counts paths while the sections below list one row per stage
// visit, so the counter names what it actually counts.
final counter = query.trim().isEmpty
? ''
: '$matched of ${run.files.length} changed '
'${run.files.length == 1 ? 'path' : 'paths'} match';
final field = usesCupertino(context)
? CupertinoSearchTextField(
controller: _filter,
placeholder: 'Filter changed files',
onChanged: (_) => setState(() {}),
)
: TextField(
controller: _filter,
decoration: InputDecoration(
labelText: 'Filter changed files',
hintText: 'Filename contains…',
prefixIcon: const Icon(Icons.search),
suffixIcon: query.isEmpty
? null
: IconButton(
tooltip: 'Clear filter',
onPressed: () {
_filter.clear();
setState(() {});
},
icon: const Icon(Icons.clear),
),
),
onChanged: (_) => setState(() {}),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
field,
if (counter.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(counter, style: Theme.of(context).textTheme.bodySmall),
),
],
);
}
}
@@ -0,0 +1,254 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.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 'patch_view.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
/// reason instead of a fabricated diff.
class FileDiffViewer extends StatefulWidget {
const FileDiffViewer({super.key, required this.file, this.onClose});
final FileChange file;
/// Called by the Close control. Defaults to popping the enclosing route.
final VoidCallback? onClose;
@override
State<FileDiffViewer> createState() => _FileDiffViewerState();
}
class _FileDiffViewerState extends State<FileDiffViewer> {
DiffForm _form = DiffForm.rendered;
bool _copied = false;
Timer? _copyTimer;
@override
void dispose() {
_copyTimer?.cancel();
super.dispose();
}
void _close() {
final close = widget.onClose;
if (close != null) {
close();
} else {
Navigator.of(context).maybePop();
}
}
Future<void> _copy() async {
final patch = widget.file.patch;
if (patch == null) return;
await Clipboard.setData(ClipboardData(text: patch));
if (!mounted) return;
setState(() => _copied = true);
_copyTimer?.cancel();
_copyTimer = Timer(const Duration(seconds: 2), () {
if (mounted) setState(() => _copied = false);
});
}
@override
Widget build(BuildContext context) {
final file = widget.file;
final cupertino = usesCupertino(context);
final base = DefaultTextStyle.of(context).style;
final mono = monospaceText(base);
final stat = changeStat(file.added, file.removed);
final tags = changeEntryTags(file);
return ConstrainedBox(
key: const ValueKey('file-diff-viewer'),
constraints: BoxConstraints(
maxWidth: 900,
maxHeight: MediaQuery.sizeOf(context).height * 0.85,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 8, 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Semantics(
container: true,
header: true,
excludeSemantics: true,
label: [
changeKindTitle(file.kind),
if (stat.isNotEmpty) stat,
if (tags.isNotEmpty) tags.join(' · '),
'for ${file.path}',
if (file.steps.isNotEmpty)
'changed by ${file.steps.join(' → ')}',
if (file.modeChanged && !file.binary)
'mode ${file.beforeMode ?? ''}→'
'${file.afterMode ?? ''}',
].join(', '),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
spacing: 12,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text(
changeKindTitle(file.kind),
style: Theme.of(context).textTheme.titleMedium,
),
if (stat.isNotEmpty) Text(stat, style: mono),
if (tags.isNotEmpty)
Text(
tags.join(' · '),
style: Theme.of(context).textTheme.bodySmall,
),
],
),
const SizedBox(height: 4),
Text(file.path, style: mono),
if (file.steps.isNotEmpty)
Text(
'changed by ${file.steps.join(' → ')}',
style: Theme.of(context).textTheme.bodySmall,
),
if (file.modeChanged && !file.binary)
Text(
'mode ${file.beforeMode ?? ''}→'
'${file.afterMode ?? ''}',
style: Theme.of(context).textTheme.bodySmall,
),
],
),
),
),
closeDiffControl(context, _close),
],
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Wrap(
spacing: 8,
runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (file.hasPatch)
diffFormControl(
context,
form: _form,
onChanged: (value) => setState(() => _form = value),
),
copyPatchControl(
context,
enabled: file.hasPatch,
copied: _copied,
onPressed: _copy,
),
],
),
),
Divider(
height: 16,
color: cupertino
? CupertinoColors.separator.resolveFrom(context)
: Theme.of(context).dividerColor,
),
Flexible(child: _body(context, cupertino, mono)),
],
),
);
}
Widget _body(BuildContext context, bool cupertino, TextStyle mono) {
final file = widget.file;
if (file.binary) return _message(context, binaryDiffMessage);
if (!file.hasPatch) {
return _message(context, patchUnavailableReason(file));
}
if (_form == DiffForm.raw) {
return Semantics(
container: true,
label: 'Raw patch for ${file.path}',
value: file.patch,
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: SingleChildScrollView(
// Raw patch bytes are one line each: scroll them sideways like the
// web view instead of wrapping a continuation under a new line.
scrollDirection: Axis.horizontal,
child: ExcludeSemantics(
child: SelectionArea(
child: Text(
file.patch!,
style: mono,
softWrap: false,
overflow: TextOverflow.visible,
),
),
),
),
),
);
}
return SingleChildScrollView(
padding: const EdgeInsets.only(bottom: 16),
child: PatchView(file: file),
);
}
Widget _message(BuildContext context, String text) {
return SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
child: Text(text),
);
}
}
/// Open [file] in the platform's standard modal: a Material dialog on
/// Android/desktop/web, a Cupertino dialog with a popup surface on iOS/macOS.
Future<void> showFileDiffViewer(BuildContext context, FileChange file) {
final cupertino = usesCupertino(context);
Widget buildDialog(BuildContext dialogContext) {
final viewer = FileDiffViewer(
file: file,
onClose: () => Navigator.of(dialogContext).pop(),
);
if (cupertino) {
// A popup surface spans the window unless it is inset; on a phone the
// screen edge would clip its native rounded corners.
final width = MediaQuery.sizeOf(dialogContext).width;
return Padding(
padding: EdgeInsets.symmetric(
horizontal: width < 600 ? 16 : 40,
vertical: 24,
),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 900),
child: CupertinoPopupSurface(child: SafeArea(child: viewer)),
),
),
);
}
return Dialog(child: SafeArea(child: viewer));
}
if (cupertino) {
return showCupertinoDialog<void>(context: context, builder: buildDialog);
}
return showDialog<void>(context: context, builder: buildDialog);
}
@@ -0,0 +1,193 @@
import 'package:flutter/material.dart';
import '../domain/change_wording.dart';
import '../domain/file_change.dart';
import '../domain/unified_patch.dart';
import 'change_style.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.
/// This is the only custom drawing in the feature; everything around it is a
/// standard platform control.
class PatchView extends StatelessWidget {
const PatchView({super.key, required this.file});
final FileChange file;
@override
Widget build(BuildContext context) {
final parsed = file.parsedPatch;
final base = monospaceText(DefaultTextStyle.of(context).style);
final stat = changeStat(parsed.added, parsed.removed);
return Semantics(
container: true,
label: 'Rendered diff for ${file.path}',
value: stat.isEmpty ? noLineChangesMessage : stat,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: ExcludeSemantics(
child: _StatLine(
added: parsed.added,
removed: parsed.removed,
base: base,
),
),
),
if (file.truncated)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: Text(
truncatedPatchNote,
style: base.copyWith(color: mutedColor(context)),
),
),
// 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),
],
),
);
}
}
/// `+N` in the add colour and `-M` in the remove colour, or the honest note when
/// the patch records no changed line.
class _StatLine extends StatelessWidget {
const _StatLine({
required this.added,
required this.removed,
required this.base,
});
final int added;
final int removed;
final TextStyle base;
@override
Widget build(BuildContext context) {
if (added == 0 && removed == 0) {
return Text(
noLineChangesMessage,
style: base.copyWith(color: mutedColor(context)),
);
}
return Text.rich(
TextSpan(
children: [
if (added > 0)
TextSpan(
text: '+$added',
style: base.copyWith(
color: diffLineColors(context, ChangeLineKind.add).text,
),
),
if (added > 0 && removed > 0) TextSpan(text: ' ', style: base),
if (removed > 0)
TextSpan(
text: '-$removed',
style: base.copyWith(
color: diffLineColors(context, ChangeLineKind.remove).text,
),
),
],
),
);
}
}
class _HunkView extends StatelessWidget {
const _HunkView({required this.hunk});
final PatchHunk hunk;
@override
Widget build(BuildContext context) {
final base = monospaceText(DefaultTextStyle.of(context).style);
final width = gutterWidth(hunk);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
color: hunkHeaderColor(context),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Text(hunk.header, style: base),
),
LayoutBuilder(
builder: (context, constraints) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: ConstrainedBox(
// At least the dialog's width, so a short hunk still paints
// full-width bands; wider content scrolls sideways.
constraints: BoxConstraints(minWidth: constraints.maxWidth),
// The widest recorded line sets the hunk's content width, so
// every line tint is a full-width band instead of a bar as long
// as its own text.
child: IntrinsicWidth(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (var index = 0; index < hunk.lines.length; index++)
_LineRow(
key: ValueKey('diff-line-$index'),
line: hunk.lines[index],
width: width,
base: base,
),
],
),
),
),
);
},
),
],
);
}
}
class _LineRow extends StatelessWidget {
const _LineRow({
super.key,
required this.line,
required this.width,
required this.base,
});
final PatchLine line;
final int width;
final TextStyle base;
@override
Widget build(BuildContext context) {
final gutter = line.noNewlineMarker
? ' ' * (width * 2 + 1)
: '${gutterText(line.oldLine, width)} ${gutterText(line.newLine, width)}';
final colors = diffLineColors(context, line.kind);
final content = '${diffLineSymbol(line.kind)} ${line.text}';
return Container(
color: colors.background,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
child: Text.rich(
TextSpan(
children: [
TextSpan(
text: gutter,
style: base.copyWith(color: mutedColor(context)),
),
TextSpan(
text: content,
style: base.copyWith(color: colors.text),
),
],
),
softWrap: false,
overflow: TextOverflow.visible,
),
);
}
}