import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import '../../features/changes/domain/file_change.dart'; import '../../features/changes/widgets/file_diff_page.dart'; import 'detached_platform.dart'; import 'detached_route.dart'; import 'detached_window_body.dart'; /// The diff a window was handed: its files and the one it opened on. typedef DetachedDiffContent = ({List files, int index}); /// Reads the hand-over [json] (`{"files": [...], "index": n}`); null when it /// holds no file. DetachedDiffContent? decodeDetachedDiff(String? json) { if (json == null) return null; try { final value = jsonDecode(json); if (value is! Map) return null; final raw = value['files']; final files = [ if (raw is List) for (final entry in raw) ?FileChange.fromHandover(entry), ]; if (files.isEmpty) return null; final index = value['index']; return ( files: files, index: index is int ? index.clamp(0, files.length - 1) : 0, ); } on FormatException { return null; } } /// A diff alone in a detached window. Its files are in memory only, handed /// over through the platform (see [DetachedPlatform.take]); there is nothing /// to read from the server. class DetachedDiff extends StatefulWidget { const DetachedDiff({ super.key, required this.token, required this.platform, required this.window, }); final String token; final DetachedPlatform platform; final DetachedWindowControls window; @override State createState() => _DetachedDiffState(); } class _DetachedDiffState extends State { late final Future _content = widget.platform .take(widget.token) .then(decodeDetachedDiff); @override void initState() { super.initState(); unawaited(_content.then(_retitle)); } void _retitle(DetachedDiffContent? content) { final files = content?.files; widget.window.setTitle(switch (files) { null || [] => 'Diff', [final file] => file.path.split('/').last, _ => '${files.length} files changed', }); } @override Widget build(BuildContext context) => FutureBuilder( future: _content, builder: (context, snapshot) { if (snapshot.connectionState != ConnectionState.done) { return const Material(child: SizedBox.expand()); } final content = snapshot.data; if (content == null) { return const Material( child: Center(child: Text('This diff is no longer available.')), ); } return FileDiffPage( files: content.files, initialIndex: content.index, inWindow: true, actions: [ DetachedBringBackButton( onPressed: () => widget.window.bringBack( DetachedKind.diff, widget.token, files: [for (final file in content.files) file.toJson()], initialIndex: content.index, ), ), ], ); }, ); }