merge(app): land recorded changes viewer with native-default corrections

This commit is contained in:
2026-10-21 18:40:55 +01:00
22 changed files with 4511 additions and 0 deletions
+17
View File
@@ -0,0 +1,17 @@
/// Public API for the run Changes feature. Integration imports this barrel:
///
/// * [ChangesViewer] - the whole run, from `run detail['steps']`.
/// * [FileDiffViewer] and [showFileDiffViewer] - one recorded file.
/// * The pure domain models/parsers/wording for tests and other surfaces.
library;
export 'domain/change_capture.dart';
export 'domain/change_kind.dart';
export 'domain/change_wording.dart';
export 'domain/file_change.dart';
export 'domain/run_changes.dart';
export 'domain/unified_patch.dart';
export 'widgets/change_style.dart' show DiffForm, usesCupertino;
export 'widgets/changes_viewer.dart';
export 'widgets/file_diff_viewer.dart';
export 'widgets/patch_view.dart';
@@ -0,0 +1,145 @@
import '../../../core/api_gateway.dart';
import 'file_change.dart';
/// One step's recorded `file_changes` capture. A null capture on a
/// [StageCapture] means the step recorded no capture at all - it must never be
/// read as "the workspace was unchanged".
class ChangeCapture {
ChangeCapture({
required this.status,
this.scope = '',
required this.files,
this.skipped = 0,
this.omitted = 0,
this.diagnostic = '',
});
final String status;
final String scope;
final List<FileChange> files;
final int skipped;
final int omitted;
final String diagnostic;
String get _state => status.trim().toLowerCase();
bool get unavailable => _state == 'unavailable';
bool get partial => _state == 'partial';
bool get complete => _state == 'complete' || _state.isEmpty;
bool get hasFiles => files.isNotEmpty;
factory ChangeCapture.fromJson(JsonMap json) {
final rawFiles = json['files'];
final files = <FileChange>[];
if (rawFiles is List) {
for (final value in rawFiles) {
final file = FileChange.tryParse(value);
if (file != null) files.add(file);
}
}
return ChangeCapture(
status: '${json['status'] ?? ''}'.trim(),
scope: '${json['scope'] ?? ''}'.trim(),
files: List.unmodifiable(files),
skipped: _count(json['skipped']),
omitted: _count(json['omitted']),
diagnostic: '${json['diagnostic'] ?? ''}'.trim(),
);
}
}
/// The honest wording for a `file_changes` value that exists but is not an
/// object. Such a record is unreadable evidence, not an observed no-change.
const malformedCaptureDetail =
'The recorded change capture could not be read, so no changes can be '
'shown. This does not mean the workspace was unchanged.';
/// One stage visit and the capture it recorded, in run order. `capture == null`
/// is missing evidence, not an observed no-change.
class StageCapture {
const StageCapture({
required this.sequence,
required this.visit,
required this.stage,
required this.stepStatus,
required this.capture,
});
/// The run-wide step ordinal, used for ordering and widget keys.
final int sequence;
/// The display visit number within [stage]: the recorded `control.visit` when
/// positive, otherwise the visit's 1-based position in its stage. Mirrors the
/// web client's `displayVisit`; [sequence] is not the visit number.
final int visit;
final String stage;
final String stepStatus;
final ChangeCapture? capture;
bool get missing => capture == null;
/// Parses one step. [position] is the step's 1-based position among the
/// steps of its own stage, used when the step recorded no `control.visit`.
factory StageCapture.fromStep(JsonMap step, {int position = 1}) {
final raw = step['file_changes'];
return StageCapture(
sequence: _count(step['sequence']),
visit: _displayVisit(step, position),
stage: _stageName(step),
stepStatus: '${step['status'] ?? ''}'.trim(),
// A non-null but malformed value still records that a capture existed;
// only null is missing evidence. A value we cannot read is unavailable,
// never a fabricated empty capture that would claim "no changes".
capture: raw == null
? null
: raw is Map
? ChangeCapture.fromJson(Map<String, dynamic>.from(raw))
: ChangeCapture(
status: 'unavailable',
files: const [],
diagnostic: malformedCaptureDetail,
),
);
}
}
/// Groups a run's steps into stage/visit captures ordered by numeric sequence,
/// stable for ties. A step with a null `file_changes` still appears so its
/// missing evidence is visible next to the captures that did record.
List<StageCapture> stageCaptures(List<JsonMap> steps) {
final indexed = <({JsonMap step, int index})>[];
for (var i = 0; i < steps.length; i++) {
indexed.add((step: steps[i], index: i));
}
indexed.sort((a, b) {
final bySequence = _count(
a.step['sequence'],
).compareTo(_count(b.step['sequence']));
return bySequence != 0 ? bySequence : a.index.compareTo(b.index);
});
// The visit position is per stage, in the same sequence order (the web
// client's displayVisit), not the run-wide step ordinal.
final positions = <String, int>{};
final captures = <StageCapture>[];
for (final entry in indexed) {
final stage = _stageName(entry.step);
final position = (positions[stage] ?? 0) + 1;
positions[stage] = position;
captures.add(StageCapture.fromStep(entry.step, position: position));
}
return captures;
}
/// The recorded `control.visit` when positive, else the stage position.
int _displayVisit(JsonMap step, int position) {
final control = step['control'];
final recorded = control is Map ? control['visit'] : null;
if (recorded is num && recorded > 0) return recorded.toInt();
return position < 1 ? 1 : position;
}
String _stageName(JsonMap step) {
final name = '${step['stage'] ?? ''}'.trim();
return name.isEmpty ? 'stage' : name;
}
int _count(dynamic value) => value is num ? value.toInt() : 0;
@@ -0,0 +1,30 @@
/// The three recorded file-change kinds plus a safe fallback for future server
/// values. Ported from `web/src/changes.js` (and the Android client's
/// `ui/changes/RunChanges.kt`) so the Flutter client says the same words.
enum ChangeKind { added, modified, deleted, other }
/// Maps a server kind token to a [ChangeKind]. The token is trimmed and
/// lowercased; an unknown or blank token stays [ChangeKind.other] rather than
/// being guessed, so a future server value is shown read-only instead of
/// mislabelled.
ChangeKind changeKind(dynamic kind) =>
switch ('${kind ?? ''}'.trim().toLowerCase()) {
'added' => ChangeKind.added,
'modified' => ChangeKind.modified,
'deleted' => ChangeKind.deleted,
_ => ChangeKind.other,
};
/// The word a file's kind is named by in the list and the diff header.
String changeKindLabel(ChangeKind kind) => switch (kind) {
ChangeKind.added => 'added',
ChangeKind.modified => 'modified',
ChangeKind.deleted => 'deleted',
ChangeKind.other => 'changed',
};
/// The kind word as the viewer header shows it, first letter capitalised.
String changeKindTitle(ChangeKind kind) {
final label = changeKindLabel(kind);
return label.isEmpty ? label : label[0].toUpperCase() + label.substring(1);
}
@@ -0,0 +1,184 @@
import 'change_capture.dart';
import 'file_change.dart';
import 'run_changes.dart';
import 'unified_patch.dart';
/// The honest messages the viewer and its tests share. Spelled once, matching
/// the web client's `web/src/changes.js`.
const binaryDiffMessage =
'This is a binary file: the server recorded the change but has no textual '
'diff to show.';
const truncatedPatchNote =
'The server truncated this patch at its capture limit; the raw text is the '
'whole record.';
const noLineChangesMessage = 'no line changes recorded';
/// A step with no capture recorded no evidence; it does not prove the workspace
/// was unchanged.
const missingCaptureDetail =
'This visit recorded no change capture (a historical step, or a stage that '
'does not capture). That does not mean the workspace was unchanged.';
const pendingCaptureDetail =
'The capture runs after the stage finishes; nothing is recorded yet.';
const unavailableCaptureDetail =
'The workspace snapshot could not be compared, so no changes can be shown.';
const emptyCaptureDetail =
'The captured snapshots were identical: the workspace was unchanged.';
const partialCaptureDetail = 'Partial capture: some changes may be missing.';
/// The Changes section header's one-line summary: the observed file count, the
/// total `+N -M`, and the honest capture caveats.
String runChangesHeader(RunChanges changes) {
if (changes.unavailable) return 'Changes · capture unavailable';
if (changes.files.isEmpty) {
if (changes.pending) return 'Changes · capture pending';
if (changes.partial) return 'Changes · partial capture';
if (changes.stepsWithChanges == 0) {
return 'Changes · not recorded for this run';
}
if (changes.missingCaptures > 0) return 'Changes · capture incomplete';
return 'Changes · no changes observed';
}
final stat = changeStat(changes.added, changes.removed);
final count = changes.files.length;
final label = stat.isEmpty
? '$count ${count == 1 ? 'file' : 'files'} changed'
: '$count ${count == 1 ? 'file' : 'files'} changed · $stat';
if (changes.partial) return '$label · partial capture';
if (changes.missingCaptures > 0) return '$label · capture incomplete';
return label;
}
/// The honest one-line note under the header for a capture that is not
/// complete, or "" when it was.
String runChangesNote(RunChanges changes) {
if (changes.unavailable) {
return changes.diagnostic.isNotEmpty
? changes.diagnostic
: 'The workspace snapshot could not be compared; the changes below may '
'be incomplete.';
}
var out = '';
if (changes.partial) {
out = partialCaptureDetail;
final caveats = <String>[];
if (changes.skipped > 0) caveats.add('${changes.skipped} files skipped');
if (changes.omitted > 0) caveats.add('${changes.omitted} omitted');
final truncated = changes.files.where((file) => file.truncated).length;
if (truncated > 0) caveats.add('$truncated truncated');
if (caveats.isNotEmpty) out += ' (${caveats.join(', ')})';
if (changes.diagnostic.isNotEmpty) out += ' ${changes.diagnostic}';
}
if (changes.missingCaptures > 0) {
if (out.isNotEmpty) out += ' ';
out +=
'Missing capture: ${changes.missingCaptures} '
'${changes.missingCaptures == 1 ? 'stage did' : 'stages did'} not '
'record changes.';
}
return out.trim();
}
/// The file list's own summary line.
String changesListSummary(RunChanges changes) {
final count =
'${changes.files.length} '
'${changes.files.length == 1 ? 'file' : 'files'} changed';
final stat = changeStat(changes.added, changes.removed);
return stat.isEmpty ? count : '$count · $stat';
}
/// Why no change is listed: a pending capture, an unavailable one, a missing
/// capture or a recorded none.
String noChangeDetail(RunChanges changes) {
if (changes.pending) return pendingCaptureDetail;
if (changes.unavailable) return unavailableCaptureDetail;
if (changes.stepsWithChanges == 0) {
return 'This run recorded no change capture (a historical step, or a stage '
'that does not capture).';
}
return emptyCaptureDetail;
}
/// Why a file has no patch to render, in the entry's own recorded terms.
String patchUnavailableReason(FileChange file) {
if (file.truncated) {
return "The server truncated this file's patch at its capture limit; no "
'diff text was recorded.';
}
if (file.otherModeChange) {
return "Only the file's mode changed (${file.beforeMode ?? ''}→"
'${file.afterMode ?? ''}); the server recorded no text diff.';
}
return 'The server recorded this change without a patch.';
}
/// The tags shown beside a file row: traits that change how the entry must be
/// read, never a fabricated diff.
List<String> changeEntryTags(FileChange file) => file.tags;
/// The row's secondary line for an aggregated entry: which stage(s) changed it
/// and how to read it.
String changeRowMeta(FileChange file) {
var out = file.steps.isEmpty ? '' : 'changed by ${file.steps.join(' → ')}';
for (final tag in changeEntryTags(file)) {
out += '${out.isEmpty ? '' : ' · '}$tag';
}
if (file.modeChanged && !file.binary) {
out +=
'${out.isEmpty ? '' : ' · '}mode ${file.beforeMode ?? ''}→'
'${file.afterMode ?? ''}';
}
return out;
}
/// A compact per-entry line for a file row: stat, tags and mode, or the honest
/// no-line-change note. Content-driven; no fixed cell widths.
String changeFileMeta(FileChange file) {
final parts = <String>[];
final stat = changeStat(file.added, file.removed);
if (stat.isNotEmpty) parts.add(stat);
parts.addAll(file.tags);
if (file.modeChanged && !file.binary) {
parts.add('mode ${file.beforeMode ?? ''}→${file.afterMode ?? ''}');
}
return parts.isEmpty ? noLineChangesMessage : parts.join(' · ');
}
/// A compact capture summary, e.g.
/// `partial (2 files), 1 skipped, 3 omitted · Excluded protected files.`.
/// Blank parts are omitted; an entirely blank capture renders as "".
String fileChangesSummary(ChangeCapture capture) {
var text = capture.status;
if (capture.files.isNotEmpty) {
if (text.isNotEmpty) text += ' ';
text += '(${capture.files.length} files)';
}
if (capture.skipped > 0) {
if (text.isNotEmpty) text += ', ';
text += '${capture.skipped} skipped';
}
if (capture.omitted > 0) {
if (text.isNotEmpty) text += ', ';
text += '${capture.omitted} omitted';
}
if (capture.diagnostic.isNotEmpty) {
if (text.isNotEmpty) text += ' · ';
text += capture.diagnostic;
}
return text;
}
/// Filters changed filenames by a case-insensitive substring, preserving the
/// recorded order. A blank query keeps every file.
List<FileChange> filterFileChanges(Iterable<FileChange> files, String query) {
final needle = query.trim().toLowerCase();
final all = files.toList(growable: false);
if (needle.isEmpty) return all;
return all
.where((file) => file.path.toLowerCase().contains(needle))
.toList(growable: false);
}
/// The `N of M` position label a viewer can show for its open file.
String changePositionLabel(int index, int count) => '${index + 1} of $count';
@@ -0,0 +1,117 @@
import '../../../core/api_gateway.dart';
import 'change_kind.dart';
import 'unified_patch.dart';
/// One recorded file change, as the server's `file_changes.files[]` entry
/// describes it. A null/blank [patch] is a recorded fact (binary, truncated or
/// no text diff), never an invented empty diff.
class FileChange {
FileChange({
required this.path,
required this.kind,
String? patch,
this.binary = false,
this.truncated = false,
String? beforeMode,
String? afterMode,
this.steps = const [],
ParsedPatch? parsedPatch,
}) : patch = _nonBlank(patch),
beforeMode = _nonBlank(beforeMode),
afterMode = _nonBlank(afterMode),
// Aggregate copies pass their already-parsed patch through instead of
// re-parsing the same recorded bytes for every stage that touched a path.
parsedPatch = parsedPatch ?? parseUnifiedPatch(patch);
final String path;
final ChangeKind kind;
/// The server's unified patch verbatim, or null when it recorded none. This
/// exact string is what Copy patch puts on the clipboard, including any
/// trailing newline or truncated final line.
final String? patch;
final bool binary;
final bool truncated;
final String? beforeMode;
final String? afterMode;
/// Stage names that recorded a change to this path, in run order and deduped.
/// Empty for a single recorded entry; filled by [runChanges] aggregation.
final List<String> steps;
final ParsedPatch parsedPatch;
int get added => parsedPatch.added;
int get removed => parsedPatch.removed;
/// True when a patch the operator can read is present.
bool get hasPatch => !binary && patch != null;
/// True when the recorded permissions differ.
bool get modeChanged =>
beforeMode != null && afterMode != null && beforeMode != afterMode;
/// True when the recorded permissions differ and no content change explains
/// it. The server records no text diff for a mode-only change.
bool get otherModeChange =>
modeChanged && !binary && added == 0 && removed == 0;
List<String> get tags => [
if (binary) 'binary',
if (truncated) 'truncated',
if (otherModeChange) 'mode change',
];
FileChange withSteps(List<String> value) => FileChange(
path: path,
kind: kind,
patch: patch,
binary: binary,
truncated: truncated,
beforeMode: beforeMode,
afterMode: afterMode,
steps: List.unmodifiable(value),
parsedPatch: parsedPatch,
);
/// Parses one server file entry; null when it has no usable path. The
/// capture owns the decision to skip such an entry, so it is never rendered
/// as an anonymous row.
static FileChange? tryParse(dynamic value) {
if (value is! Map) return null;
final json = Map<String, dynamic>.from(value);
final path = _text(json['path']);
if (path.trim().isEmpty) return null;
return FileChange(
path: path,
kind: changeKind(json['kind']),
patch: json['patch'] is String ? json['patch'] as String : null,
binary: json['binary'] == true,
truncated: json['truncated'] == true,
beforeMode: _textOrNull(json['before_mode']),
afterMode: _textOrNull(json['after_mode']),
);
}
/// Parses a required file entry. Integration code normally receives files
/// from [ChangeCapture] or [runChanges]; this constructor is for a viewer
/// opened directly with one recorded entry.
factory FileChange.fromJson(JsonMap json) {
final file = tryParse(json);
if (file == null) {
throw const FormatException('A recorded file change needs a path.');
}
return file;
}
}
/// A value kept as itself when present, else null (`?:` over nullable fields).
String? _textOrNull(dynamic value) => value == null ? null : '$value';
String _text(dynamic value) => '${value ?? ''}';
/// A string kept only when it has non-whitespace content.
String? _nonBlank(String? value) {
if (value == null) return null;
return value.trim().isEmpty ? null : value;
}
@@ -0,0 +1,59 @@
/// Patch value objects produced by the unified-patch parser. Kept separate from
/// the parser so widgets import the smallest model they need.
library;
enum ChangeLineKind { context, add, remove }
class PatchLine {
const PatchLine({
required this.kind,
required this.text,
required this.oldLine,
required this.newLine,
this.noNewlineMarker = false,
});
final ChangeLineKind kind;
final String text;
final int oldLine;
final int newLine;
/// A `\ No newline at end of file` marker: shown verbatim, never numbered.
final bool noNewlineMarker;
}
class PatchHunk {
const PatchHunk({
required this.header,
required this.oldStart,
required this.oldCount,
required this.newStart,
required this.newCount,
required this.lines,
});
final String header;
final int oldStart;
final int oldCount;
final int newStart;
final int newCount;
final List<PatchLine> lines;
}
class ParsedPatch {
const ParsedPatch({
required this.raw,
required this.headerLines,
required this.hunks,
required this.added,
required this.removed,
});
final String raw;
final List<String> headerLines;
final List<PatchHunk> hunks;
final int added;
final int removed;
bool get isEmpty => hunks.isEmpty;
}
@@ -0,0 +1,102 @@
import '../../../core/api_gateway.dart';
import 'change_capture.dart';
import 'file_change.dart';
/// The run-level final-state aggregate of recorded file captures. Ported from
/// `web/src/changes.js` `runChanges`:
///
/// * a null `file_changes` is missing evidence (pending while the step is
/// running/waiting), never "no changes";
/// * a present capture with no files is a real, observed no-change;
/// * a path recorded by several visits is one entry, in first-seen order, whose
/// per-file facts come from the last recorded visit (the run's final state);
/// * capture counters and caveats describe every contributing step.
class RunChanges {
const RunChanges({
required this.files,
required this.stepsWithChanges,
required this.stepsPending,
required this.added,
required this.removed,
required this.partial,
required this.unavailable,
required this.pending,
required this.missingCaptures,
required this.skipped,
required this.omitted,
required this.diagnostic,
});
final List<FileChange> files;
final int stepsWithChanges;
final int stepsPending;
final int added;
final int removed;
final bool partial;
final bool unavailable;
final bool pending;
final int missingCaptures;
final int skipped;
final int omitted;
final String diagnostic;
}
RunChanges runChanges(List<JsonMap> steps) =>
runChangesFor(stageCaptures(steps));
/// The same aggregate over already-derived [stageCaptures], so a caller that
/// shows both the summary and the sections parses each capture only once.
RunChanges runChangesFor(List<StageCapture> visits) {
final entries = <String, FileChange>{};
var stepsWithChanges = 0;
var stepsPending = 0;
var partial = false;
var unavailable = false;
var missingCaptures = 0;
var skipped = 0;
var omitted = 0;
var truncatedSeen = false;
final diagnostics = <String>{};
for (final visit in visits) {
final capture = visit.capture;
if (capture == null) {
final status = visit.stepStatus.trim().toLowerCase();
if (status == 'running' || status == 'waiting') {
stepsPending++;
} else {
missingCaptures++;
}
continue;
}
stepsWithChanges++;
if (capture.unavailable) unavailable = true;
if (capture.partial) partial = true;
if (capture.diagnostic.isNotEmpty) diagnostics.add(capture.diagnostic);
skipped += capture.skipped;
omitted += capture.omitted;
for (final file in capture.files) {
if (file.truncated) truncatedSeen = true;
final existing = entries[file.path];
final names = existing == null ? <String>[] : [...existing.steps];
if (!names.contains(visit.stage)) names.add(visit.stage);
entries[file.path] = file.withSteps(names);
}
}
final files = entries.values.toList(growable: false);
return RunChanges(
files: List.unmodifiable(files),
stepsWithChanges: stepsWithChanges,
stepsPending: stepsPending,
added: files.fold(0, (sum, file) => sum + file.added),
removed: files.fold(0, (sum, file) => sum + file.removed),
partial: partial || truncatedSeen || omitted > 0,
unavailable: unavailable,
pending: stepsWithChanges == 0 && stepsPending > 0,
missingCaptures: missingCaptures,
skipped: skipped,
omitted: omitted,
diagnostic: diagnostics.join(' '),
);
}
@@ -0,0 +1,239 @@
/// Parses a server-recorded unified patch into hunks, lines and the true
/// `+N -M` stat. Ported from `web/src/changes.js` so the Flutter viewer numbers
/// and groups lines exactly like the browser and Android clients.
///
/// The server builds these patches with the Go `internal/filediff` writer: a
/// standard `---`/`+++` header, optional metadata, `@@ -a,b +c,d @@` hunk
/// headers and a ` `/`+`/`-` body. Anything unrecognised before the first hunk
/// is carried verbatim in [ParsedPatch.headerLines]; a truncated tail or exotic
/// marker inside a hunk stays an unnumbered context line. The raw patch is
/// always retained byte-for-byte so Copy patch never rewrites the record.
library;
export 'patch_models.dart';
import 'patch_models.dart';
const _emptyPatch = ParsedPatch(
raw: '',
headerLines: [],
hunks: [],
added: 0,
removed: 0,
);
/// Parses a patch with the same total behaviour as the browser: a blank or
/// absent patch is an empty result, never a fabricated diff.
ParsedPatch parseUnifiedPatch(dynamic patch) {
final text = patch == null ? '' : '$patch';
if (text.trim().isEmpty) return _emptyPatch;
final headers = <String>[];
final hunks = <PatchHunk>[];
_HunkBuilder? current;
for (final line in text.split('\n')) {
final start = _parseHunkHeader(line);
if (start != null) {
if (current != null) hunks.add(current.build());
current = _HunkBuilder(line, start);
} else if (line.startsWith('--- ') || line.startsWith('+++ ')) {
// An aggregated entry can contain one complete patch per contributing
// stage. A new file header closes the preceding hunk instead of becoming
// an unnumbered context line inside it.
if (current != null) {
hunks.add(current.build());
current = null;
}
headers.add(line);
} else if (current == null) {
headers.add(line);
} else {
current.lines.add(current.parseBody(line));
}
}
if (current != null) hunks.add(current.build());
var added = 0;
var removed = 0;
for (final hunk in hunks) {
for (final line in hunk.lines) {
if (line.kind == ChangeLineKind.add) {
added++;
} else if (line.kind == ChangeLineKind.remove) {
removed++;
}
}
}
return ParsedPatch(
raw: text,
headerLines: headers,
hunks: hunks,
added: added,
removed: removed,
);
}
/// Mutable accumulator carrying the running old/new counters so each body line
/// is numbered in one pass.
class _HunkBuilder {
_HunkBuilder(this.header, _HunkStart start)
: oldStart = start.oldStart,
oldCount = start.oldCount,
newStart = start.newStart,
newCount = start.newCount,
oldLine = start.oldStart,
newLine = start.newStart;
final String header;
final int oldStart;
final int oldCount;
final int newStart;
final int newCount;
final List<PatchLine> lines = [];
int oldLine;
int newLine;
PatchHunk build() => PatchHunk(
header: header,
oldStart: oldStart,
oldCount: oldCount,
newStart: newStart,
newCount: newCount,
lines: List.unmodifiable(lines),
);
PatchLine parseBody(String line) {
if (line.startsWith('+')) {
return PatchLine(
kind: ChangeLineKind.add,
text: line.substring(1),
oldLine: 0,
newLine: newLine++,
);
}
if (line.startsWith('-')) {
return PatchLine(
kind: ChangeLineKind.remove,
text: line.substring(1),
oldLine: oldLine++,
newLine: 0,
);
}
if (line.startsWith('\\')) {
return PatchLine(
kind: ChangeLineKind.context,
text: line,
oldLine: 0,
newLine: 0,
noNewlineMarker: true,
);
}
if (line.startsWith(' ')) {
return PatchLine(
kind: ChangeLineKind.context,
text: line.substring(1),
oldLine: oldLine++,
newLine: newLine++,
);
}
if (line.isEmpty) {
return PatchLine(
kind: ChangeLineKind.context,
text: '',
oldLine: oldLine++,
newLine: newLine++,
);
}
// A truncated tail or an unexpected marker: keep the text, do not number it.
return PatchLine(
kind: ChangeLineKind.context,
text: line,
oldLine: 0,
newLine: 0,
);
}
}
class _HunkStart {
const _HunkStart(this.oldStart, this.oldCount, this.newStart, this.newCount);
final int oldStart;
final int oldCount;
final int newStart;
final int newCount;
}
_HunkStart? _parseHunkHeader(String line) {
if (!line.startsWith('@@')) return null;
final end = line.indexOf('@@', 2);
if (end < 0) return null;
final ranges = _tokenizeRanges(line.substring(2, end));
return ranges == null
? null
: _HunkStart(ranges[0], ranges[1], ranges[2], ranges[3]);
}
List<int>? _tokenizeRanges(String body) {
final plus = body.indexOf('+');
final old = plus == -1 ? body : body.substring(0, plus);
final next = plus == -1 ? '' : body.substring(plus + 1);
if (old.isEmpty || next.isEmpty) return null;
final oldRange = _parseRange(old);
if (oldRange == null) return null;
final newRange = _parseRange(next);
if (newRange == null) return null;
return [oldRange[0], oldRange[1], newRange[0], newRange[1]];
}
List<int>? _parseRange(String text) {
var trimmed = text.trim();
if (trimmed.startsWith('-') || trimmed.startsWith('+')) {
trimmed = trimmed.substring(1);
}
if (trimmed.isEmpty) return null;
final comma = trimmed.indexOf(',');
final startText = (comma == -1 ? trimmed : trimmed.substring(0, comma))
.trim();
final start = _intOrNull(startText);
if (start == null) return null;
final countText = (comma == -1 ? '' : trimmed.substring(comma + 1)).trim();
final count = countText.isEmpty ? 1 : _intOrNull(countText);
if (count == null) return null;
return [start, count];
}
int? _intOrNull(String text) =>
RegExp(r'^[+-]?\d+$').hasMatch(text) ? int.tryParse(text) : null;
/// The widest line number in a hunk, so its gutter lines up across every row.
int gutterWidth(PatchHunk hunk) {
var widest = 0;
for (final line in hunk.lines) {
if (line.oldLine > widest) widest = line.oldLine;
if (line.newLine > widest) widest = line.newLine;
}
return '${widest < 1 ? 1 : widest}'.length;
}
/// One gutter number padded to [width]; 0 means no number on that side.
String gutterText(int value, int width) =>
value > 0 ? '$value'.padLeft(width) : ' ' * width;
/// The gutter symbol one line kind is drawn with (`+`/`-`/space).
String diffLineSymbol(ChangeLineKind kind) => switch (kind) {
ChangeLineKind.add => '+',
ChangeLineKind.remove => '-',
ChangeLineKind.context => ' ',
};
/// The `+N -M` stat, or "" when both counts are zero. Shared by every renderer.
String changeStat(int added, int removed) {
var out = '';
if (added > 0) out += '+$added';
if (removed > 0) {
if (out.isNotEmpty) out += ' ';
out += '-$removed';
}
return out;
}
@@ -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 = nativeDiffText(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,151 @@
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 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;
}
/// Patch text inherits the host's typography, including its font and scaler.
/// A diff is not an exception to the native-defaults requirement.
TextStyle nativeDiffText(TextStyle base) => base;
/// Native semantic colours, never a bespoke diff palette. The recorded +/-
/// markers carry meaning independently of colour. No background tint is added.
({Color text, Color? background}) diffLineColors(
BuildContext context,
ChangeLineKind kind,
) {
return switch (kind) {
ChangeLineKind.add => (
text: usesCupertino(context)
? CupertinoColors.systemGreen.resolveFrom(context)
: Theme.of(context).colorScheme.primary,
background: null,
),
ChangeLineKind.remove => (
text: usesCupertino(context)
? CupertinoColors.destructiveRed.resolveFrom(context)
: Theme.of(context).colorScheme.error,
background: null,
),
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 = nativeDiffText(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 = nativeDiffText(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 = nativeDiffText(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,
),
);
}
}